简体   繁体   中英

Swift - Get ipv6 link local address?

I checked the below code to get ipv6 address and this code returned global unicast address like '2001:x:x...'. But I want to get link local address like 'fe80:...'. How can I get link local address by using the below code?

static var ipAddress: String? {
    var ipv6 : String?
    var ifaddr : UnsafeMutablePointer<ifaddrs>?
    guard getifaddrs(&ifaddr) == 0 else { return (nil, nil) }
    guard let firstAddr = ifaddr else { return (nil, nil) }

    for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
        let interface = ifptr.pointee
        let addrFamily = interface.ifa_addr.pointee.sa_family
        if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
            let name = String(cString: interface.ifa_name)
            if  name == "en0" {
                var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len),&hostname, socklen_t(hostname.count),nil, socklen_t(0), NI_NUMERICHOST)
                ipv6 = String(cString: hostname)
            }
        }
    }
    freeifaddrs(ifaddr)
    return ipv6
}

The system include file netinet6/in6.h defines a macro

#define IN6_IS_ADDR_LINKLOCAL(a)        \
        (((a)->s6_addr[0] == 0xfe) && (((a)->s6_addr[1] & 0xc0) == 0x80))

That macro is not imported into Swift, but shows how we have to proceed. The following modification of the loop (from Swift - Get device's IP Address ) finds all IPv6 link-local addresses:

    for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
        let interface = ifptr.pointee
        let addrFamily = interface.ifa_addr.pointee.sa_family
        if addrFamily == UInt8(AF_INET6) {
            // Get the sin6_addr part of the sockaddr as UInt8 "array":
            let s6_addr = interface.ifa_addr.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) {
                $0.pointee.sin6_addr.__u6_addr.__u6_addr8
            }
            // Check for link-local address:
            if s6_addr.0 == 0xfe && (s6_addr.1 & 0xc0) == 0x80 {
                let name = String(cString: interface.ifa_name)

                // ...
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM