我有一个ipv6字符串,如何使用Swift转换为in6_addr
let ipString = "2001:0b28:f23f:f005:0000:0000:0000:000a"
答案 0 :(得分:2)
您可以使用inet_pton()
与在C程序中一样:
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()
addr
变量为inet_pton()
。