rishu1992
rishu1992

Reputation: 1434

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.

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

Answers (1)

Richard Stelling
Richard Stelling

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 and , and .

If you're exclusively targeting macOS with Objective-C, then 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 .

If you want a 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.

  1. Use CFHost to get the addressing info, this will be a CFArray of CFData objets.

    let sockaddrs = CFHostGetAddressing("apple.com", &resolved)?.takeRetainedValue() 
    
  2. Get the first object

    let data = CFArrayGetValueAtIndex(sockaddrs, 0)
    
  3. Cast the bytes into a sockaddr struct

    var storage = sockaddr_storage()
    data.getBytes(&storage, length: sizeof(sockaddr_storage))
    
  4. Then force the sockaddr struct into a sockaddr_in struct so we can use it

    let addr = withUnsafePointer(&storage) { UnsafePointer<sockaddr_in>($0).memory
    
  5. 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

Related Questions