I've got the following code that successfully retrieves all the IPs connected to my router. But I need to a get the MAC Addresses for each IP.
So instead of addresses being returned as an array with [ips]
, be returned as a dictionary [ips:0000000, mac: 000000]
Is it possible to be achieved with changes to the following code (from How to get Ip address in swift)?
func getIFAddresses() -> [String] {
print("GET IF ADDRESSSE")
var addresses = [String]()
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
if getifaddrs(&ifaddr) == 0 {
print("getifaddrs\(getifaddrs)")
// For each interface ...
for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next) {
let flags = Int32(ptr.memory.ifa_flags)
var addr = ptr.memory.ifa_addr.memory
print("flags\(flags)")
print("addr\(addr)")
// Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
print("addr.sa_family\(addr.sa_family)")
// Convert interface address to a human readable string:
var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
print("hostname\(hostname)")
if (getnameinfo(
&addr, socklen_t(addr.sa_len),
&hostname,
socklen_t(hostname.count),
nil,
socklen_t(0), NI_NUMERICHOST) == 0) {
if let address = String.fromCString(hostname) {
addresses.append(address)
}
}
}
}
}
freeifaddrs(ifaddr)
print("freeifaddrs\(freeifaddrs)")
}
print("ADDRESSES \(addresses)")
return addresses
}
If you will use this inside a framework, you have to add a .modelmap file with this configuration inside it
and then in your .swift file
(Remark/clarification: This is an answer to the question "Manage ifaddrs to return MAC addresses as well in Swift" and "Is it possible to modify the code from How to get Ip address in swift to return the MAC addresses as well". This is not a solution to "retrieve all the IPs connected to my router" which is also mentioned in the question body.)
Here is an extension of the referenced code which returns the local (up and running) interfaces as an array of (interface name, ip address, MAC address) tuples. The MAC address is retrieved from the interfaces of type
AF_LINK
which are stored assockaddr_dl
structure in the interface list. This is a variable length structure, and Swift's strict type system makes some pointer juggling necessary.Important: This code is meant to run on Mac computers. It does not work to get the MAC addresses on iOS devices. iOS intentionally returns "02:00:00:00:00:00" as hardware address for all interfaces for privacy reasons, see for example Trouble with MAC address in iOS 7.0.2.)
You have to add
to the bridging header file to make this compile.
Example usage:
Update for Swift 3 (Xcode 8):