-2

I'm trying to detect an Ethernet cable disconnection/connection status using the following code. I'm not getting required result, as it gives back the status of Wi-fi network along with Ethernet. How to get the status of the Ethernet port alone?

using System.Net.NetworkInformation;

     
bool isNetworkCableConnected = NetworkInterface.GetIsNetworkAvailable();

Please share any suggestions.

impulse101
  • 99
  • 1
  • 10
  • A good starting point could be [WMI - netwoork adapter](https://stackoverflow.com/questions/10114455/determine-network-adapter-type-via-wmi) – Cleptus Jul 28 '20 at 10:43
  • `NetworkInterface` has the properties [NetworkInterfaceType](https://learn.microsoft.com/en-us/dotnet/api/system.net.networkinformation.networkinterface.networkinterfacetype?view=netcore-3.1#System_Net_NetworkInformation_NetworkInterface_NetworkInterfaceType) and [OperationalStatus](https://learn.microsoft.com/en-us/dotnet/api/system.net.networkinformation.networkinterface.operationalstatus?view=netcore-3.1#System_Net_NetworkInformation_NetworkInterface_OperationalStatus). The former let's you filter for Ethernet, the latter gives you a hint of operational status. – Fildor Jul 28 '20 at 10:58
  • 1
    ^^ ... Meaning: If it's up, you can be sure a cable is plugged. What you cannot know is whether the reason for it to be _not_ up is an unplugged cable. – Fildor Jul 28 '20 at 10:58

1 Answers1

1

To get Ethernet-only connectivity, you first have to filter for Ethernet interfaces:

NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
var ethOnly = adapters.Where( x => x.NetworkInterfaceType = NetworkInterfaceType.Ethernet );

Maybe also include Ethernet3Megabit and GigabitEthernet.

Then you can check the resulting adapter(s) for connectivity:

// check first adapter for connectivity
bool upAndRunning = ethOnly[0]?.OperationalStatus == OperationalStatus.Up ?? false;

Mind that the operational status depends on more things than just a plugged or unplugged cable. If it's up, you can be pretty confident, that a cable is present and intact. If it's not up, you cannot know if a missing cable is the culprit, however.

tl/dr: I think the closest you can get is to monitor operational status, but not specifically cable (= layer 0) status.

Fildor
  • 14,510
  • 4
  • 35
  • 67