【问题标题】:Finding the source IP/process of a UDP packet查找 UDP 数据包的源 IP/进程
【发布时间】:2012-10-28 09:59:05
【问题描述】:

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

【问题讨论】:

  • recvfrom函数返回的sockaddr结构需要使用inet_ntop和ntohs。
  • 这很好用。不过我遇到了一个问题,同一台计算机上的两个客户端应该有唯一的标识符,所以我在最后添加了端口。我在端口上使用 ntohs,但无法将其转换为 char*。我该怎么做?
  • 没关系,我使用sprintf() 来完成工作。感谢您的帮助!

标签: c sockets udp


【解决方案1】:
#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;

【讨论】:

    猜你喜欢
    • 2011-01-30
    • 2017-05-13
    • 2011-11-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    相关资源
    最近更新 更多