Reputation: 106
To create a packet socket
, following socket()
function call is used (socket type and protocol may be different):
socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))
And to create a stream socket
, following call is used:
socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
My question is why use htons()
to specify protocol when creating a packet socket
and not when creating socket of AF_INET or AF_INET6
family? Why not use
socket(AF_INET, SOCK_XXX, htons(IPPROTO_XXX))
to create a STREAM or DATAGRAM socket as used when creating a packet socket
or vice-versa. What is different with the use of the protocols in the two calls to socket() function as both the calls are used to create sockets, one for packet socket and the other for socket at TCP level?
Upvotes: 1
Views: 1791
Reputation: 12357
First, like most other network parameters that are passed to the kernel (IP addresses, ports, etc), the parameters are passed in their "on-the-wire" format so that underlying software doesn't need to manipulate them before comparing/copying/transmitting/etc. (For comparison, consider that AF_PACKET
and SOCK_RAW
are parameters to the kernel itself -- hence "native format" is appropriate -- while the ETH_P_xxx
value is generally for "comparison with incoming packets"; it just so happens that ETH_P_ALL
is a special signal value saying 'capture everything'.)
Second, interpretation of the protocol is potentially different by address family. A different address family could choose to interpret the protocol in whatever form made sense for it. It just so happens that Ethernet and IP have always used big-endian (and were important/ubiquitous enough that big-endian came to be called network order).
Third, the protocol number in the AF_INET
world (i.e. Internet Protocol) only occupies a single byte so it doesn't make sense to specify a byte-ordering.
Upvotes: 2