Binding a Socket
For a server to accept client connections, it must be bound to a network address within the system. The following code demonstrates how to bind a socket that has already been created to an IP address and port. Client applications use the IP address and port to connect to the host network.
To bind a socket
The sockaddr structure holds information regarding the address family, IP address, and port number.
Call the bind function, passing the created socket and sockaddr structure returned from the getaddrinfo function as parameters. Check for general errors.
// Setup the TCP listening socket
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
Once the bind function is called, the address information returned by the getaddrinfo function is no longer needed. The freeaddrinfo function is called to free the memory allocated by the getaddrinfo function for this address information.
freeaddrinfo(result);
Next Step: Listening on a Socket
Related topics