3

I have a .NET application that needs to access resources from a web site. Access to these resources may require the user to change their proxy settings.

I'm wondering how best to detect the presence of a network (i.e. potential internet connection) from the application in a way that is useful for deciding whether to offer the user the ability to change their proxy settings. If there is no network available that can allow a connection to the internet, then changing the proxy settings won't help.

There is NetworkInterface.GetIsNetworkAvailable(), but this returns true

if any network interface is marked "up" and is not a loopback or tunnel interface.

I found that after disconnecting the network cable and wifi on my machine (Google could not be reached), this method still returned true and a number of network interfaces were still up.

  • One had a type of Ppp which corresponded to a VPN connection.
  • Another had a type of Ethernet but a description of "Hyper-V Virtual Ethernet Adapter #4".
  • The third had a type of Loopback.

Obviously the test I performed was only exploratory, and could not be used as a conclusive means of coming up with some kind of filter. There is a suggested filter here but in my test, this always returned false whether or not I had an internet connection, unless I was connected to the VPN.

I can't just attempt to access (say) google.com as this could also fail due to proxy settings being incorrectly configured.

Does what I am trying to do have a viable solution? Can I do better than GetNetworkIsAvailable()?

Community
  • 1
  • 1
fractor
  • 1,534
  • 2
  • 15
  • 30

1 Answers1

0

As pointed out by Simon Mourier in an answer on another question, there are certain cases when the standard method is fooled by virtual cards.

He is proposing using NetworkInterface.GetAllNetworkInterfaces() and iterate through interfaces checking for connection and ignoring virtual, tunnel and loopback interfaces.

I have implemented his solution and it works great. Performance wise you can skip his initial NetworkInterface.GetIsNetworkAvailable(), as the rest of the code do the exact same checks. Both method is fairly CPU expensive, so running both is unnecessary.

I will not copy and take credit, so take a look at his answer: https://stackoverflow.com/a/8345173/146921

Frode Evensen
  • 516
  • 1
  • 10
  • 22