Transport Interfaces Programming Guide

Binding Local Names

A socket is created with no name. A remote process has no way to refer to a socket until an address is bound to it. Communicating processes are connected through addresses. In the Internet domain, a connection is composed of local and remote addresses, and local and remote ports. In the UNIX domain, a connection is composed of (usually) one or two path names. In most domains, connections must be unique.

In the Internet domain, there can never be duplicate ordered sets, such as: protocol, local address, local port, foreign address, foreign port. UNIX domain sockets need not always be bound to a name, but, when bound, there can never be duplicate ordered sets such as: local pathname or foreign pathname. The path names cannot refer to existing files.

The bind() call allows a process to specify the local address of the socket. This forms the set local address, local port (or local pathname) while connect() and accept() complete a socket's association by fixing the remote half of the address tuple. The bind() function call is used as follows:


bind (s, name, namelen);

The socket handle is s. The bound name is a byte string that is interpreted by the supporting protocol(s). Internet domain names contain an Internet address and port number. UNIX domain names contain a path name and a family. Example 2-1 shows binding the name /tmp/foo to a UNIX domain socket.


Example 2-1 Bind Name to Socket


#include <sys/un.h>
 ...
struct sockaddr_un addr;
 ...
strcpy(addr.sun_path, "/tmp/foo");
addr.sun_family = AF_UNIX;
bind (s, (struct sockaddr *) &addr,
		strlen(addr.sun_path) + sizeof (addr.sun_family));

When determining the size of an AF_UNIX socket address, null bytes are not counted, which is why strlen() use is fine.

The file name referred to in addr.sun_path is created as a socket in the system file name space. The caller must have write permission in the directory where addr.sun_path is created. The file should be deleted by the caller when it is no longer needed. AF_UNIX sockets can be deleted with unlink().

Binding an Internet address is more complicated but the call is similar:


#include <sys/types.h>
#include <netinet/in.h>
...
struct sockaddr_in sin;
...
		s = socket(AF_INET, SOCK_STREAM, 0);
		sin.sin_family = AF_INET;
		sin.sin_addr.s_addr = htonl(INADDR_ANY);
		sin.sin_port = htons(MYPORT);
		bind(s, (struct sockaddr *) &sin, sizeof sin);

The content of the address sin is described in "Address Binding", where Internet address bindings are discussed.