Dam*_*ito 9 public objective-c ip-address ios
我找到了这个示例代码来获取所有本地IP地址,但我找不到一个简单的解决方案来获取公共IP.
来自Apple 的传统课程允许这样做...但它的遗产......
Tar*_*rek 17
这很简单:
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
Run Code Online (Sandbox Code Playgroud)
And*_*rei 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;
}
}
Run Code Online (Sandbox Code Playgroud)
感谢@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
}
Run Code Online (Sandbox Code Playgroud)
注意1:要获取公共IP地址,我们必须有外部站点返回公共IP。我使用的网站是商业公司的网站,所以,直到生意消失为止,这将是他们的网站。
注意2:您可以自己创建一些站点,但是Apple需要HTTPS站点才能使用此功能。
| 归档时间: |
|
| 查看次数: |
11145 次 |
| 最近记录: |