bind() — Bind a name to a socket

Standards

Standards / Extensions C or C++ Dependencies
XPG4.2
Single UNIX Specification, Version 3
both  

Format

X/Open
#define _XOPEN_SOURCE_EXTENDED 1
#include <sys/socket.h>

int bind(int socket, const struct sockaddr *address, socklen_t address_len);
Berkeley Sockets
#define _OE_SOCKETS
#include <sys/types.h>
#include <sys/socket.h>

int bind(int socket, struct sockaddr *address, int address_len);

General description

The bind() function binds a unique local name to the socket with descriptor socket. After calling socket(), a descriptor does not have a name associated with it. However, it does belong to a particular address family as specified when socket() is called. The exact format of a name depends on the address family.
Parameter
Description
socket
The socket descriptor returned by a previous socket() call.
address
The pointer to a sockaddr structure containing the name that is to be bound to socket.
address_len
The size of address in bytes.

The socket parameter is a socket descriptor of any type created by calling socket().

The address parameter is a pointer to a buffer containing the name to be bound to socket. The address_len parameter is the size, in bytes, of the buffer pointed to by address. For AF_UNIX, this function creates a file that you later need to unlink besides closing the socket.

Socket Descriptor Created in the AF_INET Domain

If the socket descriptor socket was created in the AF_INET domain, the format of the name buffer is expected to be sockaddr_in, as defined in the include file netinet/in.h:
struct in_addr
{
        ip_addr_t s_addr;
};

 struct sockaddr_in {
     unsigned char  sin_len;
     unsigned char  sin_family;
     unsigned short sin_port;
     struct in_addr sin_addr;
     unsigned char  sin_zero[8];

};

The sin_family field must be set to AF_INET.

The sin_port field is set to the port to which the application must bind. It must be specified in network byte order. If sin_port is set to 0, the caller leaves it to the system to assign an available port. The application can call getsockname() to discover the port number assigned.

The sin_addr.s_addr field is set to the Internet address and must be specified in network byte order. On hosts with more than one network interface (called multihomed hosts), a caller can select the interface to which it is to bind. Subsequently, only UDP packets and TCP connection requests from this interface (which match the bound name) are routed to the application. If this field is set to the constant INADDR_ANY, as defined in netinet/in.h, the caller is requesting that the socket be bound to all network interfaces on the host. Subsequently, UDP packets and TCP connections from all interfaces (which match the bound name) are routed to the application. This becomes important when a server offers a service to multiple networks. By leaving the address unspecified, the server can accept all UDP packets and TCP connection requests made for its port, regardless of the network interface on which the requests arrived.

The sin_zero field is not used and must be set to all zeros.

Socket Descriptor Created in the AF_INET6 Domain If the socket descriptor socket was created in the AF_INET6 domain, the format of the name buffer is expected to be sockaddr_in6, as defined in the include file netinet/in.h. The structure is defined as follows:
struct sockaddr_in6 {
   uint8_t          sin6_len;
   sa_family_t      sin6_family;
   in_port_t        sin6_port;
   uint32_t         sin6_flowinfo;
   struct in6_addr  sin6_addr;
   uint32_t         sin6_scope_id;
};

The sin6_len field is set to the size of this structure. The SIN6_LEN macro is defined to indicate the version of the sockaddr_in6 structure being used.

The sin6_family field identifies this as a sockaddr_in6 structure. This field overlays the sa_family field when the buffer is cast to a sockaddr structure. The value of this field must be AF_INET6.

The sin6_port field contains the 16-bit UDP or TCP port number. This field is used in the same way as the sin_port field of the sockaddr_in structure. The port number is stored in network byte order.

The sin6_flowinfo field is a 32-bit field that contains the traffic class and the flow label.

The sin6_addr field is a single in6_addr structure. This field holds one 128-bit IPv6 address. The address is stored in network byte order.

The sin6_scope_id field is a 32-bit integer that identifies a set of interfaces as appropriate for the scope of the address carried in the sin6_addr field. For a link scope sin6_addr, sin6_scope_id, this would be an interface index. For a site scope sin6_addr, sin6_scope_id, this would be a site identifier.

Socket Descriptor Created in the AF_UNIX Domain

If the socket descriptor socket is created in the AF_UNIX domain, the format of the name buffer is expected to be sockaddr_un, as defined in the include file un.h.
 struct sockaddr_un {
    unsigned char  sun_len;
    unsigned char  sun_family;
             char  sun_path[108];        /* pathname */
};

The sun_family field is set to AF_UNIX.

The sun_path field contains the NULL-terminated pathname, and sun_len contains the length of the pathname.
Notes:
  1. For AF_UNIX, when a bind is issued, a file is created with a mode of 660. In order to allow other users to access this file, a chmod() should be issued to modify this mode if desired.
  2. For AF_UNIX, when closing sockets that were bound, you should also use unlink() to delete the file created at bind() time.
  3. The pathname the client uses on the bind() must be unique.
  4. The sendto() call must specify the pathname associated with the server.
  5. For AF_INET or AF_INET6, the user must have appropriate privileges to bind to a port in the range from 1 to 1023.

