Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

objective c - How do I get the currently connected network interface name using Cocoa or Foundation?

I need to know the network interface name of the currently connected network interface, as in en0, lo0 and so on.

Is there a Cocoa/Foundation function that is going to give me this information?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can cycle through network interfaces and get their names, IP addresses, etc.

#include <ifaddrs.h>
// you may need to include other headers

struct ifaddrs* interfaces = NULL;
struct ifaddrs* temp_addr = NULL;

// retrieve the current interfaces - returns 0 on success
NSInteger 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) // internetwork only
      {
        NSString* name = [NSString stringWithUTF8String:temp_addr->ifa_name];
        NSString* address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
        NSLog(@"interface name: %@; address: %@", name, address);
      }

      temp_addr = temp_addr->ifa_next;
    }
}

// Free memory
freeifaddrs(interfaces);

There are many other flags and data in the above structures, I hope you will find what you are looking for.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...