简体   繁体   中英

Linux raw socket - endianness in ip header

I would like to confirm that any value in a ip header bigger than one byte (short, int.. Or their alternative int16_t..) should be converted to big endian using ntohs/ntohl etc to send over the wire.

Did The kernel managed that under the hood when normal socket were used or another technic was used?

It is quite of a mess since some functions, like getting the ip address of the interface with ioctl seem to already put the data in a big endian fashion when casted to sockaddr_in*. It output my address like 36.2.168.192 (with printf's %d) but the ifreq output it like 192.168.2.36

code

int addr = ((struct sockaddr_in *)(&ifr.ifr_addr))->sin_addr.s_addr;
printf("%d %d %d %d ", (addr >> 24) & 255 , (addr >> 16) & 255,(addr >> 8) & 255, (addr) & 255);

gives me my ip address in the reverse order

whereas using

for (int _x = 0; x < 14; ++_x) {
        printf("%d ", ifr.ifr_ifru.ifru_addr.sa_data[_x] );
}

will give me some zeros the ip address in the right order (192.168.2.36) followed by zeros. Waw.. I am lost.

Quite of a jungle if you ask me.

QUESTION

what to convert to big endian and what not to ?

Best not to think of it as big-endian or little-endian, but rather host order (which may be either) and network order (which is big-endian). You are correct that in the IP standard, every field is in network order. You should use the ntohs and ntohl functions for converting network to host order, and the htons and htonl functions for converting host to network order. That way your code will compile right on a big-endian machine too.

An IP address is normally stored internally in network order, in which case it can be converted to/from presentation format using inet_pton and inet_ntop . You thus don't normally need to play around with the storage format of these addresses unless you are manually applying netmasks etc. If you are doing this, the octets (bytes to you and me) are stored in the natural order, ie 111.222.33.44 is stored in the order 111, 222, 33 and 44. If you think about it, that's a big-endian order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM