简体   繁体   中英

Programatically finding IP of MacBook to which iOS device is connected via cable

When the iOS device is connected to a MacBook via a USB cable is there any programatic way for an app running on the iOS device to discover the IP address of the MacBook? This would be so that a socket connection could then be established between the iOS device and a server running on the laptop.

The IP address on the USB link between them? I'm not even sure there's one in all cases, I believe there's one only when tethering (personal hotspot) is active.

If you mean the IP address of the Mac on Wi-Fi or Ethernet, then there's no guarantee both devices are actually on the same network (you could have the Mac on a local LAN behind a NAT while the iPhone is on a mobile network behind a different NAT), which would make communication problematic (you'd then have the usual P2P NAT-traversal issues, which in turn require external servers).

If you really want the devices to talk to each other over the network (rather than over the USB cable), you should probably look into Bonjour (which requires both devices to be on the same network) or the more recent Multipeer connectivity frameworks (which can even set up a peer-to-peer Wi-Fi network when needed, I believe.

If you really want to communicate over the cable, you're probably better off looking into talking to the device via libimobiledevice / usbmuxd , which can provide communication with a port on the iOS device. Note however that AFAIK, this works with the app on the Mac talking to a server app on the iOS device rather than the opposite.

Put this method into your class & you can obtain the IP address of current device.

// 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM