【发布时间】:2012-06-12 13:44:57
【问题描述】:
如何在 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;
}
我使用了一段时间 arp 和 netstat,但它们并不总是按预期工作,而且您可能理解这些解决方案存在风险......
还有其他“Apple 方式”来获取此类信息吗?不使用arpa/inet.h?例子?
谢谢。
【问题讨论】:
标签: objective-c c mac-address gateway inet