繁体   English   中英

在iPhone上获取IP地址| Objective-C或Swift

[英]Get IP Address on iPhone | Objective-C or Swift

我刚刚发现此代码是使用Objective-C来获取iPhone的IP地址,但对于我正在从事的项目来说有点

- (NSString*)getExternalIP{
NSString *externalIP = @"";
NSArray *ipItemsArray = [[NSArray alloc] init];
NSURL *iPURL = [NSURL URLWithString:@"http://www.dyndns.org/cgi-bin/check_ip.cgi"];
if (iPURL) {
    NSError *error = nil;
    NSString *theIpHtml = [NSString stringWithContentsOfURL:iPURL encoding:NSUTF8StringEncoding error:&error];

    if (!error){
        NSScanner *theScanner;
        NSString *text = nil;
        theScanner = [NSScanner scannerWithString:theIpHtml];
        while ([theScanner isAtEnd] == NO) {
            [theScanner scanUpToString:@"<" intoString:NULL] ;
            [theScanner scanUpToString:@">" intoString:&text] ;
            theIpHtml = [theIpHtml stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@" "] ;
            ipItemsArray = [theIpHtml componentsSeparatedByString:@" "];
            int an_Integer= (int)[ipItemsArray indexOfObject:@"Address:"];
            externalIP =[ipItemsArray objectAtIndex: ++an_Integer];
        }
        return externalIP;
    }
}
return @"error";}

您知道替代解决方案或解决此问题的方法吗? 注意 :必须在Wi-Fi和蜂窝网络上工作。

谢谢!

我发现使用这种方式的IP地址。 首先,您可以导入两个库。

#include <ifaddrs.h>
#include <arpa/inet.h>

然后您可以使用此操作

- (NSString *)getIPAddress {

    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];

                }

            }

            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;

} 

并以这种方式在您的代码中调用此操作。

NSString *strYourIP = [self getIPAddress];

希望这对您有用。

在使用问题中的代码之前,请仔细考虑一下:

如果dyndns.org开始落后会怎样?

以我的经验,此服务的响应时间变化如此之大,以至于对于可能对性能敏感的任何事情,它都是无法使用的。 (我的响应时间从0秒到50+秒不等,已在多个体面的连接上进行了测试。)为此目的,找到/设置服务会更好,因为它更可靠。 如果您可以控制正在使用的应用程序的Web服务,那么添加它很简单。 (在PHP中,它是单行代码。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM