如何识别iOS设备上收到的udp数据包的发件人ip地址? [英] How to identify sender's ip address of a udp packet received on iOS device?
问题描述
如何找出运行iOS 3.2
或更高版本的设备上接收到的udp数据包的发件人的ip地址?
How to find out the sender's ip address of a udp packet that was received on a device running iOS 3.2
or higher?
例如,如果在计算机上使用Python,我将使用SocketServer.UDPServer
,该类带有SocketServer.BaseRequestHandler
的子类,该子类定义了handle
回调.数据包到达时,将调用回调,发送方的IP地址将位于self.client_address
中,其中self
是SocketServer.BaseRequestHandler
实例.
For example, if using Python on a computer, I'd use SocketServer.UDPServer
which takes a subclass of SocketServer.BaseRequestHandler
which defines the handle
callback. When a packet arrives, the callback is called and the sender's ip address would be in self.client_address
, where self
is the SocketServer.BaseRequestHandler
instance.
不幸的是,当我在Objective C中编程并使用为iOS提供的框架时,我不知道如何提取此信息或访问相关的ip标头.
Unfortunately, I don't know how to extract this information or gain access to the associated ip header when programming in Objective C and using the frameworks provided for iOS.
现在,我唯一的解决方案是在udp数据包的主体上显式地编写发件人的ip,但我宁愿不依赖发件人将信息放在那儿.
Right now the only solution I have is to explicitly write the sender's ip on the body of the udp packet, but I'd rather not rely on the sender putting that information there if I don't have to.
推荐答案
您没有提到要使用什么API来接收数据包.不要将IP地址写入数据包本身,因为数据包在到达您之前可能会经过许多网络地址转换.
You didn't mention what API you are using to receive the packet. Don't write the IP address into the packet itself because the packet may go through a number of network address translations before it gets to you.
您可以使用常规BSD套接字来完成此任务.还有一些基础类围绕BSD套接字包装,但是我没有亲自使用它们,所以我不能给你一个很好的例子.
You can use regular BSD sockets to acheive this task. There are also a few Foundation classes that wrap around BSD sockets, but I haven't used them personally, so I can't give you a decent example.
// for IPv4 (IPv6 is a little different)
ssize_t received;
char buffer[0x10000];
struct sockaddr_in listenAddr;
struct sockaddr_in fromAddr;
socklen_t fromAddrLen = sizeof fromAddr;
listenAddr.sin_family = AF_INET;
listenAddr.sin_port = htons(12345); // change to whatever port
listenAddr.sin_addr.s_addr = htonl(INADDR_ANY);
int s = socket(AF_INET, SOCK_DGRAM, 0); // create UDP socket
if (s == -1)
exit(1); // failed to create socket
if (bind(s, (struct sockaddr *) &listenAddr, sizeof listenAddr))
exit(2); // failed to bind to port 12345 for any address
received = recvfrom(s, buffer, sizeof buffer, 0, (struct sockaddr *)&fromAddr, &fromAddrLen);
if (received == -1)
exit(3); // some failure trying to receive data
// check the contents of buffer, the address of the source will be in
// fromAddr.sin_addr.s_addr but only if (fromAddrLen == sizeof fromAddr)
// after the call to recvfrom.
char display[16] = {0};
inet_ntop(AF_INET, &fromAddr.sin_addr.s_addr, display, sizeof display);
NSLog (@"The source is %s.", display);
// could show "The source is 201.19.91.102."
这篇关于如何识别iOS设备上收到的udp数据包的发件人ip地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!