The bind() system call associates an address with the socket descriptor.

int bind(int sockfd, struct sockaddr *myaddr, int addrlen);

The first parameter is the socket descriptor from the socket() call, sockfd.

The second parameter is a pointer to the socket address structure, which is generalized for different protocols. The sockaddr structure is defined in <sys/socket.h>.

The third parameter is the length of the sockaddr structure, because it can vary.

In the sockaddr structure for IPv4 sockets, the first field specifies AF_INET. The second field sin_port can be any integer > 5000. Lower port numbers are reserved for specific services. The third field in_addr is the Internet address in dotted-quad notation. For the server, you can use the constant INADDR_ANY to tell the system to accept a connection on any Internet interface for the system. Conversion functions htons() and htonl() are for hardware independence. For example:

#define SERV_PORT 5432
     struct sockaddr_in serv_addr;
     bzero((char *) &serv_addr, sizeof(serv_addr));
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_port = htons(SERV_PORT);
     serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
     bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));