UDT Reference: Functions

#### bind

The bind method binds a UDT socket to a known or an available local address.

int bind(
UDTSOCKET u,
struct sockaddr* name,
int* namelen
);
int bind(
#ifndef WIN32
int udpsock
#else
SOCKET udpsock
#endif
);

##### Parameters

u
  [in] Descriptor identifying a UDT socket.
name
  [out] Address to assign to the socket from the sockaddr structure.
namelen
  [out] Length of the name structure.
udpsock
  [in] An existing UDP socket for UDT to bind.

##### Return Value

If the binding is successful, bind returns 0, otherwise it returns UDT::ERROR and the specific error information can be retrieved using getlasterror.

Error Name | Error Code | Comment
EBOUNDSOCK | 5001 | u has already been bound to certain address.
EINVPARAM | 5003 | the address is either invalid or unavailable.
EINVSOCK | 5004 | u is an invalid UDT socket.

##### Description

The bind method is usually to assign a UDT socket a local address, including IP address and port number. If INADDR_ANY is used, a proper IP address will be used once the UDT connection is set up. If 0 is used for the port, a randomly available port number will be used. The method getsockname can be used to retrieve this port number.

The second form of bind allows UDT to bind directly on an existing UDP socket. This is usefule for firewall traversing in certain situations: 1) a UDP socket is created and its address is learned from a name server, there is no need to close the UDP socket and open a UDT socket on the same address again; 2) for certain firewall, especially some on local system, the port mapping maybe changed or the "hole" may be closed when a UDP socket is closed and reopened, thus it is necessary to use the UDP socket directly in UDT.

Use the second form of bind with caution, as it violates certain programming rules regarding code robustness. Once the UDP socket descriptor is passed to UDT, it MUST NOT be touched again. DO NOT use this unless you clearly understand how the related systems work.

The bind call is necessary in all cases except for a socket to listen. If bind is not called, UDT will automatically bind a socket to a randomly available address when a connection is set up.

By default, UDT allows to reuse existing UDP port for new UDT sockets, unless UDT_REUSEADDR is set to false. When UDT_REUSEADDR is false, UDT will create an exclusive UDP port for this UDT socket. UDT_REUSEADDR must be called before bind. To reuse an existing UDT/UDP port, the new UDT socket must explicitly bind to the port. If the port is already used by a UDT socket with UDT_REUSEADDR as false, the new bind will return error. If 0 is passed as the port number, bind always creates a new port, no matter what value the UDT_REUSEADDR sets.

##### See Also

listen, connect, setsockopt, getsockopt