我有以下扩展sockaddr
:
extension sockaddr {
/// Indicates if this is an IPv4 address.
var isIPv4: Bool {
return sa_family == UInt8(AF_INET)
}
/// Indicates if this is an IPv6 address.
var isIPv6: Bool {
return sa_family == UInt8(AF_INET6)
}
/// Returns the address in string notation.
var address: String? {
var result: String = ""
var me = self
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if getnameinfo(&me, socklen_t(me.sa_len), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) == 0 {
result = String(cString: hostname)
}
return result
}
}
在我的代码的另一部分中,我正在调用getifaddrs
以获取当前设备的接口地址。上面的代码适用于 IPv4,但对于 IPv6 来说有些不可靠。
我得到如下结果:192.168.1.10
和fe80::e0fa:1204:100:0
当我将线路更改var result: String = ""
为var result: String? = nil
. IPv6地址突然变成fe80::
了,剩下的就被切断了。
更奇怪的是,当我像这样切换var result
和行时var me = self
:
extension sockaddr {
/// Indicates if this is an IPv4 address.
var isIPv4: Bool {
return sa_family == UInt8(AF_INET)
}
/// Indicates if this is an IPv6 address.
var isIPv6: Bool {
return sa_family == UInt8(AF_INET6)
}
/// Returns the address in string notation.
var address: String? {
var me = self
var result: String = ""
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if getnameinfo(&me, socklen_t(me.sa_len), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) == 0 {
result = String(cString: hostname)
}
return result
}
}
然后该功能将仅适用于 IPv4 地址。将getnameinfo
返回 4(失败)。
这是在调试期间,没有我知道的优化。如果我在模拟器或真实设备上运行它并不重要。
有人可以解释为什么会这样吗?