<< Prev | Beej's Guide to Network Programming | Next >> |
Associate a socket with an IP address and port number
#include <sys/types.h> #include <sys/socket.h> int bind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen);
When a remote machine wants to connect to your server program, it needs two pieces of information: the IP address and the port number. The bind() call allows you to do just that.
First, you call getaddrinfo() to load up a struct sockaddr with the destination address and port information. Then you call socket() to get a socket descriptor, and then you pass the socket and address into bind(), and the IP address and port are magically (using actual magic) bound to the socket!
If you don't know your IP address, or you know you only have one IP address on the machine, or you don't care which of the machine's IP addresses is used, you can simply pass the AI_PASSIVE flag in the hints parameter to getaddrinfo(). What this does is fill in the IP address part of the struct sockaddr with a special value that tells bind() that it should automatically fill in this host's IP address.
What what? What special value is loaded into the struct
sockaddr's IP address to cause it to auto-fill the address with
the current host? I'll tell you, but keep in mind this is only if
you're filling out the
Lastly, the addrlen parameter should be set to sizeof my_addr.
Returns zero on success, or -1 on error (and errno will be set accordingly.)
// modern way of doing things with getaddrinfo() struct addrinfo hints, *res; int sockfd; // first, load up address structs with getaddrinfo(): memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // fill in my IP for me getaddrinfo(NULL, "3490", &hints, &res); // make a socket: // (you should actually walk the "res" linked list and error-check!) sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); // bind it to the port we passed in to getaddrinfo(): bind(sockfd, res->ai_addr, res->ai_addrlen);
// example of packing a struct by hand, IPv4 struct sockaddr_in myaddr; int s; myaddr.sin_family = AF_INET; myaddr.sin_port = htons(3490); // you can specify an IP address: inet_pton(AF_INET, "63.161.169.137", &myaddr.sin_addr.s_addr); // or you can let it automatically select one: myaddr.sin_addr.s_addr = INADDR_ANY; s = socket(PF_INET, SOCK_STREAM, 0); bind(s, (struct sockaddr*)&myaddr, sizeof myaddr);
getaddrinfo(),
socket(),
<< Prev | Beej's Guide to Network Programming | Next >> |