简体   繁体   English

IP地址? - 可可

[英]IP Address? - Cocoa

How would I make a GUI program that displays your Ip address with a click of a button? 如何通过单击按钮制作显示您的IP地址的GUI程序? Please, no difficult explanations, I just started Cocoa not long ago. 请,没有困难的解释,我不久前刚刚开始了Cocoa。

Thanks, 谢谢,

Kevin 凯文

You can get IP address through two ways: 您可以通过两种方式获取IP地址:

1- if you want to get the local ip address on the current used netwrok, you can use the following method to retrive it: 1-如果要获取当前使用的netwrok上的本地IP地址,可以使用以下方法检索它:

-(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)
            {
                    // 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;
}

2- if you want to get the external IP address then you need to use the following method: 2-如果你想获得外部IP地址,那么你需要使用以下方法:

-(NSString*)getIP
{
    NSUInteger  an_Integer;
    NSArray * ipItemsArray;
    NSString *externalIP;

    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) {

                // 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];
            }
            NSLog(@"%@",externalIP);
        } else {
            NSLog(@"Oops... g %d, %@", [error code], [error localizedDescription]);
        }
    }
    return externalIP;
}

For determining the IP address, I found this . 为了确定IP地址,我发现了这一点

As for making it into a Cocoa app, add an NSTextField (label) to your main window in Interface Builder, put in a button, add in an application controller (a subclass of NSObject that you make), put in the outlet and the action, do the proper connenctions, and in the "get IP" method, put in that code and set the value for the label's stringValue . 至于将它变成Cocoa应用程序,在Interface Builder的主窗口中添加一个NSTextField (标签),放入一个按钮,添加一个应用程序控制器(你制作的NSObject的子类),放入插座和动作,做正确的连接,并在“获取IP”方法,输入该代码并设置标签的stringValue的值。

You can use [[NSHost currentHost] address] , but it won't always display what you like. 您可以使用[[NSHost currentHost] address] ,但它不会始终显示您喜欢的内容。 On my system, for example, it gives my IPv6 address. 例如,在我的系统上,它提供了我的IPv6地址。

EDIT: On my system, [[[NSHost currentHost] addresses] objectAtIndex:0] has my IPv4 address. 编辑:在我的系统上, [[[NSHost currentHost] addresses] objectAtIndex:0]有我的IPv4地址。

[[NSHost currentHost] addresses] will get you an array of IPs. [[NSHost currentHost] addresses]将为您提供一系列IP。 Read the documentation for NSHost . 阅读NSHost文档

As for displaying that in a GUI, I recommend getting Aaron Hillegass' book Cocoa Programming for Mac OS X, or any Cocoa beginners book should teach that. 至于在GUI中显示,我建议让Aaron Hillegass为Mac OS X编写Cocoa Programming,或者任何Cocoa初学者书都应该教它。

I just wrote this, may need some work but seems to work well on my machine... 我刚刚写了这个,可能需要一些工作,但似乎在我的机器上运行良好...

- (NSString *)getLocalIPAddress
{
    NSArray *ipAddresses = [[NSHost currentHost] addresses];
    NSArray *sortedIPAddresses = [ipAddresses sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.allowsFloats = NO;

    for (NSString *potentialIPAddress in sortedIPAddresses)
    {
        if ([potentialIPAddress isEqualToString:@"127.0.0.1"]) {
            continue;
        }

        NSArray *ipParts = [potentialIPAddress componentsSeparatedByString:@"."];

        BOOL isMatch = YES;

        for (NSString *ipPart in ipParts) {
            if (![numberFormatter numberFromString:ipPart]) {
                isMatch = NO;
                break;
            }
        }
        if (isMatch) {
            return potentialIPAddress;
        }
    }

    // No IP found
    return @"?.?.?.?";
}

We can use hostWithName: method with current host name. 我们可以使用hostWithName:方法和当前主机名。 This will return only single local IPv4 and IPv6 IP, which we can filter easily. 这将仅返回单个本地IPv4和IPv6 IP,我们可以轻松过滤。

We can get the current system host name using [[NSHost currentHost] name] . 我们可以使用[[NSHost currentHost] name]获取当前系统主机名。

+(NSString *)getLocalIPAddress{
    NSArray *ipAddresses = [[NSHost hostWithName:[[NSHost currentHost] name]] addresses];
    for (NSString *ipAddress in ipAddresses) {
        if ([ipAddress componentsSeparatedByString:@"."].count == 4) {
            return ipAddress;
        }
    }
    return @"Not Connected.";
}

So, this will solve all the problems mentions in comments of other answers. 因此,这将解决其他答案的评论中提到的所有问题。 Also, this significantly work more faster than other solution mention here. 此外,这显着比这里提到的其他解决方案更快。

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

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