In the process of establishing the socket communication, the address plays a key role in the design of TCP/IP network program, must have a clear understanding of the address structure of the socket.
The address data structure of TCP/IP.
struct SOCKADDR {
U_short safamily;/* address Family, af_xxx*/
Specific protocol address for Char sa_data[14];/*14 byte
}
The 14-byte sa_data varies with the protocol. In the TCP/IP protocol family, the address data structure is:
struct in_addr{
U_long s_addr;/*32 bit IP address, network byte order * *
};
struct sockaddr_in{
Short sin_family; /*af_inet*/
U_short Sin_short; /*16 bit port number, network byte order *
struct IN_ADDR sin_addr; /*32 bit IP address, network byte order * *
Char Sin_zero[8]; /* Not used * *
}
Network byte order is a set of data representation format in TCP/IP, which is independent of specific CPU type, operating system, etc., so that data can be interpreted correctly when transmitting between different hosts. The two functions converted from host byte order to network byte order are as follows: Htons (): Converts 16-bit host byte order data to network byte order htonl (): Converts 32-bit host byte-order data to network byte order the corresponding function to convert the network byte order to host byte order is:
Ntohs (): Converts 16-bit network byte-order data to host byte Order Ntohl (): Converts 32-bit network byte order data to host byte order because of the length of the various socket address structures, the TCP/IP address family address length is 8 bytes, The Xns address is 14 bytes, the UNIX address is indeterminate, up to 110 bytes long, so it cannot be defined in a uniform format, and the length of the socket address needs to be explicitly specified in the bind () call.
When the bind () parameter is invalid or the port is already in the other program, the function returns-1, indicating that the socket name failed.