Reputation:
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
Upvotes: 6
Views: 8620
Reputation: 1168
To detect 'Is network cable plugged in a machine?', below piece of code works.
class Program
{
private static void Main(string[] args)
{
bool isNetworkCableConnected = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
}
}
Upvotes: 0
Reputation: 3189
You could register a delegate to the NetworkChange
Class. When a network change occurs, it doesn't actually notify you what happened, so you could list all the network interfaces (Using NetworkInterface
), filter the ones that concern you (By checking there properties) and check their operational status.
Upvotes: 1
Reputation: 31
You can use this
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
Upvotes: 3
Reputation: 29576
How about pinging the default gateway?
There is some code here that gets the default gateway from the registry.
Upvotes: 0
Reputation: 3793
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.
Upvotes: 6
Reputation: 60017
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.
Upvotes: 2
Reputation: 67831
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:
Upvotes: 4
Reputation: 6763
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?
Upvotes: 0
Reputation: 328556
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.
Upvotes: 1