連線到遠端主機

Version < POSIX.1-2008

給定伺服器的名稱為字串 char* servername 和埠號 int port,以下程式碼建立並開啟連線到該伺服器的套接字。伺服器的名稱可以是 DNS 名稱,例如“www.stackoverflow.com”,也可以是標準表示法中的 IP 地址,例如“192.30.253.113”; 輸入格式對 gethostbyname已從 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.

close(sock);