I haven't read the Linux network programming book for a long time. Today I see the key part: TCP socket. Next let's take a look at the socket address Structure
Linux sockets support multiple protocols. Each protocol uses a different address structure. In the header file <Linux/socket. h>, there is an old-fashioned structure (this is not enough currently ).
StructSockaddr
{
Unsigned ShortSa_family;// The protocol cluster address type of the socket, and the TCP/IP protocol for IPv4 address type is af_inet
CharSa_data [14];// Store the specific Protocol address
};
The following sockaddr_in structure is generally used (used to set/obtain address information ):
StructSockaddr_in
{
Unsigned ShortSin_len; // IPv4 address Length
Short IntSin_family; // indicates the protocol cluster. In TCP socket programming, it can only be af_inet.
Unsigned ShortSin_port; // The storage port number (in the byte sequence of the network). The data type is a 16-character unsigned integer type.
StructIn_addr sin_addr; // storage IP address. The IP address is an in_add struct (the structure is shown below)
Unsigned CharSin_zero [8]; // reserved NULL bytes to keep sockaddr and sockaddr_in data structures of the same size
};
Here, the data structure of in_addr is as follows:
StructIn_addr
{
Unsigned LongS_addr; // store IP addresses in byte order.
};
In the currently popular IPv6, the socket address structure uses the following structure (the members in the structure are ordered ):
# Define sin6_len
StructSockaddr_in6
{
Unsigned Short IntSin6_len; // IPv6 structure length. It is an unsigned 8 Integer, indicating that 128 is the IPv6 address length.
Short IntSin6_family; // address type af_inet6
Unsigned Short Int sin6_port; // The storage port number, in bytes.
Unsigned Short IntSin6_flowinfo; // The 24-bit low is the traffic label, followed by the 4-bit priority mark, and the remaining four are retained.
StructIn6_addr sin6_addr; // IPv6 address, in bytes
};
StructIn6_addr
{
Unsigned LongS6_addr; // 128-bit IPv6 address, in bytes
};
Let's take an example to better illustrate the application of these struct structures. The following uses IPv4 as an example:
StructSockaddr_in mysock;
Mysock. sin_family = af_inet;// TCP address Structure
Mysock. sin_port = htons (3490 );// Byte sequence Conversion Function (I will introduce it later)
Mysock. sin_addr.s_addr = inet_addr ("166.111.160.10");// Set the IP address
Bzero (& (mysock. sin_zero), 8 );// Set sin_zero to 8-bit reserved bytes
// If mysock. sin_addr.s_addr = inaddr_any, no IP address is specified (used for serverProgram)
Some basic functions:
IP address conversion functions: inet_addr () and inet_ntoa ()
Format:
Unsigned LongInet_addr (Const Char* CP );
Char* Inet_ntoa (StructIn_addr in );