gpt4 book ai didi

c - "Connected"UDP套接字,双向通信?

转载 作者:行者123 更新时间:2023-11-30 19:03:30 24 4
gpt4 key购买 nike

如何在连接的 UDP 套接字上实现 2 路通信?

我可以从客户端向服务器发送消息,但无法从服务器获取消息。这是我的代码。我认为问题一定出在服务器端,但我不知道如何解决该问题。我故意删除了错误检查,只是为了在 SO 上发布并保持我的帖子简短。我没有收到任何方面的任何错误。

我可以使用未连接 UDP 套接字运行该程序,但不能使用已连接套接字运行。

服务器.c

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>

int main()
{
int sockfd;
struct sockaddr_in me;
char buffer[1024];

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

memset(&me, '\0', sizeof(me));
me.sin_family = AF_INET;
me.sin_port = htons(8080);
me.sin_addr.s_addr = inet_addr("127.0.0.1");

bind(sockfd, (struct sockaddr *)&me, sizeof(me));

recv(sockfd, buffer, 1024, 0);
printf("[+]Data Received: %s\n", buffer);

strcpy(buffer, "Hello Client\n");
send(sockfd, buffer, 1024, 0);
printf("[+]Data Send: %s\n", buffer);

return 0;
}

Client.c

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>

int main()
{
int sockfd;
struct sockaddr_in other;
char buffer[1024];

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

memset(&other, '\0', sizeof(other));
other.sin_family = AF_INET;
other.sin_port = htons(8080);
other.sin_addr.s_addr = inet_addr("127.0.0.1");

connect(sockfd, (struct sockaddr *)&other, sizeof(other));

strcpy(buffer, "Hello Server\n");
send(sockfd, buffer, 1024, 0);
printf("[+]Data Send: %s\n", buffer);

recv(sockfd, buffer, 1024, 0);
printf("[+]Data Received: %s\n", buffer);

return 0;
}

服务器输出

[+]Data Received: Hello Server
[+]Data Send: Hello Client

客户端的输出

[+]Data Send: Hello Server
// Here it does not receive the message sent by server.

最佳答案

在Linux上,strace可执行文件,服务器发送确实这样说:

sendto(3, "Hello Client\n\0\0\0\310$\220\4J\177\0\0\0\0\0\0\0\0\0\0"...,
1024, 0, NULL, 0) = -1 EDESTADDRREQ (Destination address required)

即服务器套接字确实不知道它需要发送到的地址。 任何 UDP 套接字都必须通过 connecting、sendto< 中提供目标套接字地址来让套接字的另一端知道。UDP 套接字上的connect 意味着只需为send 设置默认地址。

<小时/>

要与未知方连接“服务器”端的套接字,您应该使用 recvfrom 找出发送方的套接字地址 - 然后您可以connect 使用此地址或继续使用 sendto。通过sendto,同一个套接字可以同时与许多不同的各方进行通信。

<小时/>

TCP 服务器/客户端套接字是一种不同的情况,因为服务器端的监听/接受返回一个连接的套接字,该套接字与原始服务器套接字不同。

关于c - "Connected"UDP套接字,双向通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53901695/

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