我正在编写一个基本的hello world网络程序,但是当我在客户端中调用write
时,程序就会停止。有谁知道为什么会这样?该函数不返回任何内容:
const char* msg = "Hello World!\n";
char buffer[256];
int sockfd, n;
struct sockaddr_in srv_ip4;
struct hostent* server;
puts ("a");
sockfd = socket (AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror ("Unable to open socket");
return false;
}
puts ("b");
server = gethostbyname (addr);
if (!server) {
fprintf (stderr, "Unable to find host: %s\n", addr);
return false;
}
memset (&srv_ip4, 0, sizeof (struct sockaddr_in));
puts ("c");
srv_ip4.sin_family = AF_INET;
memcpy (&srv_ip4.sin_addr.s_addr, server->h_addr, server->h_length);
srv_ip4.sin_port = htons (PORT);
puts ("d");
n = write (sockfd, msg, 13);
if (n < 0) {
puts ("Why?");
perror ("Unable to write to socket");
return false;
}
memset (buffer, 0, 256);
puts ("e");
n = read (sockfd, buffer, 255);
if (n < 0) {
perror ("Unable to read from socket");
return false;
}
printf ("%s", buffer);
puts ("f");
close (sockfd);
return true;
输出结果为:
a b c d