Search code examples
swiftunsafe-pointers

swift Cannot convert value of type 'in_addr_t' (aka 'UInt32') to expected argument type 'UnsafeMutablePointer<in_addr_t>!'


I tried to add function from objective c to swift just like here https://stackoverflow.com/a/29440193/7395969 and I converted call method to Swift as shown below. But I get error : Cannot convert value of type 'in_addr_t' (aka 'UInt32') to expected argument type 'UnsafeMutablePointer!' on this line : let r: Int

func getGatewayIP() -> String {
    var ipString: String? = nil

    let gatewayaddr: in_addr
    let r: Int = getdefaultgateway((gatewayaddr.s_addr))
    if r >= 0 {
        ipString = "\(inet_ntoa(gatewayaddr))"
        print("default gateway : \(ipString)")
    }
    else {
        print("getdefaultgateway() failed")
    }
    return ipString!
}

Solution

  • You have to pass the address of gatewayaddr.s_addr as inout argument with &. Also the gatewayaddr must be initialized:

    var gatewayaddr = in_addr()
    let r = getdefaultgateway(&gatewayaddr.s_addr)
    

    Note that string interpolation

        ipString = "\(inet_ntoa(gatewayaddr))"
    

    will not work to convert the C string to a Swift String, you have to call String(cString:). Also

    return ipString!
    

    will crash if the gateway could not be determined.

    Example of a safe version:

    func getGatewayIP() -> String? {
        var gatewayaddr = in_addr()
        let r = getdefaultgateway(&gatewayaddr.s_addr)
        if r >= 0 {
            return String(cString: inet_ntoa(gatewayaddr))
        } else {
            return nil
        }
    }
    
    if let gateway = getGatewayIP() {
        print("default gateway", gateway)
    } else {
        print("getGatewayIP() failed")
    }