Windows API Reference

bind Function (Winsock)

The bind function assigns a local protocol-independent address to a socket.

int bind( _In_ SOCKET s, _In_ const sockaddr *name, _In_ int namelen );

Parameters

Parameter Description
s

A descriptor that identifies an unbound socket.

name

A pointer to a sockaddr structure that contains the protocol-specific address and port number for the socket.

For Internet protocols, this is a pointer to a sockaddr_in structure. The sockaddr_in structure contains the following members:

struct sockaddr_in {
    short int sin_family;             // Address family (AF_INET)
    unsigned short int sin_port;      // Port number
    struct in_addr sin_addr;          // IP address
    char sin_zero[8];                 // Not used
};
namelen

The size, in bytes, of the name structure.

Return Value

If no error occurs, bind returns zero. Otherwise, it returns a socket error code.

Possible error codes include:

  • WSAEACCES: An attempt was made to access a socket in a way forbidden by its access permissions.
  • WSAEADDRINUSE: A requested address is already in use.
  • WSAEFAULT: The name parameter is not a valid address.
  • WSAEINTR: A blocking Windows Sockets 1.1 call was interrupted by a Windows Sockets 2 function.
  • WSAEINVAL: The socket is already bound to an address.
  • WSAENETDOWN: The network subsystem has failed.
  • WSAENOBUFS: No buffer space is available.
  • WSAENOTSOCK: The descriptor is not a socket.
  • WSAEOPNOTSUPP: The attempted operation is not supported.
  • WSAEPROTONOSUPPORT: The requested protocol is not supported by the Windows Sockets implementation.
  • WSAEPROTOTYPE: The specified protocol is not the correct type for the supplied address structure.
  • WSAESHUTDOWN: The socket has been shut down and cannot be bound.
  • WSAEWOULDBLOCK: The socket is nonblocking and a connection cannot be established immediately.

Remarks

The bind function is used with a stream or datagram socket to associate it with a particular network address (interface and port number).

For TCP/IP, the name parameter should point to a sockaddr_in structure that specifies the desired local address and port number.

If the IP address member of the sockaddr_in structure is set to INADDR_ANY (0.0.0.0), the Winsock provider will associate the socket with all available network interfaces on the local machine.

If the port number is specified as 0, the Winsock provider will assign an ephemeral port from the dynamic port range.

For connectionless sockets (like UDP), binding is typically required before sending data. For connection-oriented sockets (like TCP), binding is often done implicitly when connect or listen is called, but explicitly calling bind is also supported.

When using bind with a datagram socket, you must specify a port number. For a server application, this is usually a well-known port. For a client application, it is typically 0 to allow the system to assign an ephemeral port.

If the socket is a multicast socket, you should bind to the wildcard address (INADDR_ANY) and the desired port. For sending multicast datagrams, you can use sendto to specify the outgoing interface.

Requirements

Client: Windows Vista [desktop apps only]
Server: Windows Server 2008 [desktop apps only]
Header: winsock2.h
Library: Ws2_32.lib
DLL: Ws2_32.dll

Example Code

This example demonstrates how to bind a socket to a specific address and port.


#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

// Link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

#define DEFAULT_PORT "27015"

int main() {
    WSADATA wsaData;
    SOCKET ListenSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL;
    struct addrinfo hints;

    int iResult;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE; // Socket address will be used in a call to bind()

    // Resolve the local address and port to be used by the caller
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if (iResult != 0) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Create a SOCKET for the server to listen for client connections
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);

    if (ListenSocket == INVALID_SOCKET) {
        printf("Error at socket(): %ld\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    // 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;
    }

    printf("Socket bound successfully to port %s\n", DEFAULT_PORT);

    freeaddrinfo(result);

    // ... subsequent listen, accept, recv, send calls would follow ...

    closesocket(ListenSocket);
    WSACleanup();

    return 0;
}