Reputation: 1434
Can anyone suggest me the method in objective c to get IP address of iPhone device when device is connected to WiFi.
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?
Upvotes: 2
Views: 1279
Reputation: 25665
Getting information about network interfaces in Unix type systems like iOS or Mac OS X requires using some arcane C APIs. These APIs have varying amounts of visibility in swift and objective-c, ios and mac-os-x.
If you're exclusively targeting macOS with Objective-C, then nshost is your best solution. However, if you require iOS compatibility then you'll have to drop down to lower level C API such as getifaddrs(...)
or cfhost.
If you want a swift based solution even getifaddrs(...)
comes with some bridging header requirements (making it unusable in a Framework).
Here is an example using CFHost
and sockaddr_in struct
that will work in Swift and on macOS and iOS (even in Frameworks). See Host.swift for a fully working example.
Use CFHost
to get the addressing info, this will be a CFArray
of CFData
objets.
let sockaddrs = CFHostGetAddressing("apple.com", &resolved)?.takeRetainedValue()
Get the first object
let data = CFArrayGetValueAtIndex(sockaddrs, 0)
Cast the bytes into a 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
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. We can then use String(Cstring: encoding:)
to get a nice String of the IP Address.
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.
Upvotes: 1