Expand example program, and move it to new EXAMPLE section.

This commit is contained in:
Michael Kerrisk 2007-05-28 10:38:13 +00:00
parent 35bf3cc818
commit 185f68728f
1 changed files with 61 additions and 43 deletions

View File

@ -63,7 +63,7 @@
.\" $Id: bind.2,v 1.3 1999/04/23 19:56:07 freitag Exp $
.\" Modified 2004-06-23 by Michael Kerrisk <mtk-manpages@gmx.net>
.\"
.TH BIND 2 2004-06-23 "Linux 2.6.7" "Linux Programmer's Manual"
.TH BIND 2 2007-06-08 "Linux" "Linux Programmer's Manual"
.SH NAME
bind \- bind a name to a socket
.SH SYNOPSIS
@ -147,48 +147,7 @@ The only purpose of this structure is to cast the structure
pointer passed in
.I my_addr
in order to avoid compiler warnings.
The following example shows how this is done when binding a socket
in the Unix
.RB ( AF_UNIX )
domain:
.in +0.25in
.nf
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MY_SOCK_PATH "/somepath"
int
main(int argc, char *argv[])
{
int sfd;
struct sockaddr_un addr;
sfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sfd == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
memset(&addr, 0, sizeof(struct sockaddr_un));
/* Clear structure */
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, MY_SOCK_PATH,
sizeof(addr.sun_path) - 1);
if (bind(sfd, (struct sockaddr *) &addr,
sizeof(struct sockaddr_un)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
...
}
.fi
.in -0.25in
See EXAMPLE below.
.SH "RETURN VALUE"
On success, zero is returned.
On error, \-1 is returned, and
@ -281,6 +240,65 @@ Some POSIX confusion resulted in the present
also used by glibc.
See also
.BR accept (2).
.SH EXAMPLE
.\" unix.7 refers to this example.
The following example shows how to bind a stream socket in the Unix
.RB ( AF_UNIX )
domain, and accept connections:
.in +0.25in
.nf
#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
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) {
perror("socket");
exit(EXIT_FAILURE);
}
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) {
perror("bind");
exit(EXIT_FAILURE);
}
if (listen(sfd, LISTEN_BACKLOG) == -1) {
perror("listen");
exit(EXIT_FAILURE);
}
/* 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) == -1) {
perror("accept");
exit(EXIT_FAILURE);
}
}
.fi
.in -0.25in
.SH BUGS
The transparent proxy options are not described.
.SH "SEE ALSO"