IPPROTO_IP vs IPPROTO_TCP/IPPROTO_UDP

55,007

Documentation for socket() on Linux is split between various manpages including ip(7) that specifies that you have to use 0 or IPPROTO_UDP for UDP and 0 or IPPROTO_TCP for TCP. When you use 0, which happens to be the value of IPPROTO_IP, UDP is used for SOCK_DGRAM and TCP is used for SOCK_STREAM.

In my opinion the clean way to create a UDP or a TCP IPv4 socket object is as follows:

int sock_udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
int sock_tcp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

The reason is that it is generally better to be explicit than implicit. In this specific case using 0 or worse IPPROTO_IP for the third argument doesn't gain you anything.

Also imagine using a protocol that can do both streams and datagrams like sctp. By always specifying both socktype and protocol you are safe from any ambiguity.

Share:
55,007

Related videos on Youtube

Steven Lu
Author by

Steven Lu

Play a multitouch HTML5 Tetris clone -- http://htmltetris.com (Interesting note about this site. It used to be my site, then Tetris Co. sent me a cease and desist, then I forgot about it, and now it’s back: someone brought it back and put MY code back on the site.) A huge fan of tmux and vim.

Updated on July 09, 2022

Comments

  • Steven Lu
    Steven Lu almost 2 years

    I'm having some trouble finding documentation on what the distinction between these settings for the third argument to socket is. I know about TCP and UDP and their differences and also that IP is one layer up (down?) on the stack... My UDP code seems to work the same whether I set it to IPPROTO_IP or IPPROTO_UDP.