连接到远程主机

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);