0

I need to keep track if the device's network IP environment has changed.

I looked at Swift - Get device's WIFI IP Address

I do not necessarily want WiFi IP address only, but any network IP that it is able to communicate (including cellular).

However, there is a corner case: when the internal (non externally routable) addresses like 192.168.x.x become duplicates, but in different subnets.

To make it clear, home network of house A gives me 192.168.1.10; when I join another home network say House B, the home net of house B could also assign me 192.168.1.10.

In this case, how would I track that the environment changed with same IP address?

jscs
  • 63,694
  • 13
  • 151
  • 195
tech_geek
  • 147
  • 2
  • 11

1 Answers1

0

If you don't actually care about the IP address, I would suggest that you use NWPathMonitor - You can use this to invoke a closure when the available network interfaces change.

I tested it with two different SSIDs on my Wi-Fi (The device gets the same IP address on both, since it is the same network underlying both SSIDs) and it reports a path change when I move from one to the other.

class ViewController: UIViewController {

    private var pathMonitor: NWPathMonitor!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.pathMonitor = NWPathMonitor()

        self.pathMonitor.pathUpdateHandler = newPath

        self.pathMonitor.start(queue: DispatchQueue.global())
    }

    func newPath(_ newPath: NWPath) -> Void {
        print("Network path changed")       
        print("Is expensive - \(newPath.isExpensive)")
    }
}
Paulw11
  • 108,386
  • 14
  • 159
  • 186