How to get the current IP address of the mobile phone in IOS, and ios get the current ip Address
There are many similar posts on the Internet. After searching for information, I think the following method is the simplest,
You can directly drag the class method to your new category,
. H file
# Import <Foundation/Foundation. h>
@ Interface NSObject (GetIP)
+ (NSString *) deviceIPAdress;
@ End
. M file
# Import "NSObject + GetIP. h"
# Include <ifaddrs. h>
# Include <arpa/inet. h>
The above two header files must be imported
@ Implementation NSObject (GetIP)
+ (NSString *) deviceIPAdress {
NSString * address = @ "an error occurred when obtaining ip address ";
Struct ifaddrs * interfaces = NULL;
Struct ifaddrs * temp_addr = NULL;
Int success = 0;
Success = getifaddrs (& interfaces );
If (success = 0) {// 0 indicates that the acquisition is successful.
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 stringwithuf8string: temp_addr-> ifa_name] isEqualToString: @ "en0"]) {
// Get NSString from C String
Address = [NSString stringwithuf8string: inet_ntoa (struct sockaddr_in *) temp_addr-> ifa_addr)-> sin_addr)];
}
}
Temp_addr = temp_addr-> ifa_next;
}
}
Freeifaddrs (interfaces );
// NSLog (@ "the mobile phone's IP address is: % @", address );
Return address;
}
@ End