import Network
func getIPAddress() {
var address: String = ""
var ifaddr: UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return }
var ptr = ifaddr
while ptr != nil {
defer { ptr = ptr?.pointee.ifa_next }
let interface = ptr?.pointee
let addrFamily = interface?.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
if String(cString: (interface?.ifa_name)!) == "en0" {
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
let res = getnameinfo(interface?.ifa_addr,
socklen_t((interface?.ifa_addr.pointee.sa_len)!),
&hostname,
socklen_t(hostname.count),
nil,
socklen_t(0),
NI_NUMERICHOST)
if res == 0 {
let str = String(cString: hostname)
if isIPAddress(str) {
address = str
}
}
}
}
}
freeifaddrs(ifaddr)
Swift.print(address)
}
func isIPAddress(_ address: String) -> Bool {
let pattern = "^[\\d.]+$"
return address.range(of: pattern, options: .regularExpression,
range: nil, locale: .current) != nil
}