How to get the public IP address of the device

前端 未结 9 540
陌清茗
陌清茗 2020-12-29 10:32

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 ... bu

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 10:54

    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
    

提交回复
热议问题