5.4. connect () --- hey, are you?
Now we assume you are a telnet program. Your USER command you get the file descriptor of the socket. You followed the command to call socket (). Next, your user will tell you to connect to "10.12.110.57" through port 23 (Standard telnet port ". What do you do? Fortunately, you are reading the connect ()-how to connect to a remote host chapter. You don't want to disappoint your users.
The following is his prototype:
# Include <sys/types. h>
# Include <sys/socket. h>
Connect (intsockfd, struct sockaddr * serv_addr, int addrlen );
Sockfd is the socket file descriptor returned by the system to call socket. Serv_addr is a struct sockaddr that contains IP addresses and ports. Addrlen is the length of this structure.
We still use the parameters returned by the getaddrinfo () function.
The following example shows how to connect to port 3490 of www.2cto.com:
Struct addrinfohints, * res;
Int sockfd;
Memset (& hints, 0, sizeof (hints ));
Hints. ai_family = AF_UNSPEC;
Hints. ai_socktype = SOCK_STREAM;
Getaddrinfo (www.2cto.com, "3490", & hints, & res );
// Make a socket:
Sockfd = socket (res-> ai_family, res-> ai_socktype, res-> ai_protocol );
// Connect!
Connect (sockfd, res-> ai_addr, res-> addrlen)
At the same time, you may see that I did not call bind (). Because I don't care about the local port number. I only care about where I am going. The kernel will select an appropriate port number for me, and the information will be automatically obtained from the locations we connect. No worries.
From the column xiaobin_HLJ80