Objective-C - 以编程方式确定iPod touch的IP地址

Jos*_*ley 2 ip multicast objective-c ip-address multicastsocket

我正在为几台iPod设备编写Objective-C编程,我对此感到疑惑.我正在开发一个利用服务器 - 客户端模型的应用程序,我正在使用带有C套接字的UDP协议.是否有一个课程允许我确定iPod设备的IP地址?在谷歌搜索其他论坛后,我还没有找到任何东西.显然这个命令不起作用,但像ipAddress = self.ip这样的东西就是我想到的.我正在设置组播C套接字,我正在尝试做一个类似于ping命令的解决方法,这显然在objective-C中不存在,或者据我所知(这是有限的,因为我只是编程在至少从今年夏天开始的目标-C中.有什么建议或提示吗?

Ben*_*key 8

这段代码将通过循环遍历接口来检索它.

- (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; 
} 
Run Code Online (Sandbox Code Playgroud)

  • 您没有包含正确的标头.首先要了解代码,然后将其复制并粘贴在浴室墙上. (6认同)
  • @TaylorAddison`#import <netinet/in.h> #import <ifaddrs.h> #import <sys/socket.h>`@BenLakey感谢您的解决方案 (4认同)