如何使用 swift 将字符串转换为 ipv6 地址

How to use swift convert string to ipv6 addr

我有一个ipv6字符串,如何使用Swift转换成in6_addr

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

您可以使用 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([=10=]))    
}

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().

Swift 5 & 网络

您可以使用 Network 中的 IPv6Address 来处理 IPv6 地址。它对于处理本地或远程端点 NWEndpoints、验证字符串 IPv6 地址、缩短等很有用

IPv6Address 有一个扩展,它实现了 in6_addr 的辅助函数:

import Network

extension IPv6Address {
    var address: in6_addr {
        rawValue.withUnsafeBytes {
            [=10=].load(as: in6_addr.self)
        }
    }
    
    var stringValue: String { debugDescription }
    
    init(_ address: in6_addr) {
        var addr = address
        let data = withUnsafeBytes(of: &addr) { Data([=10=]) }
        self.init(data)!
    }
}

使用方法:

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

// Create IPv6Address from string
if let ipv6 = IPv6Address(ipString) {
    // Get in6_addr from IPv6Address
    let addr = ipv6.address
    print(addr) // in6_addr(__u6_addr: __C.in6_addr.__Unnamed_union___u6_addr())
    
    // Create IPv6Address from in6_addr
    let ipv6 = IPv6Address(addr)
    print(ipv6.stringValue) // 2001:b28:f23f:f005::a
}