Can I use NWConnection to monitor for server availability?

I want my app to react when it sees that a certain port is being listened to, and likewise when it stops being listened to.

Specifically, another app will start a gdb server (at 127.0.0.1 on 9003) and I want mine to detect that. I don't really even care that it's a gdb server, just when the port is in use or not. I can do it right now using polling using a variation of this but that's not great for CPU wakes.

I'm wondering if I can use an NWConnection (with no timeout) to monitor for these events (port in use, port no longer in use). If so, any pointers would be very gratefully received :) Even if just to say I'm barking up the wrong tree!

Replies

Can I use NWConnection to monitor for server availability?

Not really. The issue here isn’t the NWConnection API but rather the TCP protocol itself. The only way to tell whether a host is listening on a port is to connect to that port. That has two consequences:

  • It requires polling, which is never good.

  • It creates false connections, which may be good or bad depending on the server. For example, a web server is likely to be resilient in the face of false connections because the wider internet is crawling with bad actors. OTOH, sometimes more specialised, like a debug server, may not handle them well.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Ah. Well that's a shame. Thanks so much for your helpful reply though! Saved me hours :)