OC和Swift(临时)在wifi状态下ip获取
2016-11-14 本文已影响59人
hoggenWang
在app中有时会获取当前手机的IP地址(主要在wifi下),当然主要看产品的需求;在OC的状态下获取是相对简单的,但在Swift下(强类型)目前我只有一个临时的替代方案,如果谁有更好的,希望交流一下,非常感谢。
在OC中获取当前wifi的IP
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0) {
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET) {
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
freeifaddrs(interfaces);
在Swift中获取当前wifi下的IP
var addresses = "error"
var ifaddr : UnsafeMutablePointer<ifaddrs>? = nil
var temp_addr : UnsafeMutablePointer<ifaddrs>? = nil
var success :Int = 0
success = Int(getifaddrs(&ifaddr))
if success == 0 {
temp_addr = ifaddr
while temp_addr != nil {
if (Int32((temp_addr?.pointee.ifa_addr.pointee.sa_family)!) == AF_INET) {
if (String(cString: (temp_addr?.pointee.ifa_name)!, encoding: .utf8) == "en0") {
let fucn = ((temp_addr?.pointee.ifa_addr.pointee.sa_data)?.2)! < 0 ? -((temp_addr?.pointee.ifa_addr.pointee.sa_data)?.2)! : ((temp_addr?.pointee.ifa_addr.pointee.sa_data)?.2)
let fucn2 = ((temp_addr?.pointee.ifa_addr.pointee.sa_data)?.3)! < 0 ? -((temp_addr?.pointee.ifa_addr.pointee.sa_data)?.3)! : ((temp_addr?.pointee.ifa_addr.pointee.sa_data)?.3)
let foo : UInt8 = UInt8(Int8.max) - UInt8(fucn!) + UInt8(Int8.max) + 2
let foo1 : UInt8 = UInt8(Int8.max) - UInt8(fucn2!) + UInt8(Int8.max) + 2
let fucn3:UInt8 = UInt8(((temp_addr?.pointee.ifa_addr.pointee.sa_data)?.4)!)
let fucn4:UInt8 = UInt8(((temp_addr?.pointee.ifa_addr.pointee.sa_data)?.5)!)
let intString: String = "\(foo):\(foo1):\(fucn3):\(fucn4)"
print("intString=\(intString)")
addresses = intString
}
}
temp_addr = temp_addr?.pointee.ifa_next
}
}