bind(2) System Calls Manual bind(2) bind - LIBRARY Standard C library (libc, -lc) #include 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". , SOCK_STREAM bind() , (. accept(2)). , , . . 7. AF_INET ip(7), AF_INET6 ipv6(7), AF_UNIX unix(7), AF_APPLETALK ddp(7), AF_PACKET packet(7), AF_X25 x25(7), AF_NETLINK netlink(7). , addr, . sockaddr : struct sockaddr { sa_family_t sa_family; char sa_data[14]; } , addr, . . . On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error. EACCES , . EADDRINUSE . EADDRINUSE ( ) , , , . /proc/sys/net/ipv4/ip_local_port_range ip(7). EBADF sockfd . EINVAL . EINVAL addrlen, addr . ENOTSOCK sockfd . UNIX (AF_UNIX): EACCES - (. path_resolution(7).) EADDRNOTAVAIL . EFAULT addr , . ELOOP addr . ENAMETOOLONG addr . ENOENT . ENOMEM . ENOTDIR . EROFS inode , . POSIX.1-2008. POSIX.1-2001, SVr4, 4.4BSD (bind() first appeared in 4.2BSD). , . bind() Internet getaddrinfo(3). UNIX (AF_UNIX) : #include #include #include #include #include #include #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) Artyom Kunyov , Azamat Hackimov , Dmitriy Ovchinnikov , Dmitry Bolkhovskikh , ITriskTI , Yuri Kozlov ; GNU 3 , . . , , . Linux man-pages 6.06 31 2023 . bind(2)