This is the internet(IPv4) socket address structure defined in netinet/in.h
struct sockaddr_in {
uint8_t sin_len;
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
struct in_addr {
in_addr_t s_addr;
};
Here what is the need of separate structure only for address field.
Why can't we use following structure ?
struct sockaddr_in {
uint8_t sin_len;
sa_family_t sin_family;
in_port_t sin_port;
in_addr_t sin_addr;
char sin_zero[8];
};
It's for historical reasons. In the early days of socket programming, struct in_addr
contained a union
of various structures so you could get to the individual bytes. This union
became unnecessary when subnetting and classless addressing came along, but switching out the struct
for a simple unsigned long
would break a lot of code, so it just stayed that way.
If you're interested in network programming and you haven't yet picked up a copy of UNIX Network Programming then I'd highly recommend doing so, it's a goldmine for little details like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With