There are many similar posts on the Internet, after searching for information, think the following method is the simplest,
When you use it, drag the class method directly into 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 for Success
temp_addr = interfaces;
While (temp_addr! = NULL) {
if (temp_addr->ifa_addr->sa_family = = af_inet) {
//Check If interface is En0 which are 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;
}
}
Freeifaddrs (interfaces);
//NSLog (@ "IP of mobile Phone:%@", address);
return address;
}
@end
How to get the current IP of your phone in iOS