ios获取ip信息
#ios

#include <arpa/inet.h>
#include <dns.h>
#include <resolv.h>
#include <ifaddrs.h>

– (NSDictionary *)getIPAddressInfo:(NSString*)strInterface {
NSMutableDictionary *dicIPInfo = [[NSMutableDictionary alloc] init];
NSDictionary *dicConnectList;

struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;

// retrieve the current interfaces – returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0){
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL){
if(temp_addr->ifa_addr->sa_family == AF_INET){
// Check if interface is en0 which is the wifi connection on the iPhone

char *interface_name = temp_addr->ifa_name;
if([[NSString stringWithUTF8String:interface_name] isEqualToString:strInterface]){
//接口名称
NSString *strInterfaceName = [NSString stringWithUTF8String:interface_name];

//ip地址
char *ip = inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr);
NSString *strIP = [NSString stringWithUTF8String:ip];

//子网掩码
char *submask = inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr);
NSString *strSubmask = [NSString stringWithUTF8String:submask];

//广播地址
char *dstaddr = inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr);
NSString *strDstaddr = [NSString stringWithUTF8String:dstaddr];

dicIPInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
strIP,@”ip”,
strSubmask,@”submask”,
strDstaddr,@”broadcast”,nil];

dicConnectList = [NSDictionary dictionaryWithObjectsAndKeys:
dicIPInfo,strInterfaceName,nil];

}
}

temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return dicConnectList;
}

// 使用
NSDictionary *dic_en0 = [self getIPAddressInfo:@”en0″];
NSLog(@”en0: %@”,dic_en0);

NSDictionary *dic_pdp_ip0 = [self getIPAddressInfo:@”pdp_ip0″];
NSLog(@”cell: %@”,dic_pdp_ip0);

NSDictionary *dic_ppp0 = [self getIPAddressInfo:@”ppp0″];
NSLog(@”*: %@”,dic_ppp0);