Get information on INET4 and INET6
Reference books:
I encapsulated the source code:
// // IPAddressInfo.h// yxnetwork////// http www.cnblogs.com/YouXianMing///// Copyright (c) 2014 y.x. All rights reserved. // #import <Foundation/Foundation.h>@interface ipaddressinfo:nsobject+ ( Nsdictionary *) net4info; @end
////IPADDRESSINFO.M//yxnetwork//// http://www.cnblogs.com/YouXianMing/////Copyright (c) 2014 y.x. All rights reserved.//#import "IPAddressInfo.h"#import<sys/types.h>#import<sys/socket.h>#import<netdb.h>#import<arpa/inet.h>#include<ifaddrs.h>#include<arpa/inet.h>StaticNsmutabledictionary *net4 =Nil;StaticNsmutabledictionary *net6 =Nil;@implementationIpaddressinfo+ (void) initialize{if(self = = [Ipaddressinfoclass]) {Net4= [NsmutabledictionaryNew]; Net6= [NsmutabledictionaryNew]; }}+ (Nsdictionary *) net4info{[self updatainfo]; returnNet4;}+ (void) updatainfo{structIfaddrs *interfaces =NULL; structIfaddrs *temp_addr =NULL; intSuccess =0; //getting information from the current interfaceSuccess = Getifaddrs (&interfaces); if(Success = =0) { //Traverse InterfaceTEMP_ADDR =interfaces; for(temp_addr = interfaces; Temp_addr! = NULL; temp_addr = temp_addr->Ifa_next) { if(temp_addr->ifa_addr->sa_family = =af_inet) {Nsmutabledictionary*tmp = [NsmutabledictionaryNew]; //INET4 CharNaddr[inet_addrstrlen]; CharNmask[inet_addrstrlen]; CharNgate[inet_addrstrlen]; Inet_ntop (Af_inet,& (structsockaddr_in *) temp_addr->ifa_addr)Sin_addr,naddr,inet_addrstrlen); Inet_ntop (Af_inet,& (structsockaddr_in *) temp_addr->ifa_netmask)Sin_addr,nmask,inet_addrstrlen); Inet_ntop (Af_inet,& (structsockaddr_in *) temp_addr->ifa_dstaddr)Sin_addr,ngate,inet_addrstrlen); NSString*interfacename = [NSString stringwithutf8string:temp_addr->Ifa_name]; NSString*address =[NSString stringwithutf8string:naddr]; NSString*netmask =[NSString Stringwithutf8string:nmask]; NSString*gateway =[NSString Stringwithutf8string:ngate]; [tmp setobject:address Forkey:@"Address"]; [tmp setobject:netmask Forkey:@"netmask"]; [tmp setobject:gateway Forkey:@"Gateway"]; [Net4 setobject:tmp Forkey:interfacename]; } Else if(temp_addr->ifa_addr->sa_family = =Af_inet6) { //INET6 CharNaddr[inet6_addrstrlen]; CharNgate[inet6_addrstrlen]; Inet_ntop (Af_inet6,& (structSOCKADDR_IN6 *) temp_addr->ifa_addr)Sin6_addr,naddr,inet6_addrstrlen); NSString*tmpgateway =Nil; if((structSOCKADDR_IN6 *) Temp_addr->ifa_dstaddr! =NULL) {Inet_ntop (Af_inet6,& (structSOCKADDR_IN6 *) temp_addr->ifa_dstaddr)Sin6_addr,ngate,inet6_addrstrlen); Tmpgateway=[NSString Stringwithutf8string:ngate]; } Else{Tmpgateway=@" "; } //nsstring *interfacename = [NSString stringwithutf8string:temp_addr->ifa_name];//nsstring *address = [NSString stringwithutf8string:naddr];//nsstring *netmask = @ "";//nsstring *gateway = Tmpgateway;// //NSLog (@ "%@", InterfaceName);//NSLog (@ "%@", address);//NSLog (@ "%@", netmask);//NSLog (@ "%@", Gateway); } Else { Continue; } } } //Freeing ResourcesFreeifaddrs (interfaces);}@end
Use case: