VikasPushkar
VikasPushkar

Reputation: 422

Detect network connection availability changes

I am writing a Go application for Mac and Windows, which will perform some action whenever there is a network change( Client move from Wi-fi 1 to Wi-fi 2 or to 3G to LAN). I am aware of a solution for Application running on mac in swift language but I am looking for a platform-agnostic solution here.

So far I have tried checking for an event on an interface but I am not sure if that is sufficient.

I expect that on a network change (moving from Wifi-1 to Wifi-2 or 3G or LAN) my Go app should be able to know to take some action.

Upvotes: 1

Views: 2525

Answers (2)

VikasPushkar
VikasPushkar

Reputation: 422

There is no platform agnostic solution that exists, however platforms like OSx,Linux,Windiws has ways to get network events with their platform specific limitations.

OSx: Raw socket SOCK_RAW of AF_ROUTE type can be used to detect any network events that occurs in user machine. there are various types of network event that can be detected. This thread talk about an example on BSD for network event

Windows : Windows has its APIs given as part of iphlpapi library. APIs like NotifyAddrChange, NotifyRouteChange allows you to have almost all network events( apart from metric change etc.) this git repo has a working example NotifyAddrChange, which gives back and event whenever a interface goes down or comes up.

Linux : In Linux netlink sockets allows a user space application to receive network events using netlink sockets.

Upvotes: 1

kostix
kostix

Reputation: 55453

I doubt there would be such a solution.

Every project which tries to provide some platform-agnostic solution to an inherently OS-tied problem inevitably hides the platform-specific details behind a common API. Look at https://github.com/fsnotify/fsnotify for a good example.

So, I'd take that route and would have put up a package which would have two platform-specific "backends" which would be compiled conditionally using build tags.

To get notified about network-related events under Windows, you should probably start here. Unfortunately, this stuff is COM-oriented, but you could use https://github.com/go-ole/go-ole to help with that.

You might also ask a non-Go-specific question tagged winapi to ask about what would be the best way to hook into the kernel to get notified about the availability of the networks.

Upvotes: 2

Related Questions