Unix Network Programming Episode 30

With TCP, calling bind lets us specify a port number, an IP address, both, or neither.

  • Servers bind their well-known port when they start. If a TCP client or server does not do this, the kernel chooses an ephemeral port for the socket when either connect or listen is called. It is normal for a TCP client to let the kernel choose an ephemeral port, unless the application requires a reserved port (Figure 2.10(See 7.2.9)), but it is rare for a TCP server to let the kernel choose an ephemeral port, since servers are known by their well-known port.
  • A process can bind a specific IP address to its socket. The IP address must belong to an interface on the host. For a TCP client, this assigns the source IP address that will be used for IP datagrams sent on the socket. For a TCP server, this restricts the socket to receive incoming client connections destined only to that IP address.
    Normally, a TCP client does not bind an IP address to its socket. The kernel chooses the source IP address when the socket is connected, based on the outgoing interface that is used, which in turn is based on the route required to reach the server (p. 737 of TCPv2).

With IPv4, the wildcard address is specified by the constant INADDR_ANY, whose value is normally 0. This tells the kernel to choose the IP address. We saw the use of this in Figure 1.9(See 7.1.5) with the assignment

struct sockaddr_in servaddr;
servaddr.sin_addr.s_addr = htonl (INADDR_ANY); /* wildcard */

While this works with IPv4, where an IP address is a 32-bit value that can be represented as a simple numeric constant (0 in this case), we cannot use this technique with IPv6, since the 128-bit IPv6 address is stored in a structure. (In C we cannot represent a constant structure on the right-hand side of an assignment.) To solve this problem, we write

struct sockaddr_in6 serv;
serv.sin6_addr = in6addr_any; /* wildcard */

The system allocates and initializes the in6addr_any variable to the constant IN6ADDR_ANY_INIT. The header contains the extern declaration for in6addr_any.

‘listen’ Function

The listen function is called only by a TCP server and it performs two actions:

1.When a socket is created by the socket function, it is assumed to be an active socket, that is, a client socket that will issue a connect. The listen function converts an unconnected socket into a passive socket, indicating that the kernel should accept incoming connection requests directed to this socket. In terms of the TCP state transition diagram (Figure 2.4(See 7.2.6)), the call to listen moves the socket from the CLOSED state to the LISTEN state.
2.The second argument to this function specifies the maximum number of connections the kernel should queue for this socket.

你可能感兴趣的:(Unix,Network,Programming)