如何快速获取Ip地址

前端之家收集整理的这篇文章主要介绍了如何快速获取Ip地址前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我如何获取我的本地IpAddress?

我试图使用这个Obj C的例子:how to get ip address of iphone programatically

当我得到函数getifaddrs()我不能得到任何进一步.我不能使用这个功能.

有没有办法做到这一点,或者我接近这个错误的方式?

原来在讨论中,OP需要Mac上的界面地址,而不是像我以前想的那样在iOS设备上.问题中引用的代码检查
接口名称“en0”,这是iPhone上的WiFi接口.在Mac上,它使得更多
意思是检查任何“正在运行”界面.
所以我改写了答案.现在是Swift的代码翻译
Detect any connected network.

getifaddrs()定义在< ifaddrs.h>中,默认情况下不包括.
因此,您必须创建一个桥接头并添加

  1. #include <ifaddrs.h>

以下函数返回
具有所有本地“正在运行”网络接口名称的阵列.

  1. func getIFAddresses() -> [String] {
  2. var addresses = [String]()
  3.  
  4. // Get list of all interfaces on the local machine:
  5. var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
  6. if getifaddrs(&ifaddr) == 0 {
  7.  
  8. // For each interface ...
  9. var ptr = ifaddr
  10. while ptr != nil {
  11. defer { ptr = ptr.memory.ifa_next }
  12.  
  13. let flags = Int32(ptr.memory.ifa_flags)
  14. var addr = ptr.memory.ifa_addr.memory
  15.  
  16. // Check for running IPv4,IPv6 interfaces. Skip the loopback interface.
  17. if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
  18. if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
  19.  
  20. // Convert interface address to a human readable string:
  21. var hostname = [CChar](count: Int(NI_MAXHOST),repeatedValue: 0)
  22. if (getnameinfo(&addr,socklen_t(addr.sa_len),&hostname,socklen_t(hostname.count),nil,socklen_t(0),NI_NUMERICHOST) == 0) {
  23. if let address = String.fromCString(hostname) {
  24. addresses.append(address)
  25. }
  26. }
  27. }
  28. }
  29. }
  30. freeifaddrs(ifaddr)
  31. }
  32.  
  33. return addresses
  34. }

Swift 3的更新:除了采用代码
many changes in Swift 3,
所有接口的迭代现在可以使用新的泛化
sequence()功能

  1. func getIFAddresses() -> [String] {
  2. var addresses = [String]()
  3.  
  4. // Get list of all interfaces on the local machine:
  5. var ifaddr : UnsafeMutablePointer<ifaddrs>?
  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. var 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(&addr,NI_NUMERICHOST) == 0) {
  21. let address = String(cString: hostname)
  22. addresses.append(address)
  23. }
  24. }
  25. }
  26. }
  27.  
  28. freeifaddrs(ifaddr)
  29. return addresses
  30. }

猜你在找的Swift相关文章