Reputation: 313
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
int main(int argc, char **argv) {
unsigned long addr;
unsigned long net_id;
struct sockaddr_in address;
addr = inet_addr("192.168.50.25");
// prints 1932A8C0 in host byte-order which in this case is little-endian
printf("IP-Address in Host-Byte Order: %08X\n", (unsigned int) addr);
// zero the struct out
memset(&address, 0, sizeof address);
// copy address into the struct
memcpy(&address.sin_addr.s_addr, &addr, sizeof addr);
// inet_netof returns the network ID in host byte order
net_id = inet_netof(address.sin_addr);
// prints 00C0A832 Why not 0032A8C0?
printf("Network ID in Host-Byte-Order: %08X\n", (unsigned int) net_id);
return 0;
}
I have a little-endian machine so the host byte-order is little endian. The IP-Address 192.168.50.25 is 0x1932A8C0 in host-byte order. This is obvious to me.
Now, the inet_netof function returns the networkID of the address 192.168.50.25 in host-byte-order. The output of that is 0x00C0A832. This is confusing me. This does not really look like little-endianness to me. If I would convert that into dotted decimal it would be: 0.192.168.50.
I would have assumed the network-ID would look like this in little-endian: 0.50.168.192 or 0x0032A8C0 hexadecimal instead inet_netof() returns 0x00C0A832.
Why does inet_netof() return 0x00C0A832 instead of 0x0032A8C0?
Upvotes: 1
Views: 1161
Reputation: 70931
inet_addr()
returns network byte order.inet_netof()
returns host byte order, that is Little-endian. As your machine is Little-endian the bytes returned by inet_netof()
are in revers order, compared to the output of what inet_addr()
returned.For reference please see man 3 inet
.
Upvotes: 1
Reputation: 96266
0x00C0A832
is, as you said, 0.192.168.50
.
It's in host byte order, and the correct value.
The phrasing in the documentation is a bit vague("returns the network number part of the Internet Address in"), but if I check an implementation, there's a right shift, so everything seems to be fine.
Upvotes: 1