forked from strongbox-password-safe/Strongbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WifiAddressHelper.swift
92 lines (60 loc) · 2.8 KB
/
WifiAddressHelper.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//
// WifiAddressHelper.swift
// Strongbox-iOS
//
// Created by Strongbox on 05/02/2023.
// Copyright © 2023 Mark McGuill. All rights reserved.
//
import Foundation
class WifiAddressHelper: NSObject {
@objc class func getDebugAfInetAddresses() -> [String: String] {
var ifaddr: UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0, let firstAddr = ifaddr else {
swlog("🔴 Could not getifaddrs or firstAddr")
return [:]
}
var addresses: [String: String] = [:]
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 interfaceName = String(cString: interface.ifa_name)
if interfaceName.starts(with: "utun") || interfaceName.starts(with: "lo") {
continue
}
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)
let address = String(cString: hostname)
let up = ((interface.ifa_flags & UInt32(IFF_UP)) == IFF_UP)
addresses[interfaceName] = String(format: "%@ %@", up ? "U" : "D", address)
} else {
}
}
freeifaddrs(ifaddr)
return addresses
}
@objc class func getWifiAddress() -> String? {
var address: String?
var ifaddr: UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return nil }
guard let firstAddr = ifaddr else { return 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)
address = String(cString: hostname)
}
}
}
freeifaddrs(ifaddr)
return address
}
}