bind() - Socket Function
The bind()
function is used to associate a local protocol-independent workstation address with a socket. This is necessary for both connectionless and connection-oriented sockets.
Syntax
int bind(
[in] SOCKET s,
[in] const struct sockaddr *name,
[in] int namelen
);
Parameters
Parameter | Description |
---|---|
s |
A descriptor identifying an unbound socket. |
name |
A pointer to a sockaddr structure that specifies the address to associate with the socket. For connection-oriented protocols, this is the local address. For connectionless protocols, this is the local address. |
namelen |
The size, in bytes, of the structure pointed to by the name parameter. |
Return Value
If no error occurs, bind()
returns zero. Otherwise, it returns a value of SOCKET_ERROR
, and a specific error code can be retrieved by calling WSAGetLastError()
.
Remarks
For a server application, calling bind()
is typically the first step in creating a socket that will accept incoming connections. The socket is bound to a specific network interface and port number. If the application wants to accept connections on any interface, it can specify the wildcard address (e.g., INADDR_ANY
for IPv4). For connectionless sockets, bind()
associates a local address with the socket, allowing the application to receive datagrams sent to that address.
bind()
with a UDP socket, you must bind to a specific port if you want to receive datagrams. If you don't bind to a port, the system may assign an ephemeral port, and you won't be able to reliably receive data.
sockaddr
structure is correctly populated with the desired IP address and port number. The port number must be in network byte order. Use the htons()
function to convert a host short integer to network byte order.
Example (IPv4 TCP Server)
#include <winsock2.h>
#include <ws2tcpip.h>
// Link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
int main() {
WSADATA wsaData;
SOCKET ListenSocket = INVALID_SOCKET;
struct sockaddr_in serverAddr;
int port = 27015;
// Initialize Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
// Handle error
return 1;
}
// Create a SOCKET for listening
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
// Handle error
WSACleanup();
return 1;
}
// Prepare the sockaddr_in structure
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
serverAddr.sin_port = htons(port);
// Bind the socket
if (bind(ListenSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
// Handle error
closesocket(ListenSocket);
WSACleanup();
return 1;
}
// ... continue with listen() and accept()
closesocket(ListenSocket);
WSACleanup();
return 0;
}