bind (2) - Linux Manuals
bind: bind a name to a socket
NAME
bind - bind a name to a socket
SYNOPSIS
#include <sys/types.h> /* See NOTES */ #include <sys/socket.h> int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
DESCRIPTION
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".It is normally necessary to assign a local address using bind() before a SOCK_STREAM socket may receive connections (see accept(2)).
The rules used in name binding vary between address families. Consult the manual entries in Section 7 for detailed information. For AF_INET, see ip(7); for AF_INET6, see ipv6(7); for AF_UNIX, see unix(7); for AF_APPLETALK, see ddp(7); for AF_PACKET, see packet(7); for AF_X25, see x25(7); and for AF_NETLINK, see 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 {
The only purpose of this structure is to cast the structure
pointer passed in
addr
in order to avoid compiler warnings.
See EXAMPLES below.
The following errors are specific to UNIX domain
(AF_UNIX)
sockets:
For background on the
socklen_t
type, see
accept(2).
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 "/somepath"
#define LISTEN_BACKLOG 50
#define handle_error(msg) \
int
main(int argc, char *argv[])
{
RETURN VALUE
On success, zero is returned.
On error, -1 is returned, and
errno
is set appropriately.
ERRORS
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD
(bind()
first appeared in 4.2BSD).
NOTES
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.
BUGS
The transparent proxy options are not described.
EXAMPLES
An example of the use of
bind()
with Internet domain sockets can be found in
getaddrinfo(3).
COLOPHON
This page is part of release 5.10 of the Linux
man-pages
project.
A description of the project,
information about reporting bugs,
and the latest version of this page,
can be found at
https://www.kernel.org/doc/man-pages/.
SEE ALSO
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)