【发布时间】:2017-01-06 11:29:17
【问题描述】:
当 iOS 设备通过 USB 电缆连接到 MacBook 时,是否有任何编程方式让 iOS 设备上运行的应用程序发现 MacBook 的 IP 地址? 这样就可以在 iOS 设备和笔记本电脑上运行的服务器之间建立套接字连接。
【问题讨论】:
标签: ios objective-c
当 iOS 设备通过 USB 电缆连接到 MacBook 时,是否有任何编程方式让 iOS 设备上运行的应用程序发现 MacBook 的 IP 地址? 这样就可以在 iOS 设备和笔记本电脑上运行的服务器之间建立套接字连接。
【问题讨论】:
标签: ios objective-c
它们之间的 USB 链接上的 IP 地址?我什至不确定是否在所有情况下都有一个,我相信只有在网络共享(个人热点)处于活动状态时才会有一个。
如果您指的是 Mac 在 Wi-Fi 或以太网上的 IP 地址,则不能保证两台设备实际上都在同一个网络上(您可以将 Mac 在 NAT 后面的本地 LAN 上,而 iPhone 在不同 NAT 后面的移动网络),这会使通信出现问题(然后您会遇到常见的 P2P NAT 穿越问题,而这又需要外部服务器)。
如果您确实希望设备通过网络(而不是通过 USB 电缆)相互通信,您可能应该查看Bonjour(要求两个设备在同一网络上)或更近的Multipeer connectivity 框架(我相信它甚至可以在需要时设置点对点 Wi-Fi 网络。
如果您真的想通过电缆进行通信,您可能最好考虑通过libimobiledevice / usbmuxd 与设备通信,这可以提供与 iOS 设备上的端口的通信。但是请注意,AFAIK,这适用于 Mac 上的应用程序与 iOS 设备上的服务器应用程序通信,而不是相反。
【讨论】:
把这个方法放到你的类中,就可以得到当前设备的IP地址了。
// get the IP address of current-device
- (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;
}
【讨论】: