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.
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.
Test case:
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);
}
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 ...
and lots more I have truncated.
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.
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.
To get the data obtained by the rob mayoff's answer readable you just need to take a look at the code of inet.c. In it, you have all you need to parse the data.
Take a look at my another answer in the question of Hisenberg: Network Activity Monitoring on iPhone
In my code, you can see in what part of the code the data is readable, that is when I add the values to the dictionary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With