[英]Get IP address of ios device when connectec to wifi
Can anyone suggest me the method in objective c to get IP address of iPhone device when device is connected to WiFi. 任何人都可以在目标c中向我建议在设备连接到WiFi时获取iPhone设备IP地址的方法。
Basically I wanted to know is there any other way apart from getifaddrs(&interfaces) to retrieve the IP address of the device when it is connected to WiFi? 基本上,我想知道除了getifaddrs(&interfaces)之外,还有其他方法可以在设备连接到WiFi时检索设备的IP地址吗?
Getting information about network interfaces in Unix type systems like iOS or Mac OS X requires using some arcane C APIs. 要获取有关iOS或Mac OS X等Unix类型系统中网络接口的信息,需要使用一些神秘的C API。 These APIs have varying amounts of visibility in swift and objective-c , ios and mac-os-x . 这些API在swift和Objective-c , ios和mac-os-x中具有不同程度的可见性。
If you're exclusively targeting macOS with Objective-C, then nshost is your best solution. 如果您专门针对使用Objective-C的macOS,那么nshost是您最好的解决方案。 However, if you require iOS compatibility then you'll have to drop down to lower level C API such as getifaddrs(...)
or cfhost . 但是,如果需要iOS兼容性,则必须下拉至较低级别的C API,例如getifaddrs(...)
或cfhost 。
If you want a swift based solution even getifaddrs(...)
comes with some bridging header requirements (making it unusable in a Framework). 如果您想要一个基于快速的解决方案,甚至getifaddrs(...)
都带有一些桥接头要求(使其无法在Framework中使用)。
Here is an example using CFHost
and sockaddr_in struct
that will work in Swift and on macOS and iOS (even in Frameworks). 这是一个使用CFHost
和sockaddr_in struct
的示例,该sockaddr_in struct
将在Swift以及macOS和iOS(甚至在Frameworks)中运行。 See Host.swift for a fully working example. 有关完整的示例,请参见Host.swift 。
Use CFHost
to get the addressing info, this will be a CFArray
of CFData
objets. 使用CFHost
获取寻址信息,这将是CFArray
的CFData
。
let sockaddrs = CFHostGetAddressing("apple.com", &resolved)?.takeRetainedValue()
Get the first object 获取第一个对象
let data = CFArrayGetValueAtIndex(sockaddrs, 0)
Cast the bytes into a sockaddr struct
将字节转换为sockaddr struct
var storage = sockaddr_storage() data.getBytes(&storage, length: sizeof(sockaddr_storage))
Then force the sockaddr struct
into a sockaddr_in struct
so we can use it 然后将sockaddr struct
强制为sockaddr_in struct
以便我们可以使用它
let addr = withUnsafePointer(&storage) { UnsafePointer<sockaddr_in>($0).memory
Use the inet_ntoa(...)
function to turn addr.sin_addr
(IP address) into a C-string. 使用inet_ntoa(...)
函数将addr.sin_addr
(IP地址)转换为C字符串。 We can then use String(Cstring: encoding:)
to get a nice String of the IP Address. 然后,我们可以使用String(Cstring: encoding:)
获得IP地址的漂亮String。
let address = String(CString: inet_ntoa(addr.sin_addr), encoding: NSUTF8StringEncoding)
Here is a GitHub project called Hostess.swift that I created to solve these issues using the technique above. 这是我创建的一个名为Hostess.swift的GitHub项目,用于使用上述技术解决这些问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.