How to get the current IP address of the mobile phone in IOS, and ios get the current ip Address

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.