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

编程入门 行业动态 更新时间:2024-10-11 09:22:33
本文介绍了如何获取设备的公共IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我找到了这个示例代码获取所有本地IP地址,但我找不到一个简单的解决方案来获取公共IP。

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 遗留类 Apple允许这样做 ...但它的遗产......

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

推荐答案

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

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 NSError *error = nil; NSString *theIpHtml = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"www.dyndns/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

更多推荐

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

本文发布于:2023-11-28 08:57:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641758.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:地址   设备   IP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!