如何获取设备的公共IP地址

时间:2014-12-30 16:22:04

标签: ios objective-c ip-address public

我找到this sample code来获取所有本地IP地址,但我找不到一个简单的解决方案来获取公共IP。

来自Apple的legacy class允许这样做 ......但它的遗产......

8 个答案:

答案 0 :(得分:16)

这很简单:

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

答案 1 :(得分:10)

我过去曾使用ALSystemUtilities。你基本上必须在外部打电话才能找到它。

+ (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;
    }
}

来自ALSystemUtilities

的来源

答案 2 :(得分:1)

对于我们这些使用Swift的人来说,这是我对Andrei的答案的翻译,其中添加了NSURLSession以在后台运行它。要检查网络,我使用Reachability.swift。另外,请记住在NSExceptionDomains中为NSAppTransportSecurity添加dyndns.org至info.plist

var ipAddress:String?
func getIPAddress() {

    if reachability!.isReachable() == false {
        return
    }

    guard let ipServiceURL = NSURL(string: "http://www.dyndns.org/cgi-bin/check_ip.cgi") else {
        return
    }

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithURL(ipServiceURL, completionHandler: {(data, response, error) -> Void in
        if error != nil {
            print(error)
            return
        }

        let ipHTML = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String

        self.ipAddress = self.scanForIPAddress(ipHTML)

    })

    task.resume()
}

func scanForIPAddress(var ipHTML:String?) -> String? {

    if ipHTML == nil {
        return nil
    }

    var externalIPAddress:String?
    var index:Int?
    var ipItems:[String]?
    var text:NSString?

    let scanner = NSScanner(string: ipHTML!)

    while scanner.atEnd == false {
        scanner.scanUpToString("<", intoString: nil)

        scanner.scanUpToString(">", intoString: &text)

        ipHTML = ipHTML!.stringByReplacingOccurrencesOfString(String(text!) + ">", withString: " ")

        ipItems = ipHTML!.componentsSeparatedByString(" ")

        index = ipItems!.indexOf("Address:")
        externalIPAddress = ipItems![++index!]

    }

    if let ip = externalIPAddress {
        print("External IP Address: \(ip)")
    }

    return externalIPAddress

}

答案 3 :(得分:1)

感谢@Tarek的回答

在这里,使用Swift 4版本的代码

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
}

注意1:要获取公共IP地址,我们必须具有外部站点来返回公共IP。我使用的网站是商业公司网站,因此,直到业务消失之前,这都是他们的网站。

>

注2:您可以自己创建一个站点,但是Apple要求 HTTPS 站点才能使用此功能。

答案 4 :(得分:0)

您必须查询外部服务器以找出公共IP。要么设置你自己的服务器(1行php代码),要么使用许多可用的服务器中的一个,它们在http查询时将IP作为纯文本或json返回。例如http://myipdoc.com/ip.php

答案 5 :(得分:0)

您可以调用公共IP地址查找服务来获取此信息吗?我已将http://ipof.in设置为将设备IP地址作为JSON / XML或纯文本返回的服务。你可以在这里找到它们

对于具有GeoIP数据的JSON

http://ipof.in/json

https://ipof.in/json

对于XML响应

http://ipof.in/xml

https://ipof.in/xml

对于纯文本IP地址

http://ipof.in/txt

https://ipof.in/txt

答案 6 :(得分:0)

我使用ipify并且没有投诉。

NSURL *url = [NSURL URLWithString:@"https://api.ipify.org/"];
NSString *ipAddress = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"My public IP address is: %@", ipAddress);

答案 7 :(得分:0)

如果要异步检索IP,有一种方法可以在1行代码中使用ipify.org和Alamofire来实现:

Alamofire.request("https://api.ipify.org").responseString { (response) in
    print(response.result.value ?? "Unable to get IP")
}
相关问题