Malav Soni
Malav Soni

Reputation: 2848

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

Below is the description what exactly I want to do in my code. I want connected Ethernet or Wifi's IP Address in my Mac Application using Objective C.

If my WiFi is connected then I want to get Wifi's IP address or if Ethernet is connected then Ethernet's IP Address.

I have already seen many answers here but none of them work for me.

I want this for my MAC Application.

Thanks in advance.

This is one of the code that i tried.

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

Upvotes: 3

Views: 1397

Answers (1)

stosha
stosha

Reputation: 2148

Try this:

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

Upvotes: 2

Related Questions