yarshure yarshure - 6 months ago 68
Swift Question

How to use swift convert string to ipv6 addr

I have a ipv6 string,how to use Swift convert to in6_addr

let ipString = "2001:0b28:f23f:f005:0000:0000:0000:000a"

Answer

You can use inet_pton() similarly as you would in a C program:

let ipString = "2001:0b28:f23f:f005:0000:0000:0000:000a"
var addr = in6_addr()
let retval = withUnsafeMutablePointer(&addr) {
    inet_pton(AF_INET6, ipString, UnsafeMutablePointer($0))    
}

if retval == 0 {
    print("Invalid address")
} else if retval == -1 {
    print("Failed:", String.fromCString(strerror(errno)) ?? "\(errno)")
    // For Swift 3, replace the last line by
    // print("Failed:", String(cString: strerror(errno)))
} else {
  //  Success, `addr` contains the result.
}

withUnsafeMutablePointer() is necessary to pass the address of the addr variable to inet_pton().

Comments