| |||||
| |||||
![]() |
|||||
|
BIND
2
2007-12-28
Linux
Linux Programmer's Manual
socket(2) , it exists in a name space (address family) but has no address assigned to it. bind () assigns the address specified to 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 {
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 EXAMPLE below.
The third argument of bind () is in reality an int (and this is what 4.x BSD and libc4 and libc5 have). Some POSIX confusion resulted in the present socklen_t , also used by glibc. See also accept(2) .
The following example shows how to bind a stream socket in the 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) \
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(struct sockaddr_un));
/* 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(struct sockaddr_un)) == -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(struct sockaddr_un);
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) */
}
| |||||
|
| |||||