【发布时间】:2015-04-21 10:30:49
【问题描述】:
以下是我想要在我的代码中执行的操作的描述。 我想使用 Objective C 在我的 Mac 应用程序中连接以太网或 Wifi 的 IP 地址。
如果我的 WiFi 已连接,那么我想获取 Wifi 的 IP 地址,或者如果以太网已连接,那么我想获取以太网的 IP 地址。
我已经在这里看到了很多答案,但没有一个对我有用。
我想要这个用于我的 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;
}
【问题讨论】:
-
你能告诉我们你发现了什么但它不起作用吗?
-
请查看我编辑的问题
标签: objective-c macos networking wifi ethernet