The bind function associates a local address with a socket.
Syntax
Parameters
A descriptor identifying an unbound socket.
A pointer to a sockaddr structure of the local address to assign to the bound socket .
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
WSAENETDOWN
The network subsystem has failed.
WSAEACCES
An attempt was made to access a socket in a way forbidden by its access permissions.
This error is returned if nn attempt to bind a datagram socket to the broadcast address failed because the setsockopt option SO_BROADCAST is not enabled.
WSAEADDRINUSE
Only one usage of each socket address (protocol/network address/port) is normally permitted.
This error is returned if 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 requested address is not valid in its context.
This error is returned if the specified address pointed to by the name parameter is not a valid local IP address on this computer.
WSAEFAULT
The system detected an invalid pointer address in attempting to use a pointer argument in a call.
This error is returned if the name parameter is NULL, 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 do 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
An invalid argument was supplied.
This error is returned of the socket s is already bound to an address.
WSAENOBUFS
Typically, WSAENOBUFS is an indication that there aren’t enough ephemeral ports to allocate for the bind.
WSAENOTSOCK
An operation was attempted on something that is not a socket.
This error is returned if 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 socketfunction 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 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 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 the client dynamic port range can be changed by setting a value under the following registry key:
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 the socket. 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.
For multicast operations, the preferred method is to call the bind function to associate a socket with a local IP address and then join the multicast group. Although this order of operations is not mandatory, it is strongly recommended. So a multicast application would first select an IPv4 or IPv6 address on the local computer, the wildcard IPv4 address (INADDR_ANY), or the wildcard IPv6 address (in6addr_any). The the multicast application would then call the bind function with this address in the in the sa_data member of the name parameter to associate the local IP address with the socket. If a wildcard address was 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 LPFN_WSARECVMSG (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.
WindowsВ PhoneВ 8: This function is supported for Windows Phone Store apps on WindowsВ PhoneВ 8 and later.
WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.
Examples
The following example demonstrates the use of the bind function. For another example that uses the bind function, see Getting Started With Winsock.
socket_bind
(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
socket_bind — Привязывает имя к сокету
Описание
Привязывает имя, указанное в параметре address , к сокету, описанному в параметре socket . Это должно быть сделано до того, как соединение установлено при помощи функции socket_connect() или socket_listen() .
Список параметров
Экземпляр Socket, созданный при помощи функции socket_create() .
Если сокет из семейства AF_INET , то параметр address должен быть IP-адресом в записи, разделённой точками (например, 127.0.0.1 ).
Если сокет из семейства AF_UNIX , то параметр address — это путь к доменному сокету Unix (например, /tmp/my.sock ).
Параметр port используется, только когда имя привязывается к сокету AF_INET , и указывает порт, на котором будут слушаться соединения.
Возвращаемые значения
Возвращает true в случае успешного завершения или false в случае возникновения ошибки.
Код ошибки может быть получен при помощи функции socket_last_error() . Этот код может быть передан функции socket_strerror() для получения текстового описания ошибки.
Список изменений
Версия
Описание
8.0.0
socket теперь экземпляр класса Socket; ранее был ресурсом ( resource ).
Примеры
Пример #1 Использование функции socket_bind() для установки адреса источника
Эта функция должна быть применена на сокете перед вызовом socket_connect() .
Примечание по совместимости с Windows 9x/ME: Функция socket_last_error() может возвращать неверный код ошибки при попытке связать с сокетом неверный адрес, который не принадлежит вашей машине.
Смотрите также
socket_connect() — Начинает соединение с сокетом
socket_listen() — Прослушивает входящие соединения на сокете
socket_create() — Создаёт сокет (конечную точку для обмена информацией)
socket_last_error() — Возвращает последнюю ошибку на сокете
The following tables describe SOL_SOCKET socket options. See the getsockopt and setsockopt function reference pages for more information on getting and setting socket options.
To enumerate protocols and discover supported properties for each installed protocol, use the WSAEnumProtocols, WSCEnumProtocols, or WSCEnumProtocols32 function.
Some socket options require more explanation than these tables can convey; such options contain links to additional pages.
All SOL_SOCKET socket options apply equally to IPv4 and IPv6 (except SO_BROADCAST, since broadcast is not implemented in IPv6).
**SOL\_SOCKET Socket Options**
Option
Get
Set
Optval type
Description
PVD_CONFIG
yes
yes
char []
An opaque data structure object containing configuration information for the service provider. This option is implementation dependent.
SO_ACCEPTCONN
yes
DWORDВ (boolean)
Returns whether a socket is in listening mode. This option is only Valid for connection-oriented protocols.
SO_BROADCAST
yes
yes
DWORD (boolean)
Configure a socket for sending broadcast data. This option is only Valid for protocols that support broadcasting (IPX and UDP, for example).
SO_BSP_STATE
yes
CSADDR_INFO
Returns the local address, local port, remote address, remote port, socket type, and protocol used by a socket. See the SO_BSP_STATE reference for more information.
SO_CONDITIONAL_ACCEPT
yes
yes
DWORD (boolean)
Indicates if incoming connections are to be accepted or rejected by the application, not by the protocol stack. See the SO_CONDITIONAL_ACCEPT reference for more information.
SO_CONNDATA
yes
yes
char []
Additional data, not in the normal network data stream, that is sent with network requests to establish a connection. This option is used by legacy protocols such as DECNet, OSI TP4, and others. This option is not supported by the TCP/IP protocol in Windows.
SO_CONNDATALEN
yes
DWORD
The length, in bytes, of additional data, not in the normal network data stream, that is sent with network requests to establish a connection. This option is used by legacy protocols such as DECNet, OSI TP4, and others. This option is not supported by the TCP/IP protocol in Windows.
SO_CONNECT_TIME
yes
DWORD
Returns the number of seconds a socket has been connected. This option is only valid for connection-oriented protocols.
SO_CONNOPT
yes
yes
char []
Additional connect option data, not in the normal network data stream, that is sent with network requests to establish a connection. This option is used by legacy protocols such as DECNet, OSI TP4, and others. This option is not supported by the TCP/IP protocol in Windows.
SO_CONNOPTLEN
yes
DWORD
The length, in bytes, of connect option data, not in the normal network data stream, that is sent with network requests to establish a connection. This option is used by legacy protocols such as DECNet, OSI TP4, and others. This option is not supported by the TCP/IP protocol in Windows.
SO_DISCDATA
yes
yes
char []
Additional data, not in the normal network data stream, that is sent with network requests to disconnect a connection. This option is used by legacy protocols such as DECNet, OSI TP4, and others. This option is not supported by the TCP/IP protocol in Windows.
SO_DISCDATALEN
yes
DWORD
The length, in bytes, of additional data, not in the normal network data stream, that is sent with network requests to disconnect a connection. This option is used by legacy protocols such as DECNet, OSI TP4, and others. This option is not supported by the TCP/IP protocol in Windows.
SO_DISCOPT
yes
yes
char []
Additional disconnect option data, not in the normal network data stream, that is sent with network requests to disconnect a connection. This option is used by legacy protocols such as DECNet, OSI TP4, and others. This option is not supported by the TCP/IP protocol in Windows.
SO_DISCOPTLEN
yes
DWORD
The length, in bytes, of additional disconnect option data, not in the normal network data stream, that is sent with network requests to disconnect a connection. This option is used by legacy protocols such as DECNet, OSI TP4, and others. This option is not supported by the TCP/IP protocol in Windows.
SO_DEBUG
yes
yes
DWORD (boolean)
Enable debug output. Microsoft providers currently do not output any debug information.
SO_DONTLINGER
yes
yes
DWORD (boolean)
Indicates the state of the l_onoff member of the linger structure associated with a socket. If this member is nonzero, a socket remains open for a specified amount of time after a closesocket function call to enable queued data to be sent. This option is only valid for reliable, connection-oriented protocols.
SO_DONTROUTE
yes
yes
DWORD (boolean)
Indicates that outgoing data should be sent on whatever interface the socket is bound to and not a routed on some other interface. This option is only Valid for message-oriented protocols. Microsoft providers silently ignore this option and always consult the routing table to find the appropriate outgoing interface.
SO_ERROR
yes
DWORD
Returns the last error code on this socket. This per-socket error code is not always immediately set.
SO_EXCLUSIVEADDRUSE
yes
yes
DWORD (boolean)
Prevents any other socket from binding to the same address and port. This option must be set before calling the bind function. See the SO_EXCLUSIVEADDRUSE reference for more information.
SO_GROUP_ID
yes
unsigned int
This socket option is reserved and should not be used.
SO_GROUP_PRIORITY
yes
yes
int
This socket option is reserved and should not be used.
SO_KEEPALIVE
yes
yes
DWORD (boolean)
Enables keep-alive for a socket connection. Valid only for protocols that support the notion of keep-alive (connection-oriented protocols). For TCP, the default keep-alive timeout is 2 hours and the keep-alive interval is 1 second. The default number of keep-alive probes varies based on the version of Windows. See the SO_KEEPALIVE reference for more information.
SO_LINGER
yes
yes
struct linger
Indicates the state of the linger structure associated with a socket. If the l_onoff member of the linger structure is nonzero, a socket remains open for a specified amount of time after a closesocket function call to enable queued data to be sent. The amount of time, in seconds, to remain open is specified in the l_linger member of the linger structure. This option is only valid for reliable, connection-oriented protocols.
SO_MAX_MSG_SIZE
yes
DWORD
Returns the maximum outbound message size for message-oriented sockets supported by the protocol. Has no meaning for stream-oriented sockets.
SO_MAXDG
yes
DWORD
Returns the maximum size, in bytes, for outbound datagrams supported by the protocol. This socket option has no meaning for stream-oriented sockets.
SO_MAXPATHDG
yes
DWORD
Returns the maximum size, in bytes, for outbound datagrams supported by the protocol to a given destination address. This socket option has no meaning for stream-oriented sockets. Microsoft providers may silently treat this as SO_MAXDG.
SO_OOBINLINE
yes
yes
DWORD (boolean)
Indicates that out-of-bound data should be returned in-line with regular data. This option is only valid for connection-oriented protocols that support out-of-band data.
SO_OPENTYPE
yes
yes
DWORD
Once set, affects whether subsequent sockets that are created will be non-overlapped. The possible values for this option are SO_SYNCHRONOUS_ALERT and SO_SYNCHRONOUS_NONALERT. This option should not be used. Instead use the WSASocket function and leave the WSA_FLAG_OVERLAPPED bit in the dwFlags parameter turned off.
SO_PAUSE_ACCEPT
yes
yes
DWORD(boolean)
Use this option for listening sockets. When the option is set, the socket responds to all incoming connections with an RST rather than accepting them.
SO_PORT_SCALABILITY
yes
yes
DWORD (boolean)
Enables local port scalability for a socket by allowing port allocation to be maximized by allocating wildcard ports multiple times for different local address port pairs on a local machine. On platforms where both options are available, prefer SO_REUSE_UNICASTPORT instead of this option. See the SO_PORT_SCALABILITY reference for more information.
SO_PROTOCOL_INFO
yes
WSAPROTOCOL_INFO
This option is defined to the SO_PROTOCOL_INFOW socket option if the UNICODE macro is defined. If the UNICODE macro is not defined, then this option is defined to the SO_PROTOCOL_INFOA socket option.
SO_PROTOCOL_INFOA
yes
WSAPROTOCOL_INFOA
Returns the WSAPROTOCOL_INFOA structure for the given socket
SO_PROTOCOL_INFOW
yes
WSAPROTOCOL_INFOW
Returns the WSAPROTOCOL_INFOW structure for the given socket
SO_RANDOMIZE_PORT
yes
yes
uint16
This option should be set on an unbound socket. When SO_RANDOMIZE_PORT is set and an ephemeral port is selected on the socket, a random port number is bound. Auto-reuse ports (ports selected using SO_REUSE_UNICASTPORT) also randomize the returned port, so if an application sets SO_REUSE_UNICASTPORT and then attempts to set SO_RANDOMIZE_PORT, the second setsockopt call fails.
SO_RCVBUF
yes
yes
DWORD
The total per-socket buffer space reserved for receives. This is unrelated to SO_MAX_MSG_SIZE and does not necessarily correspond to the size of the TCP receive window.
SO_RCVLOWAT
yes
yes
DWORD
A socket option from BSD UNIX included for backward compatibility. This option sets the minimum number of bytes to process for socket input operations. This option is not supported by the Windows TCP/IP provider. If this option is used on WindowsВ Vista and later, the getsockopt and setsockopt functions fail with WSAEINVAL. On earlier versions of Windows, these functions fail with WSAENOPROTOOPT.
SO_RCVTIMEO
yes
yes
DWORD
The timeout, in milliseconds, for blocking receive calls. The default for this option is zero, which indicates that a receive operation will not time out. If a blocking receive call times out, the connection is in an indeterminate state and should be closed. If the socket is created using the WSASocket function, then the dwFlags parameter must have the WSA_FLAG_OVERLAPPED attribute set for the timeout to function properly. Otherwise the timeout never takes effect.
SO_REUSEADDR
yes
yes
DWORD (boolean)
Allows a socket to bind to an address and port already in use. The SO_EXCLUSIVEADDRUSE option can prevent this.
SO_REUSE_UNICASTPORT
yes
yes
DWORD (boolean)
When set, allow ephemeral port reuse for Winsock API connection functions which require an explicit bind, such as ConnectEx. Note that connection functions with an implicit bind (such as connect without an explicit bind) have this option set by default. Use this option instead of SO_PORT_SCALABILITY on platforms where both are available.
SO_REUSE_MULTICASTPORT
yes
DWORD
When set on a socket, this option indicates that the socket will never be used to receive unicast packets, and consequently that its port can be shared with other multicast-only applications. Setting the value to 1 enables always sharing multicast traffic on the port. Setting the value to 0 (default) disables this behavior.
SO_SNDBUF
yes
yes
DWORD
The total per-socket buffer space reserved for sends. This is unrelated to SO_MAX_MSG_SIZE and does not necessarily correspond to the size of a TCP send window.
SO_SNDLOWAT
yes
yes
DWORD
A socket option from BSD UNIX included for backward compatibility. This option sets the minimum number of bytes to process for socket output operations. This option is not supported by the Windows TCP/IP provider. If this option is used on WindowsВ Vista and later, the getsockopt and setsockopt functions fail with WSAEINVAL. On earlier versions of Windows, these functions fail with WSAENOPROTOOPT.
SO_SNDTIMEO
yes
yes
DWORD
The timeout, in milliseconds, for blocking send calls. The default for this option is zero, which indicates that a send operation will not time out. If a blocking send call times out, the connection is in an indeterminate state and should be closed. If the socket is created using the WSASocket function, then the dwFlags parameter must have the WSA_FLAG_OVERLAPPED attribute set for the timeout to function properly. Otherwise the timeout never takes effect.
SO_TYPE
yes
DWORD
Returns the socket type for the given socket (SOCK_STREAM or SOCK_DGRAM, for example).
SO_UPDATE_ACCEPT_CONTEXT
yes
DWORD (boolean)
This option is used with the AcceptEx function. This option updates the properties of the socket which are inherited from the listening socket. This option should be set if the getpeername, getsockname, getsockopt, or setsockopt functions are to be used on the accepted socket.
SO_UPDATE_CONNECT_CONTEXT
yes
DWORD (boolean)
This option is used with the ConnectEx, WSAConnectByList, and WSAConnectByName functions. This option updates the properties of the socket after the connection is established. This option should be set if the getpeername, getsockname, getsockopt, setsockopt, or shutdown functions are to be used on the connected socket.
SO_USELOOPBACK
yes
yes
DWORD (boolean)
Use the local loopback address when sending data from this socket. This option should only be used when all data sent will also be received locally. This option is not supported by the Windows TCP/IP provider. If this option is used on WindowsВ Vista and later, the getsockopt and setsockopt functions fail with WSAEINVAL. On earlier versions of Windows, these functions fail with WSAENOPROTOOPT.
**Windows Support for SOL\_SOCKET Options**
Option
Windows 10
Windows 7
Windows Server 2008
Windows Vista
Windows Server 2003
Windows XP
Windows 2000
Windows NT4
Windows 9x/ME
PVD_CONFIG
SO_ACCEPTCONN
x
x
x
x
x
x
x
x
x
SO_BROADCAST
x
x
x
x
x
x
x
x
x
SO_BSP_STATE
x
x
x
x
SO_CONDITIONAL_ACCEPT
x
x
x
x
x
x
x
SO_CONNDATA
x
x
x
x
x
x
x
x
SO_CONNDATALEN
x
x
x
x
x
x
x
x
SO_CONNECT_TIME
x
x
x
x
x
x
x
x
x
SO_CONNOPT
x
x
x
x
x
x
x
x
SO_CONNOPTLEN
x
x
x
x
x
x
x
x
SO_DISCDATA
x
x
x
x
x
x
x
x
SO_DISCDATALEN
x
x
x
x
x
x
x
x
SO_DISCOPT
x
x
x
x
x
x
x
x
SO_DISCOPTLEN
x
x
x
x
x
x
x
x
SO_DEBUG
x
x
x
x
x
x
x
x
x
SO_DONTLINGER
x
x
x
x
x
x
x
x
x
SO_DONTROUTE
x
x
x
x
x
x
x
x
x
SO_ERROR
x
x
x
x
x
x
x
x
x
SO_EXCLUSIVEADDRUSE
x
x
x
x
x
x
x
x SP4+
SO_GROUP_ID
x
x
x
x
SO_GROUP_PRIORITY
x
x
x
x
SO_KEEPALIVE
x
x
x
x
x
x
x
x
x
SO_LINGER
x
x
x
x
x
x
x
x
x
SO_MAX_MSG_SIZE
x
x
x
x
x
x
x
x
x
SO_MAXDG
x
x
x
x
x
x
x
SO_MAXPATHDG
x
x
x
x
x
x
x
SO_OOBINLINE
x
x
x
x
x
x
x
x
x
SO_OPENTYPE
x
x
x
x
x
x
x
x
x
SO_PORT_SCALABILITY
x
x
x
SO_PROTECT
x
SO_PROTOCOL_INFO
x
x
x
x
x
x
x
x
x
SO_PROTOCOL_INFOA
x
x
x
x
x
x
x
x
x
SO_PROTOCOL_INFOW
x
x
x
x
x
x
x
x
x
SO_RCVBUF
x
x
x
x
x
x
x
x
x
SO_RCVLOWAT
SO_RCVTIMEO
x
x
x
x
x
x
x
x
x
SO_RANDOMIZE_PORT
x
x
x
x
SO_REUSEADDR
x
x
x
x
x
x
x
x
x
SO_REUSE_UNICASTPORT
x
SO_REUSE_MULTICASTPORT
x
SO_SNDBUF
x
x
x
x
x
x
x
x
x
SO_SNDLOWAT
SO_SNDTIMEO
x
x
x
x
x
x
x
x
x
SO_TYPE
x
x
x
x
x
x
x
x
x
SO_UPDATE_ACCEPT_CONTEXT
x
x
x
x
x
x
x
x
SO_UPDATE_CONNECT_CONTEXT
x
x
x
x
x
x
SO_USELOOPBACK
Remarks
The SOL_SOCKET socket options are defined in several Winsock header files: