We relied on the createClientSocket to establish a connection with a server running on a specified hostname and port.
- Here's the code that establishes a connection to the server/port pair of interest:
static const int kClientSocketError = -1;
int createClientSocket(const string& host, unsigned short port) {
struct hostent *he = gethostbyname(host.c_str());
if (he == NULL) return kClientSocketError;
int s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0) return kClientSocketError;
struct sockaddr_in serverAddress;
memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(port);
serverAddress.sin_addr.s_addr = ((struct in_addr *)he->h_addr)->s_addr;
if (connect(s, (struct sockaddr *) &serverAddress,
sizeof(serverAddress)) == 0) return s;
close(s);
return kClientSocketError;
}
- At the end of it all, the s is the client-end socket descriptor that can be used to manage a two-way conversation with the service running on the remote host/port pair.
- There's obviously some mystery as to how the connect system call associates the socket descriptor with the host/port pair, but because it's a system-level service (that's what system calls are, no?), we really have to choice but to assume it works.