简体   繁体   中英

Finding the source IP/process of a UDP packet

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM