3

recvfrom()在我的 C 程序中使用从多个客户端接收 UDP 数据包,这些客户端可以使用自定义用户名登录。一旦他们登录,我希望他们的用户名与唯一的客户端进程配对,以便服务器通过数据包的来源自动知道用户是谁。如何从我收到的数据包中获取此信息recvfrom()

4

1 回答 1

2
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>

int main()
{
  int sock = socket(AF_INET, SOCK_DGRAM, 0);

  struct sockaddr_in addr;
  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  addr.sin_port = htons(1234);
  addr.sin_addr.s_addr = INADDR_ANY;

  bind(sock, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr));

  char message[256];
  struct sockaddr_in from;
  socklen_t fromLen = sizeof(from);
  recvfrom(sock, message, sizeof(message), 0, reinterpret_cast<struct sockaddr*>(&from), &fromLen);

  char ip[16];
  inet_ntop(AF_INET, &from.sin_addr, ip, sizeof(ip));

  std::cout << ip << ":" << ntohs(from.sin_port) << " - " << message << std::endl;
于 2012-10-28T01:59:05.657 回答