The bind function associates a local name (address and port) with a socket.
This is typically done before a socket is connected to establish a connection or to make it ready to receive incoming datagrams.
Syntax
int bind(
[in] SOCKET s,
[in] const sockaddr *name,
[in] int namelen
);
Parameters
s [in]
A descriptor identifying an unconnected socket.
name [in]
A pointer to a sockaddr structure that specifies the address and port to associate with the socket.
For IPv4, this is a sockaddr_in structure. For IPv6, this is a sockaddr_in6 structure.
namelen [in]
The size, in bytes, of the structure pointed to by the name parameter.
Return Value
If no error occurs, bind returns zero. Otherwise, a Windows Sockets error code is returned.
WSAEADDRINUSE: The requested address is already in use.
WSAEADDRNOTAVAIL: The requested address was not local to the local machine.
WSAEFAULT: The name parameter is not a valid pointer.
WSAEINVAL: The socket has been shown to be in a permanently closed state, or the namelen parameter is incorrect.
WSAENOTSOCK: The descriptor s does not refer to a socket.
Remarks
The bind function is used to assign a unique name to an unnamed socket.
A socket is typically created using the socket function.
Binding to a Specific IP Address and Port
To bind a socket to a specific IP address and port, you typically populate a sockaddr_in (for IPv4) or sockaddr_in6 (for IPv6) structure.
Binding to Any Available Address
To bind to any available address on the local machine, you can specify the IP address as INADDR_ANY.
This is common for servers that need to listen on all network interfaces.
Note:
When binding a UDP socket, the OS will typically only bind the socket to the specified port and not the IP address.
This means that if you bind to INADDR_ANY, the socket will be able to receive datagrams from any IP address.
If you bind to a specific IP address, the socket will only receive datagrams sent to that specific IP address.
Example
#include <winsock2.h>
#include <ws2tcpip.h>
// ...
SOCKET listen_socket;
struct sockaddr_in server_addr;
int port = 8080;
// Initialize Winsock
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
// Handle error
return 1;
}
// Create a TCP socket
listen_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_socket == INVALID_SOCKET) {
// Handle error
WSACleanup();
return 1;
}
// Configure the server address structure
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Bind to any available interface
server_addr.sin_port = htons(port); // Port to listen on
// Bind the socket to the address and port
if (bind(listen_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
// Handle error
closesocket(listen_socket);
WSACleanup();
return 1;
}
// Now the socket is ready to listen for incoming connections
// ...
// Cleanup
// closesocket(listen_socket);
// WSACleanup();