bind Function (Winsock2.h)
Binds a local name (address and port) to a socket.
Syntax
int bind(
SOCKET s,
const SOCKADDR *name,
int namelen
);
Parameters
Parameter | Description |
---|---|
s |
A descriptor that identifies an unbound socket. |
name |
A pointer to a SOCKADDR structure that specifies the address and port to associate with the socket s . For internet protocols, this is a pointer to a SOCKADDR_IN structure.
|
namelen |
The size, in bytes, of the structure pointed to by the name parameter.
|
Return Value
bind
returns zero. Otherwise, a SOCKET error code is returned, and a specific error code can be retrieved by calling WSAGetLastError
.
Remarks
The bind
function is used to associate a local address with a socket. When a socket is created with socket
, it exists in an unknown name space. A local name must be explicitly assigned by calling bind
before the socket can be connected to another socket.
If the socket is of type SOCK_DGRAM
, the local address is the address that the datagrams will be sent from. If you do not care about the incoming data, you can bind to the wildcard address (all interfaces).
For connection-oriented protocols like SOCK_STREAM
, binding to a specific port is often required for servers to accept incoming connections. Clients can typically bind to an unspecified port, allowing the system to assign a unique ephemeral port.
Important Notes:
- Ensure that the
SOCKADDR
structure is correctly populated with the desired address family, IP address, and port number. - For IPv4, use
AF_INET
and aSOCKADDR_IN
structure. - For IPv6, use
AF_INET6
and aSOCKADDR_IN6
structure. - Binding to the wildcard address (0.0.0.0 for IPv4, or :: for IPv6) allows the socket to accept connections on any available network interface.