4

I need to develop an iOS app Using Swift 5 to find my iPhone hotspot connected devices IP info.

Is there any API for it in Swift 5 or any other open source code?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Joe
  • 365
  • 2
  • 9
  • 24

1 Answers1

0

Please refer to the code below.

For getting the hotspot connected device's IP, use Network.wifi .

enum Network: String {
    case wifi = "en0"
    case cellular = "pdp_ip0"
    case ipv4 = "ipv4"
    case ipv6 = "ipv6"
}

func getAddress(for network: Network) -> String? {
    var address: String?

    // Get list of all interfaces on the local machine:
    var ifaddr: UnsafeMutablePointer<ifaddrs>?
    guard getifaddrs(&ifaddr) == 0 else { return nil }
    guard let firstAddr = ifaddr else { return nil }

    // For each interface ...
    for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
        let interface = ifptr.pointee

        // Check for IPv4 or IPv6 interface:
        let addrFamily = interface.ifa_addr.pointee.sa_family
        if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {

            // Check interface name:
            let name = String(cString: interface.ifa_name)
            if name == network.rawValue {

                // Convert interface address to a human readable string:
                var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len),
                            &hostname, socklen_t(hostname.count),
                            nil, socklen_t(0), NI_NUMERICHOST)
                address = String(cString: hostname)
            }
        }
    }
    freeifaddrs(ifaddr)

    return address
}

print("wifi: \(String(describing: getAddress(for: .wifi)))")

For more information refer to below links:

Swift - Get device's WIFI IP Address

Get IPAddress of iPhone or iPad device Using Swift 3

Amyth
  • 383
  • 3
  • 9
  • Thanks for your info. This gives the app running device IP Address. But I would like to get hotspot connected device IP address. For example, I have enabled personal hotspot in my iPhone and connected my iPad through that hotspot. Now from my iPhone, I would like to get IP address of the iPad using my app. – Joe Dec 09 '19 at 14:38
  • @Joe can you tell me how did you get the IP address of iPad using your app? I also need the same thing to do. Can you help me out? – Muhammad Danish Qureshi Dec 24 '20 at 07:28