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

How to get IP address of Connected Ethernet or WiFi in MAC

下面是我想在我的代码中做什么的描述。 我想在我的 Mac 应用程序中使用 Objective C.

连接以太网或 Wifi 的 IP 地址

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

我已经在这里看到了很多答案,但是 none 对我有用。

我的 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;
}

试试这个:

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