How to get the Mac address and IP address of the iOS device using the Swift programming

  1. func getIFAddresses() -> [String] { 
  2. var addresses = [String]() 
  3.  
  4. // Get list of all interfaces on the local machine: 
  5. var ifaddr : UnsafeMutablePointer? 
  6. guard getifaddrs(&ifaddr) == 0 else { return [] } 
  7. guard let firstAddr = ifaddr else { return [] } 
  8.  
  9. // For each interface … 
  10. for ptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) { 
  11. let flags = Int32(ptr.pointee.ifa_flags) 
  12. let addr = ptr.pointee.ifa_addr.pointee 
  13.  
  14. // Check for running IPv4, IPv6 interfaces. Skip the loopback interface. 
  15. if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) { 
  16. if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) { 
  17.  
  18. // Convert interface address to a human readable string: 
  19. var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) 
  20. if (getnameinfo(ptr.pointee.ifa_addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count), 
  21. nil, socklen_t(0), NI_NUMERICHOST) == 0) { 
  22. let address = String(cString: hostname) 
  23. addresses.append(address) 
  24.  
  25. freeifaddrs(ifaddr) 
  26. return addresses