gpt4 book ai didi

c - 写入套接字退出程序

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:38:12 26 4
gpt4 key购买 nike

我正在编写一个基本的 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

最佳答案

你应该connect发送数据之前到服务器。

通过this article .

关于c - 写入套接字退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22250591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com