问题描述
您好我想通过objective-c获取iphone上的所有tcp / udp开放端口状态列表?像Linux上的netstat,你知道如何实现它,或者有任何API可以做到这一点?谢谢。
Hi I want to get all tcp/udp opening port status list on iphone by objective-c? like netstat on Linux, Do you know how to achieve it or it there any API can do that? Thanks.
推荐答案
你不能在iPhone上运行 netstat
(除非你越狱它,但你可以做 netstat
那样做。在。我确认您可以使用net.inet.tcp.pcblist
作为名称调用 sysctlbyname
并取回一堆数据。我没有尝试解释像 netstat
那样的数据。
You can't run netstat
on an iPhone (unless you jailbreak it), but you can do what netstat
does. Take a look at function protopr
in the netstat
source code. I verified that you can call sysctlbyname
with "net.inet.tcp.pcblist"
as the name and get back a bunch of data. I didn't try to interpret the data like netstat
does.
测试用例:
size_t len = 0;
if (sysctlbyname("net.inet.tcp.pcblist", 0, &len, 0, 0) < 0) {
perror("sysctlbyname");
} else {
char *buf = malloc(len);
sysctlbyname("net.inet.tcp.pcblist", buf, &len, 0, 0);
NSData *data = [NSData dataWithBytesNoCopy:buf length:len];
NSLog(@"data = %@", data);
}
运行iOS 5.0的iPad 2输出:
Output on my iPad 2 running iOS 5.0:
2011-11-17 19:59:34.712 keyboardtest[29423:707] data = <18000000 2c000000 9e2a0900
00000000 c60e5d00 00000000 0c020000 00000000 00000000 00000000 00000000 d4d3d4d2
00000000 00000000 ...
还有更多我被截断。
确保将 len
初始化为0.此外,您不能只放置<$ c的内容$ c> buf 在 NSString
中,好像它是一个C字符串。不是。它是你必须解释的二进制数据,比如 netstat
。
Make sure you're initializing len
to 0. Also, you can't just put the contents of buf
in an NSString
as if it were a C string. It's not. It's binary data that you have to interpret, like netstat
does.
大概你想要解释数据。您需要阅读我在上面链接的 netstat
源代码中的 protopr
函数。 protopr
使用的数据结构在< netinet / in_pcb.h>
中声明, < netinet / tcp_var.h>
,以及 / usr / include / netinet
中的其他头文件。这些头文件包含在iOS SDK中(至少从iOS 7.0开始),因此您可以使用它们。
Presumably you want to interpret the data. You need to read through the protopr
function in the netstat
source code, which I linked to above. The data structures used by protopr
are declared in <netinet/in_pcb.h>
, <netinet/tcp_var.h>
, and other header files in /usr/include/netinet
. These header files are included in the iOS SDK (as of iOS 7.0 at least), so you can use them.
这篇关于如何通过objective-c获取iphone上的tcp / udp开放端口列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!