Special Behavior for C++

To use this function with C++, you must use the _XOPEN_SOURCE_EXTENDED 1 feature test macro.

Note: The bind() function has a dependency on the level of the Enhanced ASCII Extensions. See Enhanced ASCII support for details.

Returned value

If successful, bind() returns 0.

If unsuccessful, bind() returns -1 and sets errno to one of the following values:
Error Code
Description
EACCES
Permission denied.
EADDRINUSE
The address is already in use. See the SO_REUSEADDR option described under getsockopt() — Get the options associated with a socket and the SO_REUSEADDR described under the setsockopt() — Set options associated with a socket for more information.
EADDRNOTAVAIL
The address specified is not valid on this host. For example, the Internet address does not specify a valid network interface.
EAFNOSUPPORT
The address family is not supported (it is not AF_UNIX, AF_INET, or AF_INET6).
EBADF
The socket parameter is not a valid socket descriptor.
EINVAL
One of three conditions may apply:
  • The socket is already bound to an address—for example, trying to bind a name to a socket that is already connected.
  • The socket was shut down.
  • An incorrect parameter was passed on the bind() invocation.
Check the parameter values passed and ensure they are specified as described above.
EIO
There has been a network or transport failure.
ENOBUFS
bind() is unable to obtain a buffer due to insufficient storage.
ENOTSOCK
The descriptor is for a file, not for a socket.
EOPNOTSUPP
The socket type of the specified socket does not support binding to an address.
EPERM
The user is not authorized to bind to the port specified.
The following are for AF_UNIX only:
Error Code
Description
EACCES
A component of the path prefix denies search permission, or the requested name requires writing in a directory with a mode that denies write permission.
EDESTADDRREQ
The address argument is a NULL pointer.
EIO
An I/O error occurred.
ELOOP
Too many symbolic links were encountered in translating the pathname in address.
ENAMETOOLONG
A component of a pathname exceeded NAME_MAX characters, or an entire pathname exceeded PATH_MAX characters.
ENOENT
A component of the pathname does not name an existing file or the pathname is an empty string.
ENOTDIR
A component of the path prefix of the pathname in address is not a directory.
EROFS
The name would reside on a read-only file system.

Example

The following are examples of the bind() call. It is a good idea to zero the structure before using it to ensure that the name requested does not set any reserved fields.

AF_INET Domain Example

The following example illustrates the bind() call binding to interfaces in the AF_INET domain. The Internet address and port must be in network byte order. To put the port into network byte order, the htons() utility routine is called to convert a short integer from host byte order to network byte order. The address field is set using another utility routine, inet_addr(), which takes a character string representing the dotted-decimal address of an interface and returns the binary Internet address representation in network byte order.
int rc;
int s;
struct sockaddr_in myname;
/* Bind to a specific interface in the Internet domain */
/* make sure the sin_zero field is cleared */
memset(&myname, 0, sizeof(myname));
myname.sin_family = AF_INET;
myname.sin_addr.s_addr = inet_addr("129.5.24.1"); 
/* specific interface */
myname.sin_port = htons(1024);
⋮
rc = bind(s, (struct sockaddr *) &myname, 
sizeof(myname));
/* Bind to all network interfaces in the Internet domain */
/* make sure the sin_zero field is cleared */
memset(&myname, 0, sizeof(myname));
myname.sin_family = AF_INET;
myname.sin_addr.s_addr = INADDR_ANY; /* specific interface */
myname.sin_port = htons(1024);
⋮
rc = bind(s, (struct sockaddr *) &myname, 
sizeof(myname));
/* Bind to a specific interface in the Internet domain.
   Let the system choose a port                        */
/* make sure the sin_zero field is cleared */
memset(&myname, 0, sizeof(myname));
myname.sin_family = AF_INET;
myname.sin_addr.s_addr = inet_addr("129.5.24.1"); 
/* specific interface */
myname.sin_port = 0;
⋮
rc = bind(s, (struct sockaddr *) &myname, 
sizeof(myname));

AF_UNIX Domain Example

The following example illustrates the bind() call binding to interfaces in the AF_UNIX domain.
/* Bind to a name in the UNIX domain */
struct sockaddr_un myname;
char socket_name[]="/tmp/socket.for._";
⋮
memset(&myname, 0, sizeof(myname));
myname.sun_family = AF_UNIX;
strcpy(myname.sun_path,socket_name);
myname.sun_len = sizeof(myname.sun_path);
⋮
rc = bind(s, (struct sockaddr *) &myname, SUN_LEN(&myname));

Related information