I have a C# application that should only be used when the network is down, but am afraid users will just unplug the network cable in order to use it.
Is there a way to detect if the network cable has been unplugged?
Thanks
I have a C# application that should only be used when the network is down, but am afraid users will just unplug the network cable in order to use it.
Is there a way to detect if the network cable has been unplugged?
Thanks
The network card will report this as a state. Tools like ethtool
can display this (Link up
), but that is only available for Linux/Unix.
If you can enumerate the installed network cards with a Windows API, I'm sure you'll find the flag for "link up" somewhere in there.
If I really wanted to use your application and whether it will work depends on something like this, I would always be able to find a way to trick your application. Are you sure there's no better solution?
In my humble opinion, there is no certain way to distinguish between a network down and an unplugged cable. And even if there is a way, there is also a way to work around it.
Let's assume that you have a solution and let's look at some situations:
Some network drivers are able to detect this. However you'd need to use unmanaged code to access them from C# (which may be very difficult/impossible) and the solution may not be reliable for all network adapters.
You could use IsNetworkAlive(). Although technically it doesn't check link state, it's probably better since it can detect wireless and dialup connectivity as well. Here's an example:
using System.Runtime.InteropServices;
class Program
{
[DllImport("sensapi.dll")]
static extern bool IsNetworkAlive(out int flags);
static void Main(string[] args)
{
int flags;
bool connected = IsNetworkAlive(out flags);
}
}
The flags param returns whether the connection is to the internet or just a LAN. I'm not 100% sure how it knows, but I'd bet it just looks to see if there is a default gateway set.
How about pinging the default gateway?
There is some code here that gets the default gateway from the registry.