如何在MAC中获取连接的以太网或WiFi的IP地址

如何在MAC中获取连接的以太网或WiFi的IP地址

问题描述:

下面是我的代码中想要做什么的描述。 我想在我的Mac应用程序中使用目标C连接以太网或Wifi的IP地址。如何在MAC中获取连接的以太网或WiFi的IP地址

如果我的WiFi已连接,那么我想要获取Wifi的IP地址,或者如果以太网连接了以太网的IP地址。

我已经在这里看到很多答案,但没有一个适合我。

我希望这是我的MAC应用程序。

在此先感谢。

这是我试过的代码之一。

- (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; 
    } 
} 
freeifaddrs(interfaces); 
return address; 
} 
+2

能否请您为我们提供你发现了什么,它不工作? – stosha

+0

请查看我编辑的问题 –

试试这个:

+ (NSString*) getIPAddress 
{ 
    NSMutableString* address = [[NSMutableString alloc] init]; 
    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) 
      { 
       NSString* ifa_name = [NSString stringWithUTF8String: temp_addr->ifa_name]; 
       NSString* ip = [NSString stringWithUTF8String: inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; 
       NSString* name = [NSString stringWithFormat: @"%@: %@ ", ifa_name, ip]; 
       [address appendString: name]; 
      } 
      temp_addr = temp_addr->ifa_next; 
     } 
    } 
    freeifaddrs(interfaces); 

    return [address autorelease]; 
} 
+0

It works .. Thanks。 –