bind(2) System Calls Manual bind(2)

bind - enlaza un nombre a un conector (socket)

Biblioteca Estándar C (libc, -lc)

#include <sys/socket.h>
int bind(int sockfd, const struct sockaddr *addr,
         socklen_t addrlen);

When a socket is created with socket(2), it exists in a name space (address family) but has no address assigned to it. bind() assigns the address specified by addr to the socket referred to by the file descriptor sockfd. addrlen specifies the size, in bytes, of the address structure pointed to by addr. Traditionally, this operation is called “assigning a name to a socket”.

Normalmente, es necesario asignar una dirección local usando bind() a un conector SOCK_STREAM antes de que éste pueda recibir conexiones (vea accept(2)).

Las reglas usadas en el enlace de nombres varían entre familias de direcciones. Consulte las entradas de manual de la Sección 7 para obtener una información más detallada. Para AF_INET vea ip(7), para AF_INET6 vea ipv6(7), para AF_UNIX vea unix(7), para AF_APPLETALK vea ddp(7), para AF_PACKET vea packet(7), para AF_X25 vea x25(7) y para AF_NETLINK vea netlink(7).

The actual structure passed for the addr argument will depend on the address family. The sockaddr structure is defined as something like:


struct sockaddr {
    sa_family_t sa_family;
    char        sa_data[14];
}

The only purpose of this structure is to cast the structure pointer passed in addr in order to avoid compiler warnings. See EXAMPLES below.

En caso de éxito se devuelve cero. En caso de error se devuelve -1, y errno se configura para indicar el error.

La dirección está protegida y el usuario no es el superusuario.
The given address is already in use.
(Internet domain sockets) The port number was specified as zero in the socket address structure, but, upon attempting to bind to an ephemeral port, it was determined that all port numbers in the ephemeral port range are currently in use. See the discussion of /proc/sys/net/ipv4/ip_local_port_range ip(7).
sockfd no es un descriptor de archivo válido.
The socket is already bound to an address.
addrlen is wrong, or addr is not a valid address for this socket's domain.
El descriptor de archivo sockfd no se refiere a un conector.

Los siguientes errores son específicos a los conectores del dominio UNIX (AF_UNIX):

El permiso de búsqueda ha sido denegado en uno de los componentes de la ruta. Consulte path_resolution(7).
Se requirió una interfaz inexistente o una dirección no local.
addr señala fuera del espacio de direcciones accesible por el usuario.
Se han encontrado demasiados enlaces simbólicos al resolver addr.
addr es demasiado larga.
No existe algún componente del prefijo del directorio del nombre de ruta del conector.
No hay disponible suficiente memoria del núcleo.
Un componente del prefijo de la ruta no es un directorio.
El nodo-i del conector reside en un sistema de ficheros de `sólo lectura'.

POSIX.1-2008.

POSIX.1-2001, SVr4, 4.4BSD (bind() first appeared in 4.2BSD).

No están descritas las opciones de proxy transparente.

An example of the use of bind() with Internet domain sockets can be found in getaddrinfo(3).

The following example shows how to bind a stream socket in the UNIX (AF_UNIX) domain, and accept connections:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#define MY_SOCK_PATH "/somepath"
#define LISTEN_BACKLOG 50
#define handle_error(msg) \
    do { perror(msg); exit(EXIT_FAILURE); } while (0)
int
main(void)
{
    int                 sfd, cfd;
    socklen_t           peer_addr_size;
    struct sockaddr_un  my_addr, peer_addr;
    sfd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (sfd == -1)
        handle_error("socket");
    memset(&my_addr, 0, sizeof(my_addr));
    my_addr.sun_family = AF_UNIX;
    strncpy(my_addr.sun_path, MY_SOCK_PATH,
            sizeof(my_addr.sun_path) - 1);
    if (bind(sfd, (struct sockaddr *) &my_addr,
             sizeof(my_addr)) == -1)
        handle_error("bind");
    if (listen(sfd, LISTEN_BACKLOG) == -1)
        handle_error("listen");
    /* Now we can accept incoming connections one
       at a time using accept(2). */
    peer_addr_size = sizeof(peer_addr);
    cfd = accept(sfd, (struct sockaddr *) &peer_addr,
                 &peer_addr_size);
    if (cfd == -1)
        handle_error("accept");
    /* Code to deal with incoming connection(s)... */
    if (close(sfd) == -1)
        handle_error("close");
    if (unlink(MY_SOCK_PATH) == -1)
        handle_error("unlink");
}

accept(2), connect(2), getsockname(2), listen(2), socket(2), getaddrinfo(3), getifaddrs(3), ip(7), ipv6(7), path_resolution(7), socket(7), unix(7)

La traducción al español de esta página del manual fue creada por Miguel Angel Sepulveda <angel@vivaldi.princeton.edu>, Juan Piernas <piernas@ditec.um.es> y Marcos Fouces <marcos@debian.org>

Esta traducción es documentación libre; lea la GNU General Public License Version 3 o posterior con respecto a las condiciones de copyright. No existe NINGUNA RESPONSABILIDAD.

Si encuentra algún error en la traducción de esta página del manual, envíe un correo electrónico a debian-l10n-spanish@lists.debian.org.

31 Octubre 2023 Páginas de manual de Linux 6.06