【问题标题】:Objective-C - Determining IP address of iPod touch programmaticallyObjective-C - 以编程方式确定 iPod touch 的 IP 地址
【发布时间】:2010-11-09 19:56:54
【问题描述】:

我正在用 Objective-C 为几个 iPod 设备编程,我想知道一些事情。我正在开发一个利用服务器-客户端模型的应用程序,并且我正在使用带有 C 套接字的 UDP 协议。是否有一个类可以让我确定 iPod 设备的 IP 地址?在谷歌搜索其他论坛后,我没有找到任何东西。显然这个命令是行不通的,但是像 ipAddress = self.ip 这样的命令是我想到的。我正在设置多播 C 套接字,我正在尝试做一个类似于 ping 命令的解决方法,这显然不存在于 Objective-C 中或据我所知(这是有限的,因为我只是在编程至少在今年夏天开始以来在Objective-C中)。有什么建议或提示吗?

【问题讨论】:

    标签: objective-c ip ip-address multicast multicastsocket


    【解决方案1】:

    这段代码的 sn-p 将通过循环访问接口来检索它。

    - (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; 
    } 
    

    【讨论】:

    • 首先测试并运行代码,然后发布完整代码。我从上面的代码中得到警告和错误。警告:函数“getifadrs”的隐式声明错误:取消引用指向不完整类型的指针(temp_addr!= NULL)和更多错误。
    • 您没有包含正确的标题。在将代码复制并粘贴到浴室墙上之前,请先了解代码。
    • 有人想给我们一些关于正确标题的内容吗?
    • @TaylorAddison #import <netinet/in.h> #import <ifaddrs.h> #import <sys/socket.h>@BenLakey 感谢您的解决方案
    【解决方案2】:

    你看到了吗? http://www.appsamuck.com/day4.html。我认为正确的答案是在 SDK 中使用CFHost

    编辑
    看来该项目中的源代码正在使用以下代码,这使其成为完全无效的解决方案,除非 Apple 决定将 NSHost 放入 SDK。

    -(NSString*)getAddress {  
        char iphone_ip[255];  
        strcpy(iphone_ip,"127.0.0.1"); // if everything fails  
        NSHost* myhost =[NSHost currentHost];  
        if (myhost)  
        {  
            NSString *ad = [myhost address];  
            if (ad)  
                strcpy(iphone_ip,[ad cStringUsingEncoding: NSISOLatin1StringEncoding]);  
        }  
        return [NSString stringWithFormat:@"%s",iphone_ip];   
    }
    

    【讨论】:

    • 这也是我脑海中闪现的第一件事
    • NSHost 不受 iPhone SDK 支持。如果是这样就好了。
    • iPhone SDK 支持NSHost!
    • 不,不是。请参阅 Apple 的技术问答 QA1652 以获得证明。 NSHost 是私有的。
    猜你喜欢
    • 2010-11-23
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    相关资源
    最近更新 更多