iOS 獲取手機的ip地址 並傳給後臺(三步搞定)
第一步 建立一個NSObject 檔案
.h 檔案 寫
#import <Foundation/Foundation.h>
@interface NSObject (GetIP)
+ (NSString *)deviceIPAdress;
@end
.m檔案 寫
#import "NSObject+GetIP.h"
#include <ifaddrs.h>
#include <arpa/inet.h>
@implementation NSObject (GetIP)
//必須在有網的情況下才能獲取手機的IP地址
+ (NSString
NSString *address = @"an error occurred when obtaining ip address";
structifaddrs *interfaces = NULL;
structifaddrs *temp_addr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0) { // 0 表示獲取成功
temp_addr = interfaces;
while (temp_addr !=
if( temp_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
if ([[NSStringstringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
// Get NSString from C String
address = [NSStringstringWithUTF8String
}
}
temp_addr = temp_addr->ifa_next;
}
}
freeifaddrs(interfaces);
NSLog(@"%@", address);
return address;
}
@end
第二步 在VC 裡面匯入 標頭檔案等#import "NSObject+GetIP.h"
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>
#define IOS_CELLULAR @"pdp_ip0"
#define IOS_WIFI @"en0"
#define IOS_VPN @"utun0"
#define IP_ADDR_IPv4 @"ipv4"
#define IP_ADDR_IPv6 @"ipv6"
第三步 在你寫給後臺的網路請求裡寫入
NSString *StringIP = [NSStringdeviceIPAdress]; //呼叫方法 獲取ip地址 賦值給字串 stringIP
[params setObject:StringIP forKey:@"ipNum"]; //把ip 地址對應後臺提供的引數 傳給後臺