Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the need of separate address structure in sockaddr_in?

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];  
};
like image 587
sujin Avatar asked Sep 22 '13 16:09

sujin


1 Answers

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.

like image 106
Crowman Avatar answered Oct 13 '22 10:10

Crowman