查找 UDP 数据包的源 IP/进程 [英] Finding the source IP/process of a UDP packet

查看:31
本文介绍了查找 UDP 数据包的源 IP/进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using recvfrom() in my C program to receive UDP packets from mutltiple clients, who can log in with a custom username. Once they log in, I would like their username to be paired with the unique client process, so the server automatically knows who the user is by where the packets come from. How can I get this information from the packet I receive with recvfrom()?

推荐答案

#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;

这篇关于查找 UDP 数据包的源 IP/进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