本文介绍了找到一个UDP数据包的源IP /流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 recvfrom的()
在我的C程序从mutltiple客户,谁可以用自定义的用户名登录,接收UDP数据包。一旦登录,我想他们的用户名与独特的客户端进程进行配对,让服务器自动知道用户是通过数据包来自哪里谁。我怎样才能从我收到 recvfrom的()
?
解决方案
的#include<&iostream的GT;
#包括LT&; SYS / socket.h中>
#包括LT&; ARPA / inet.h>
#包括LT&; CString的GT;诠释的main()
{
INT袜子=插座(AF_INET,SOCK_DGRAM,0); 结构sockaddr_in的地址;
memset的(放,地址,0,sizeof的(地址));
addr.sin_family = AF_INET;
addr.sin_port = htons(1234);
addr.sin_addr.s_addr = INADDR_ANY; 绑定(袜子,reinter pret_cast<结构sockaddr *>(安培;地址)的sizeof(地址)); CHAR消息[256];
结构SOCKADDR_IN从;
socklen_t的fromlen为此= sizeof的(从);
recvfrom的(袜子,消息的sizeof(消息),0,reinter pret_cast<结构sockaddr *>(安培;从),放大器; fromlen为此); 焦炭IP [16];
inet_ntop(AF_INET,&安培; from.sin_addr,IP的sizeof(IP)); 性病::法院LT&;< IP<< :&所述;&下;还有ntohs(from.sin_port)LT;< - &所述;&下;消息<<的std :: ENDL;
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 /流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!