Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the public IP address of the device

I found this sample code to get all local IP addresses, but I don't find an easy solution to get the public IP.

A legacy class from Apple allowed to do that ... but it's legacy ...

like image 598
Damien Romito Avatar asked Dec 30 '14 16:12

Damien Romito


People also ask

What is public IP address of my computer?

To check if your IP address is public, you can use myip.com (or any similar service). You will be shown the IP address that was used for accessing the site; and if it matches the IP address that your Internet service provider assigned you, then you have a public IP address.


3 Answers

It's as simple as this:

NSString *publicIP = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"https://icanhazip.com/"] encoding:NSUTF8StringEncoding error:nil];
publicIP = [publicIP stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; // IP comes with a newline for some reason
like image 157
Tarek Avatar answered Oct 17 '22 19:10

Tarek


I have used ALSystemUtilities in the past. You basically have to make a call externally to find this out.

+ (NSString *)externalIPAddress {
    // Check if we have an internet connection then try to get the External IP Address
    if (![self connectedViaWiFi] && ![self connectedVia3G]) {
        // Not connected to anything, return nil
        return nil;
    }

    // Get the external IP Address based on dynsns.org
    NSError *error = nil;
    NSString *theIpHtml = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.dyndns.org/cgi-bin/check_ip.cgi"]
                                                   encoding:NSUTF8StringEncoding
                                                      error:&error];
    if (!error) {
        NSUInteger  an_Integer;
        NSArray *ipItemsArray;
        NSString *externalIP;
        NSScanner *theScanner;
        NSString *text = nil;

        theScanner = [NSScanner scannerWithString:theIpHtml];

        while ([theScanner isAtEnd] == NO) {

            // find start of tag
            [theScanner scanUpToString:@"<" intoString:NULL] ;

            // find end of tag
            [theScanner scanUpToString:@">" intoString:&text] ;

            // replace the found tag with a space
            //(you can filter multi-spaces out later if you wish)
            theIpHtml = [theIpHtml stringByReplacingOccurrencesOfString:
                         [ NSString stringWithFormat:@"%@>", text]
                                                             withString:@" "] ;
            ipItemsArray = [theIpHtml  componentsSeparatedByString:@" "];
            an_Integer = [ipItemsArray indexOfObject:@"Address:"];
            externalIP =[ipItemsArray objectAtIndex:++an_Integer];
        }
        // Check that you get something back
        if (externalIP == nil || externalIP.length <= 0) {
            // Error, no address found
            return nil;
        }
        // Return External IP
        return externalIP;
    } else {
        // Error, no address found
        return nil;
    }
}

Source from ALSystemUtilities

like image 34
Andrei Avatar answered Oct 17 '22 20:10

Andrei


Thanks @Tarek for his answer

Here, code in Swift 4 version

func getPublicIPAddress() -> String {
    var publicIP = ""
    do {
        try publicIP = String(contentsOf: URL(string: "https://www.bluewindsolution.com/tools/getpublicip.php")!, encoding: String.Encoding.utf8)
        publicIP = publicIP.trimmingCharacters(in: CharacterSet.whitespaces)
    }
    catch {
        print("Error: \(error)")
    }
    return publicIP
}

NOTE1: To get public IP address, we must have external site to return public IP. The website I use is business company website, so, it will be their until the business gone.

NOTE2: You can made some site by yourself, however, Apple require HTTPS site to be able to use this function.

like image 7
Sruit A.Suk Avatar answered Oct 17 '22 21:10

Sruit A.Suk