Forming Internet (IPv4) Socket Addresses
The
most commonly used address family under Linux is the AF_INET family.
This gives a socket an IPv4 socket address to allow it to communicate
with other hosts over a TCP/IP network. The include file that defines
the structure sockaddr_in is defined by the C language statement:
#include <netinet/in.h>
Example
Listing
2.7 shows an example of the structure sockaddr_in which is used for
Internet addresses. An additional structure in_addr is also shown,
because the sockaddr_in structure uses it in its definition.
Listing 2.7: The sockaddr_in Structure
struct sockaddr_in {
sa_family_t sin_family; /* Address Family */
uint16_t sin_port; /* Port number */
struct in_addr sin_addr; /* Internet address */
unsigned char sin_zero[8]; /* Pad bytes */
};
struct in_addr {
uint32_ t s_ addr; /* Internet address */
};
Listing 2.7 can be described as follows:
- The sin_family member occupies the same storage area that sa_family does in the generic socket definition. The value of sin_family is initialized to the value of AF_INET.
- The sin_port member defines the TCP/IP port number for the socket address. This value must be in network byte order (this will be elaborated upon later).
- The sin_addr member is defined as the structure in_addr, which holds the IP number in network byte order. If you examine the structure in_addr, you will see that it consists of one 32- bit unsigned integer.
- Finally, the remainder of the structure is padded to 16 bytes by the member sin_zero[8] for 8 bytes. This member does not require any initialization and is not used.
Now turn your attention to Figure 2.3 to visualize the physical layout of the address.
Figure 2.3:
Here is the structure sockaddr_in physical layout.
In
Figure 2.3, you see that the sin_port member uses two bytes, whereas
the sin_addr member uses four bytes. Both of these members show a tag on
them indicating that these values must be in network byte order.
TIP
Information about IPv4 Internet addresses can be obtained by examining the ip(4) man page.
No comments:
Post a Comment