theeggman85
theeggman85

Reputation: 1825

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()?

Upvotes: 3

Views: 3196

Answers (1)

goji
goji

Reputation: 7092

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

Upvotes: 2

Related Questions