A socket is created without a name. Until a name is bound to a socket, processes have no way to reference it and consequently no messages may be received on it. Communicating processes are bound by an association. In the Internet domain, an association is composed of local and foreign addresses, and local and foreign ports, while in the UNIX domain, an association is composed of local and foreign pathnames.
In most domains, associations must be unique.
In the Internet domain there may never be duplicate tuples, 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 may never be duplicate tuples of the type:
<protocol, local pathname, foreign pathname>
Currently, the pathnames may not refer to files already existing on the system, though this may change in future releases.
system call allows a process to specify half of
an association, for example
<local address, local port> (or <local pathname>)
while the connect and accept primitives are used to complete a socket's association.
The bind system call is used as follows:
bind(s, name, namelen);The bound name is a variable length byte string that is interpreted by the supporting protocol(s). Its interpretation may vary between communication domains (this is one of the properties that comprises a domain). Whereas Internet domain names contain an Internet address and port number, UNIX domain names contain a pathname and a family. The family is always AF_UNIX. The following code would be used to bind the name /tmp/foo to a UNIX domain socket:
#include <sys/un.h> ... struct sockaddr_un addr; ... strcpy(addr.sun_path, "/tmp/foo"); addr.sun_len = sizeof(addr); addr.sun_family = AF_UNIX; bind(s, (struct sockaddr *) &addr, strlen(addr.sun_path) + offsetof(struct sockaddr_un, sun_path));Note that in determining the size of a UNIX domain address, null bytes are not counted, which is why strlen is used. The file name referred to in addr.sun_path is created as a socket in the system file space. The caller must, therefore, have write permission in the directory where addr.sun_path is to reside, and the file should be deleted by the caller when it is no longer needed.
In binding an Internet address things become more complicated. The call itself is similar,
#include <sys/types.h> #include <netinet/in.h> ... struct sockaddr_in sin; ... bind(s, (struct sockaddr *) &sin, sizeof(sin));but the selection of what to place in the address sin requires some discussion. We will come back to the problem of formulating Internet addresses in ``Supporting routines'' when the library routines used in name resolution are discussed.