Description
Associate a local address with a socket.
#include <winsock.h>
int PASCAL FAR bind ( SOCKET s, const struct sockaddr FAR * name, int namelen);
s
struct sockaddr { u_short sa_family; char sa_dataφ14∙; };
namelen
Remarks
This routine is used on an unconnected datagram or stream socket, before subsequent connect()s or listen()s. When a socket is created with socket(), it exists in a name space (address family), but it has no name assigned. bind() establishes the local association (host address/port number) of the socket by assigning a local name to an unnamed socket.
In the Internet address family, a name consists of several components. For SOCK_DGRAM and SOCK_STREAM, the name consists of three parts: a host address, the protocol number (set implicitly to UDP or TCP, respectively), and a port number which identifies the application. If an application does not care what address is assigned to it, it may specify an Internet address equal to INADDR_ANY, a port equal to 0, or both. If the Internet address is equal to INADDR_ANY, any appropriate network interface will be used; this simplifies application programming in the presence of multi-homed hosts. If the port is specified as 0, the Windows Sockets implementation will assign a unique port to the application with a value between 1024 and 5000. The application may use getsockname() after bind() to learn the address that has been assigned to it, but note that getsockname() will not necessarily fill in the Internet address until the socket is connected, since several Internet addresses may be valid if the host is multi-homed.
If an application desires to bind to an arbitrary port outside of the range 1024 to 5000, such as the case of rsh which must bind to any reserved port, code similar to the following may be used:
SOCKADDR_IN sin; SOCKET s; u_short alport = IPPORT_RESERVED; sin.sin_family = AF_INET; sin.sin_addr.s_addr = 0; for (;;) { sin.sin_port = htons(alport); if (bind(s, (LPSOCKADDR)&sin, sizeof (sin)) == 0) { /* it worked */ } if ( GetLastError() ]= WSAEADDRINUSE) { /* fail */ } alport--; if (alport == IPPORT_RESERVED/2 ) { /* fail--all unassigned reserved ports are */ /* in use. */ } }
Return Value
If no error occurs, bind() returns 0. Otherwise, it returns SOCKET_ERROR, and a specific error code may be retrieved by calling WSAGetLastError().
Error Codes
WSANOTINITIALISED
WSAEINVAL
See Also
connect(), listen(), getsockname(), setsockopt(), socket(), WSACancelBlockingCall()