Previous: http://www.bkjia.com/kf/201112/115217.html
5.3. bind () --- On which port?
Once you have a socket, you may need to associate the socket with a certain port on the machine. (If you want to use listen () to listen to data on certain ports, This is a necessary step-for example, starting a multiplayer online game and telling you to connect to port 3490 of 192.168.5.10) the port number is the socket descriptor of a process from a data packet that is received by the kernel. If you only want to use connect () (because you are a client, not a server), this step is unnecessary. But in any case, please continue reading.
The following is his prototype:
# Include <sys/types. h>
# Include <sys/socket. h>
Int bind (intsockfd, struct sockaddr * my_addr, int addrlen );
Sockfd is the file descriptor returned by calling socket. My_addr is a pointer to the data structure struct sockaddr, which stores your address (that is, the port and IP address) information. Addlen is the length of this address (struct socketaddr.
Isn't it easy? Let's look at the example:
Struct addrinfohints, * res;
Int sockfd;
// First, load upaddress structs with getaddrinfo ():
Memset (& hints, 0, sizeof (hints ));
Hints. ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever
Hints. ai_socktype = SOCK_STREAM; // TCP
Hints. ai_flags = AI_PASSIVE; // fill in myIP for me
Getaddrinfo (NULL, "3490", & hints, & res );
// Make a socket
Sockfd = socket (res-> ai_family, res-> ai_socktype, res-> ai_protocol );
// Bind it to theport we passed in to getaddrinfo ():
Bind (sockfd, res-> ai_addr, res-> ai_addrlen );
By using the AI_PASSIVE flag, I told the program to bind to the IP address of the host running it. If you want to bind to a specific local IP address, delete AI_PASSIVE and assign it to the first parameter of the getaddrinfo () function.
If bind () is returned,-1 indicates an error.
The old code is omitted...
From the column xiaobin_HLJ80