Skip to content

Instantly share code, notes, and snippets.

@hsleedevelop
Created May 11, 2017 13:50
Show Gist options
  • Save hsleedevelop/14faedf11490cee7f0f093123bc3124a to your computer and use it in GitHub Desktop.
Save hsleedevelop/14faedf11490cee7f0f093123bc3124a to your computer and use it in GitHub Desktop.
get IPAddress From Hotspot
//#include <ifaddrs.h> in bridging-header first.
fileprivate func getIPAddress() -> String? {
var address : [String]? = []
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return nil}
guard let firstAddr = ifaddr else { return nil}
// For each interface ...
for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
let interface = ifptr.pointee
if Int32(interface.ifa_flags) & (IFF_LOOPBACK) == (IFF_LOOPBACK) {
continue
}
if Int32(interface.ifa_flags) & (IFF_BROADCAST) != (IFF_BROADCAST) {
continue
}
// Check for IPv4 or IPv6 interface:
let addrFamily = interface.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
// Check interface name:
//let name = String(cString: interface.ifa_name)
// Convert interface address to a human readable string:
var addr = interface.ifa_addr.pointee
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(&addr, socklen_t(interface.ifa_addr.pointee.sa_len),
&hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST)
address?.append(String(cString: hostname) + "\n")
}
}
freeifaddrs(ifaddr)
return address.flatMap({$0})?.joined()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment