套接字编程常遇到这几个数据结构:sockaddr、sockaddr_in和in_addr,很容易让人范糊涂。现将这几个结构的定义摘录于下:、
/* * Structure used by kernel to store most * addresses. */ struct sockaddr { u_short sa_family; /* address family */ char sa_data[14]; /* up to 14 bytes of direct address */ }; /* * Socket address, internet style. */ struct sockaddr_in { short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; }; // // IPv4 Internet address // This is an 'on-wire' format structure. // typedef struct in_addr { union { struct { UCHAR s_b1,s_b2,s_b3,s_b4; } S_un_b; struct { USHORT s_w1,s_w2; } S_un_w; ULONG S_addr; } S_un; #define s_addr S_un.S_addr /* can be used for most tcp & ip code */ #define s_host S_un.S_un_b.s_b2 // host on imp #define s_net S_un.S_un_b.s_b1 // network #define s_imp S_un.S_un_w.s_w2 // imp #define s_impno S_un.S_un_b.s_b4 // imp # #define s_lh S_un.S_un_b.s_b3 // logical host } IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;
首先sockaddr是通用的套接字地址,具体代表的含义要看sa_family成员变量,sockaddr_in是针对internet设计的数据结构,如果sa_family是AF_INET,可直接将sockaddr指针转换成sockaddr_in指针。in_addr仅用于表示IPV4网络地址,也就是常说的IP地址。