iOS获取当前连接的WiFi以及IP地址
程序员文章站
2024-02-13 23:34:46
导入头文件
#import
#import
#import
导入头文件
#import <ifaddrs.h> #import <arpa/inet.h> #import <systemconfiguration/captivenetwork.h>
核心代码:
+ (nullable nsstring*)getcurrentlocalip { nsstring *address = nil; 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 if([[nsstring stringwithutf8string:temp_addr->ifa_name] isequaltostring:@"en0"]) { // get nsstring from c string address = [nsstring stringwithutf8string:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; } } temp_addr = temp_addr->ifa_next; } } // free memory freeifaddrs(interfaces); return address; }
+ (nullable nsstring *)getcurrewifissid { nsarray *ifs = (__bridge_transfer id)cncopysupportedinterfaces(); nslog(@"supported interfaces: %@", ifs); id info = nil; for (nsstring *ifnam in ifs) { info = (__bridge_transfer id)cncopycurrentnetworkinfo((__bridge cfstringref)ifnam); nslog(@"%@ => %@", ifnam, info); if (info && [info count]) { break; } } return [(nsdictionary*)info objectforkey:@"ssid"]; }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!