Chapter Contents |
Previous |
Next |
bind |
Portability: | UNIX compatible |
SYNOPSIS | |
DESCRIPTION | |
RETURN VALUE | |
PORTABILITY | |
EXAMPLE | |
RELATED FUNCTIONS |
SYNOPSIS |
#include <sys/types.h> #include <sys/socket.h> int bind(int s, const void *addr, int addrlen);
DESCRIPTION |
bind
assigns a name to an unnamed socket
s
. When a socket is created, it exists in an address family, but it
does not have a name assigned to it. Servers use
bind
to associate themselves with a well-known port. Servers may also
use
bind
to restrict access
by other network addresses on a host with multiple network addresses.
bind
enables a connectionless
client to have an address that the server can use for responses.
For addresses in the
AF_INET
family,
addr
points to a
sockaddr
or
sockaddr_in
structure.
addrlen
is the length of the
address, in bytes.
addrlen
should be greater than or equal to the size of the
sockaddr
or
sockaddr_in
structure. The
INADDR_ANY
constant in the
<netinet/in.h>
header file specifies that the network address is not restricted.
If the
sin_port
field
of the
sockaddr
structure
is zero,
bind
chooses a
port. Alternatively, a well-known port number can be passed in the
sin_port
field. Internet host
addresses and port numbers in
sockaddr_in
are always in network byte order. The remainder of the
sockaddr
or
sockaddr_in
structure should be
0
.
Upon return, if a port of
0
was specified, the selected port
value is filled in. On return,
the structure pointed to by
addr
should be the same as the structure pointed to by
getsockname
for this socket
s
.
RETURN VALUE |
If
bind
is successful, it returns a
0
; otherwise, it returns a
-1
and sets
errno
to indicate the type of error.
PORTABILITY |
bind
is portable to other environments, including most UNIX systems,
that implement BSD sockets.
EXAMPLE |
In this example,
bind
assigns socket
s
to an arbitrary port without restriction by network address.
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <string.h> #include <stdio.h> f() { struct sockaddr_in sa; int s; struct servent *serv; . . . /* Specify the port. */ memset(&sa,'\0',sizeof(sa)); sa.sin_family = AF_INET; sa.sin_addr.s_addr = INADDR_ANY; sa.sin_port = serv->s_port; if (bind(s, &sa, sizeof(sa)) == -1) { perror("bind() failed"); return -1; } . . . /* Let TCP/IP choose the port. */ memset(&sa,'\0',sizeof(sa)); sa.sin_family = AF_INET; sa.sin_addr.s_addr = INADDR_ANY; sa.sin_port = 0; if (bind(s, &sa, sizeof(sa)) == -1) { perror("bind() failed"); return -1; } . . . }
RELATED FUNCTIONS |
connect
,
getservbyname
,
getsockname,
htons
Chapter Contents |
Previous |
Next |
Top of Page |
Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.