Scroll to navigation

BIND(2) Manual del Programador de Linux BIND(2)

NOMBRE

bind - enlaza un nombre a un conector (socket)

SINOPSIS

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

DESCRIPCIÓN

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.

VALOR DEVUELTO

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

ERRORES

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'.

CONFORME A

POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD (bind() por primera vez en 4.2BSD).

NOTAS

POSIX.1 does not require the inclusion of <sys/types.h>, and this header file is not required on Linux. However, some historical (BSD) implementations required this header file, and portable applications are probably wise to include it.

Para saber más acerca del tipo socklen_t, consulte accept(2).

ERRORES

No están descritas las opciones de proxy transparente.

EJEMPLOS

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 <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MY_SOCK_PATH "/unaruta"
#define LISTEN_BACKLOG 50
#define handle_error(msg) \

do { perror(msg); exit(EXIT_FAILURE); } while (0) int main(int argc, char *argv[]) {
int sfd, cfd;
struct sockaddr_un my_addr, peer_addr;
socklen_t peer_addr_size;
sfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sfd == -1)
handle_error("socket");
memset(&my_addr, 0, sizeof(my_addr));
/* Clear structure */
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)... */
/* When no longer required, the socket pathname, MY_SOCK_PATH
should be deleted using unlink(2) or remove(3) */ }

VÉASE TAMBIÉN

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)

COLOFÓN

Esta página es parte de la versión 5.10 del proyecto Linux man-pages. Puede encontrar una descripción del proyecto, información sobre cómo informar errores y la última versión de esta página en https://www.kernel.org/doc/man-pages/.

TRADUCCIÓN

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.

1 Noviembre 2020 Linux