Skip to content

Instantly share code, notes, and snippets.

@tncowart
Last active August 12, 2020 18:42
Show Gist options
  • Save tncowart/b0a302c30f674091e5589fec9350ed8a to your computer and use it in GitHub Desktop.
Save tncowart/b0a302c30f674091e5589fec9350ed8a to your computer and use it in GitHub Desktop.
enumerate iphone interfaces in swift and objective-c
private struct InterfaceNames {
static let wifi = ["en0"]
static let wired = ["en2", "en3", "en4"]
static let cellular = ["pdp_ip0", "pdp_ip1", "pdp_ip2", "pdp_ip3"]
static let supported = wifi + wired + cellular
}
private func ipAddresses() -> [String] {
var addresses = [String]()
var ifaddr: UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return addresses }
var pointer = ifaddr
while pointer != nil {
defer { pointer = pointer?.pointee.ifa_next }
guard
let interface = pointer?.pointee,
interface.ifa_addr.pointee.sa_family == UInt8(AF_INET) ||
interface.ifa_addr.pointee.sa_family == UInt8(AF_INET6),
let interfaceName = interface.ifa_name,
let interfaceNameFormatted = String(cString: interfaceName, encoding: .utf8),
InterfaceNames.supported.contains(interfaceNameFormatted)
else { 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
)
if let formattedIpAddress = String(cString: hostname, encoding: .utf8), !formattedIpAddress.isEmpty {
addresses.append(formattedIpAddress)
}
}
freeifaddrs(ifaddr)
return addresses
}
// Code adapted from https://stackoverflow.com/a/6807801
- (NSArray *)ipAddresses {
NSMutableArray *addresses = [[NSMutableArray alloc] init];
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0) {
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET) {
// Skip the loopback interface, it's always the same.
if ([[NSString stringWithUTF8String: temp_addr->ifa_name] isEqualToString: @"lo0"]) {
temp_addr = temp_addr->ifa_next;
continue;
}
NSString *address = [NSString stringWithUTF8String: inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
[addresses addObject: address];
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return [addresses copy];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment