sockaddr_in和sockaddr的区别

sockaddr_in在头文件/usr/include/netinet/in.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/* Structure describing an Internet socket address.  */
struct sockaddr_in
{
__SOCKADDR_COMMON (sin_);
in_port_t sin_port; /* Port number. */
struct in_addr sin_addr; /* Internet address. */

/* Pad to size of `struct sockaddr'. */
unsigned char sin_zero[sizeof (struct sockaddr) -
__SOCKADDR_COMMON_SIZE -
sizeof (in_port_t) -
sizeof (struct in_addr)];
};
or
struct  sockaddr_in {
short  int  sin_family;                 /* Address family */
unsigned  short  int  sin_port;       /* Port number */
struct  in_addr  sin_addr;              /* Internet address */
unsigned  char  sin_zero[8];         /* Same size as struct sockaddr */
};

 
struct   in_addr   {
union {
           struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
           struct { u_short s_w1,s_w2; } S_un_w;
           u_long S_addr; 
           } S_un;
            #define s_addr  S_un.S_addr
 };
  • 组成包含协议家族、端口、地址、填充
  • 端口和地址,需要是网络字节序号
  • inet_addr(“127.0.0.1”)把字符串点分十进制地址按照网络字节序转换为4字节的地址

sockaddr为通用的socket地址

1
2
3
4
struct sockaddr {    
unsigned short sa_family; // address family, AF_INET
char sa_data[14]; // 14 bytes of protocol address
};
  • bind、connect、recv、send等socket参数使用的就是这个结构体