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

标签 c sockets networking network-programming udp

如何在连接的 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/

相关文章:

c - 打开简历。如何将点和矩阵相乘 (CvMat)

c - 使用 fgets 和链表

c++ - Boost asio接收指定大小的数据

linux - 不需要 root 访问权限的优秀 Linux TCP/IP 监控工具?

linux - 如何通过Python脚本连接到同一网络但不同IP地址的远程Linux服务器

c - 这个c程序的输出很奇怪,而不是第二个位置第三行的值-4,它显示-5怎么办?

python - python 与 C 中的递归开销

c++ - 在同一端口上发送和接收 UDP

java - 无法在java中找到while循环行为

linux - HAProxy tcp方式源客户端ip