The
bind function associates a local address with a socket.
Syntax
int bind(
__in SOCKET s,
__in const struct sockaddr *name,
__in int namelen
);
Parameters
- s [in]
-
A descriptor identifying an unbound socket.
- name [in]
-
A pointer to a sockaddr structure of the local address to assign to the bound socket .
- namelen [in]
-
The length, in bytes, of the value pointed to by the name parameter.
Return Value
If no error occurs,
bind returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error code can be retrieved by calling
WSAGetLastError.
| Error code | Meaning |
- WSANOTINITIALISED
| Note A successful
WSAStartup call must occur before using this function.
|
- WSAENETDOWN
| The network subsystem has failed.
|
- WSAEACCES
| An attempt to bind a datagram socket to the broadcast address failed because
the setsockopt option SO_BROADCAST is not enabled.
|
- WSAEADDRINUSE
| A process on the computer is already bound to the same fully-qualified address and the socket has not been marked to allow address reuse with SO_REUSEADDR. For example, the IP address and port specified in the name parameter are already bound to another socket being used by another application. For more information, see the SO_REUSEADDR socket option in the SOL_SOCKET Socket Options reference, Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE, and SO_EXCLUSIVEADDRUSE.
|
- WSAEADDRNOTAVAIL
| The specified address pointed to by the name parameter is not a valid local IP address on this computer.
|
- WSAEFAULT
| The name or namelen parameter is not a valid part of the user address space, the namelen parameter is too small, the name parameter contains an incorrect address format for the associated address family, or the first two bytes of the memory block specified by name does not match the address family associated with the socket descriptor s.
|
- WSAEINPROGRESS
| A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
|
- WSAEINVAL
| The socket is already bound to an address.
|
- WSAENOBUFS
| Not enough buffers are available, too many connections.
|
- WSAENOTSOCK
| The descriptor in the s parameter is not a socket.
|
Remarks
The
bind function is required on an unconnected socket before subsequent calls to the
listen function. It is normally used to bind to either connection-oriented (stream) or connectionless (datagram) sockets. The
bind function may also be used to bind to a raw socket (the socket was created by calling the socket
function with the type parameter set to SOCK_RAW). The
bind function may also be used on an unconnected socket before subsequent calls to the
connect, ConnectEx, WSAConnect, WSAConnectByList, or WSAConnectByName functions before send operations.
When a socket is created with a call to the
socket function, it exists in a namespace (address family), but it has no name assigned to it. Use the
bind function to establish the local association of the socket by assigning a local name to an unnamed socket.
A name consists of three parts when using the Internet address family:
- The address family.
- A host address.
- A port number that identifies the application.
In Windows Sockets 2, the name parameter is not strictly interpreted as a pointer to a
sockaddr structure. It is cast this way for Windows Sockets 1.1 compatibility. Service providers are free to regard it as a pointer to a block of memory of size namelen. The first 2 bytes in this block (corresponding to the sa_family member of the sockaddr structure, the sin_family member of the sockaddr_in structure, or the the sin6_family member of the sockaddr_in6 structure) must contain the address family that was used to create the socket. Otherwise, an error WSAEFAULT occurs.
If an application does not care what local address is assigned, specify the constant value INADDR_ANY for an IPv4 local address or the constant value in6addr_any for an IPv6 local address in the sa_data member of the name parameter. This allows the underlying service provider to use any appropriate network address, potentially simplifying application programming in the presence of multihomed hosts (that is, hosts that have more than one network interface and address).
For TCP/IP, if the port is specified as zero, the service provider assigns a unique port to the application from the dynamic client port range. On Windows Vista and later, the dynamic client port range is with a value between 49152 and 65535. This is a change from Windows Server 2003 and earlier where the dynamic client port range was a value between 1025 and 5000. The maximum value for client dynamic port range can be changed by setting a value under the following registry key:
HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
The MaxUserPort registry value sets the value to use for the maximum value of the dynamic client port range. You must restart the computer for this setting to take effect.
On Windows Vista and later, the dynamic client port range can be viewed and changed using netsh commands. The dynamic client port range can be set differently for UDP and TCP and also for IPv4 and IPv6. For more information, see KB 929851.
The application can use
getsockname after calling
bind to learn the address and the port that has been assigned to it. If the Internet address is equal to INADDR_ANY or in6addr_any,
getsockname cannot necessarily supply the address until the socket is connected, since several addresses can be valid if the host is multihomed. Binding to a specific port number other than port 0 is discouraged for client applications, since there is a danger of conflicting with another socket already using that port number on the local computer.
Note When using bind with the SO_EXCLUSIVEADDRUSE or SO_REUSEADDR socket option, the socket option must be set prior to executing bind to have any affect. For more information, see SO_EXCLUSIVEADDRUSE and Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE.
For multicast operations, the preferred method is to call the bind function to bind a socket to a local IP address and then join the multicast group. Although this order of operations is not mandatory, it is strongly recommended. So an application would first select an appropriate local IPv4 or IPv6 address on the local computer or the wildcard address (INADDR_ANY or in6addr_any) to bind the socket to. If a wildcard address is specified, then Windows will select the local IP address to use. After the bind function completes, an application would then join the multicast group of interest. For more information on how to join a multicast group, see the section on Multicast Programming. This socket can then be used to receive multicast packets from the multicast group using the recv, recvfrom, WSARecv, WSARecvEx, WSARecvFrom, or WSARecvMsg functions.
The bind function is not normally required for send operations to a multicast group. The sendto,WSASendMsg, and WSASendTo functions implicitly bind the socket to the wildcard address if the socket is not already bound. The bind function is required before the use of the send or WSASend functions which do not perform an implicit bind and are allowed only on connected sockets, which means the socket must have already been bound for it to be connected. The bind function might be used before send operations using the sendto,WSASendMsg, or WSASendTo functions if an application wanted to select a specific local IP address on a local computer with multiple network interfaces and local IP addresses. Otherwise an implicit bind to the wildcard address using the sendto,WSASendMsg , or WSASendTo functions might result in a different local IP address being used for send operations.
Notes for IrDA Sockets
- The Af_irda.h header file must be explicitly included.
- Local names are not exposed in IrDA. IrDA client sockets therefore, must never call the
bind function before the
connect function. If the IrDA socket was previously bound to a service name using
bind, the
connect function will fail with SOCKET_ERROR.
- If the service name is of the form "LSAP-SELxxx," where xxx is a decimal integer in the range 1-127, the address indicates a specific LSAP-SEL xxx rather than a service name. Service names such as these allow server applications to accept incoming connections directed to a specific LSAP-SEL, without first performing an ISA service name query to get the associated LSAP-SEL. One example of this service name type is a non-Windows device that does not support IAS.
Examples
The following example demonstrates the use of the bind function. For another example that uses the bind function, see Getting Started With Winsock.
#include <stdio.h>
#include "winsock2.h"
#include <windows.h>
#pragma comment(lib, "wininet.lib")
void main() {
//----------------------
// Initialize Winsock
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR)
printf("Error at WSAStartup()\n");
//----------------------
// Create a SOCKET for listening for
// incoming connection requests
SOCKET ListenSocket;
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
WSACleanup();
return;
}
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is being bound.
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr("127.0.0.1");
service.sin_port = htons(27015);
//----------------------
// Bind the socket.
if (bind( ListenSocket,
(SOCKADDR*) &service,
sizeof(service)) == SOCKET_ERROR) {
printf("bind() failed.\n");
closesocket(ListenSocket);
return;
}
WSACleanup();
return;
}
Requirements
| Minimum supported client | Windows 2000 Professional |
| Minimum supported server | Windows 2000 Server |
| Header | Winsock2.h |
| Library | Ws2_32.lib |
| DLL | Ws2_32.dll |
See Also
- Winsock Reference
- Winsock Functions
- connect
- getsockname
- listen
- Multicast Programming
- setsockopt
- SO_EXCLUSIVEADDRUSE
- SOL_SOCKET Socket Options
- sockaddr
- socket
- TCP/IP Raw Sockets
- Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE
- WSACancelBlockingCall
Send comments about this topic to Microsoft
Build date: 11/12/2009