POSIX Sockets Connecting to a remote host



Given the name of a server as a string, char* servername, and a port number, int port, the following code creates and opens a socket connected to that server. The "name" of the server can either be a DNS name, such as "www.stackoverflow.com," or an IP address in standard notation, such as ""; either input format is valid for gethostbyname (which had been removed from POSIX.1-2008).

char * server = "www.example.com";

int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0) 
  perror("Failed to create a socket");

hostent *server = gethostbyname(servername);
if (server == NULL) 
  perror("Host lookup failed");

char server_ip_str[server->h_length];
inet_ntop(AF_INET, server->h_addr, server_ip_str, server->h_length);

sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length);

if (connect(sock, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
    perror("Failed to connect");

// Now you can call read, write, etc. on the socket.