简体   繁体   中英

How do I get the IP address of a local hostname in local network in Swift

how do I get the IP address (eg 192.168.0.1) of a local hostname (eg "myComputer") on my local network in swift?

I tried this:

let host = CFHostCreateWithName(nil,"www.google.com").takeRetainedValue();
CFHostStartInfoResolution(host, .Addresses, nil);
var success: Boolean = 0;
let addresses = CFHostGetAddressing(host, &success).takeUnretainedValue() as NSArray;
if (addresses.count > 0){
    let theAddress = addresses[0] as NSData;
    var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
    if getnameinfo(UnsafePointer(theAddress.bytes), socklen_t(theAddress.length),
        &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 {
            if let numAddress = String.fromCString(hostname) {
                println(numAddress)
            }
    }
} 

This works fine for addresses like "www.google.com" but not for hostnames like "myComputer"

I tried it in Xcode Simulator. There it works, but not on my iPhone

I'll get the error:

fatal error: unexpectedly found nil while unwrapping an Optional value

... in Line 4.

Thanks for your help!

Local hostnames such as myComputer will only be available to your iPhone if it's DNS server is configured to resolve them (or they are in the hosts file).

To resolve myComputer on your iPhone, you would need to have your iPhone configured to use a local DNS server that would serve IP addresses for the hostnames of the machines on your local network.

The error you're seeing relates to not getting a result. You'll need to check that the host resolves ( CFHostStartInfoResolution provides a result for this):

let host = CFHostCreateWithName(nil,"www.google.com").takeRetainedValue();
var success : Boolean = CFHostStartInfoResolution(host, .Addresses, nil);
if success > 0 {
    success = 0;
    let addresses = CFHostGetAddressing(host, &success).takeUnretainedValue() as NSArray
    if (addresses.count > 0){
        let theAddress = addresses[0] as! NSData;
        var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
        if getnameinfo(UnsafePointer(theAddress.bytes), socklen_t(theAddress.length),
            &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 {
            if let numAddress = String.fromCString(hostname) {
                println(numAddress)
            }
        }
    }
} else {
    println("Host not found!")
}

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