struct sockaddr {
unsigned short sa_family;/* address family, af_xxx */
char sa_data [14]; /* 14-byte Protocol address */
};
the above is a general socket address, specific to the internet socket, with the following structure, the two types can be converted.
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]; /* the same length as struct sockaddr */
};
Struct in_addr is a 32-bit IP address.
struct in_addr {
unsigned long s_addr;
};
Yes
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;
};
Use u_long htonl (u_long hostlong); to convert the host's byte sequence to the TCP/IP network's byte sequence.
Use u_short htons (u_short hostshort) to convert host byte to TCP/IP network byte.
Inet_addr () is to convert a point-based IP address (such as 192.168.0.1) to the 32-bit IP address (0xc0a80001) required in the preceding structure ).
The common usage is:
Int sockfd;
Struct sockaddr_in my_addr;
Sockfd = socket (af_inet, sock_stream, 0);/* do some error checks! */
My_addr.sin_family = af_inet;/* Host byte order */
My_addr.sin_port = htons (myport);/* short, network byte order */
My_addr.sin_addr.s_addr = inet_addr ("192.168.0.1 ");
Bzero (& (my_addr.sin_zero), 8);/* zero the rest of the struct */
/* Do not forget to perform an error check for BIND :*/
BIND (sockfd, (struct sockaddr *) & my_addr, sizeof (struct sockaddr ));