Objective-C:获取默认网关信息

标签 objective-c c mac-address gateway inet

如何在 Objective-C 中获取我的默认网关 IP 和 MAC 地址?

现在,我能够创建一个函数来获取使用 arpa/inet.h 的 IP 它工作正常,但我不知道如何获取默认网关 IP 和 MAC地址。

NSString* GetMyIP(NSString* inf) {
    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!
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:inf])
                {
                    // 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;
}

我使用 arpnetstat 有一段时间了,但它们并不总是按预期工作,而且您可能会理解这是有风险的解决方案...

是否有另一种更“Apple 方式”来获取此类信息?不使用 arpa/inet.h?例子?

谢谢。

最佳答案

This answer解释了如何在 OSX 上获取接口(interface)的 MAC 地址。

默认网关在路由表中注册 - 不直接与网络接口(interface)相关联。请注意,默认 网关(即 0.0.0.0 的网关)可能不是您需要关心的唯一网关,可能有路由器设置为更受限的地址范围。 (此外,可能有多个网关,默认或其他,具有不同的优先级)

路由表记录在 route(4) manpage 中- 这有望为您提供足够的信息来检索您应用中的路由表。

关于Objective-C:获取默认网关信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10997994/

相关文章:

c - 在 C 中将整数转换为位串的最佳方法是什么

ruby - 在 TCPServer (Ruby) 中,我如何从客户端获取 IP/MAC?

ios - 使用自定义字体在 CGContextRef 和 PDF 中打印 NSString

objective-c - Cocoa 合并自定义 View

c - 启动 execlp 作为后台进程

c - 通过C控制电机

android - 如何使用python在android中获取mac地址

linux - 如何从 Openwrt 中的 DHCP 租约文件解析特定的 MAC 地址?

ios - iOS 上的面部表情识别

ios - 在 IOS 中无法从 Google Drive 获取文件