C Sendto 重复执行时不起作用

标签 c linux sockets

在 C 中使用 sendto() 时,我遇到了一个奇怪的问题。我有以下代码:

struct sockaddr_in currSocket;
int currSocketLength = sizeof(currSocket);
memset((char *)&currSocket, 0, sizeof(currSocket));
currSocket.sin_family = AF_INET;
currSocket.sin_port = htons(serverPortNumber);
// add the server IP address
inet_aton(serverIP, &currSocket.sin_addr);

int send_result = sendto(masterSocket, bufferToSend , 1000, 0, (struct sockaddr *) &currSocket, currSocketLength);
if (send_result < 0) {
    perror("Something is wrong");
}
bzero(bufferToSend, 1000);

当我第一次在 bufferToSend 中发送数据时,这非常有用。但是,如果我想以完全相同的方式再次发送数据(按照上面的代码 - 创建套接字并将其发送到那里),则不会收到数据。这是为什么?我该如何解决它?

编辑: 经过更多研究后,我意识到这是因为我的 IP 地址字符串被覆盖而错误。在我之前阅读之后,它的值似乎发生了变化。

// here the IP address is fine
printf("%s\n", ipAddress);
char bufferFromSocket[512];
int amount_read = read(masterSocket, bufferFromSocket, 512);
// here the IP address is overwritten by whatever is in bufferFromSocket
printf("%s\n", ipAddress);

有什么想法为什么会发生这种情况吗?

最佳答案

我没有为 ipAddress 分配足够的空间。将它作为指针,而它应该是 char[],我使用 strcpy 复制到它。

关于C Sendto 重复执行时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58828684/

相关文章:

java - Netty TCP 套接字输入流

c - 使用 bindgen 绑定(bind)基于 TPM 的服务的 tbs.h 时出现 "unknown type name"

c - malloc之后,如何获取更多的还是连续的内存呢?

c - 当你除以十六进制时,你会得到什么?

linux - 将代码从 Microsoft Visual C++ 迁移到 debian (raspberry)

linux - vim:在 block 的开头插入不起作用

c - 如何将一个文件中以 #include 开头的所有行写入到另一个文件中

linux - 如何找到 dash-exec 命令的 PID

c - 在没有 bzero 的 sockaddr_in 上套接字绑定(bind)失败

c - 套接字接收后的 Memcpy 不起作用