I'm trying to detect when an Ethernet cable is plugged-in or unplugged but i have some probleme and i don't know if i'm doing this good or not.
I'm using NetworkChange.NetworkAddressChanged
to detect when the network change
and then NetworkInterface.GetAllNetworkInterfaces() for checking if Ethernet connexion is available or not with the property .OperationalStatus.
But when i search for the Ethernet connexion in all the network interfaces, it return me what i'm looking for, but it always return me the Bluetooth connection with it.
Here is the code :
public Form1()
{
InitializeComponent();
NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(AddressChangedCallback);
Console.ReadLine();
}
static void AddressChangedCallback(object sender, EventArgs e)
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface myInterface in adapters)
{
//if (n.Description.ToLower().Contains("ethernet")){
//if (n.NetworkInterfaceType.ToString().ToLower().Contains("ethernet")){
IPInterfaceProperties properties = n.GetIPProperties();
if (myInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
Console.WriteLine(myInterface.Description + " ........... : " + myInterface.OperationalStatus);
Console.WriteLine("NetworkInterfaceType : " + myInterface.NetworkInterfaceType);
}
}
}
At the beginning, i was trying to check the name of the connection and looks if contains the "Ethernet" word, but it appears (if i'm not wrong) sometimes the connection name does not contain "Ethernet".
Do you have some tips for always bring the good connection (without the bluetooth)?
Am i wrong in my approach?
I'm testing it on a Surface Pro 3... but maybe i have the Bluetooth problem because of that?
Despite that, i need it to work even on device like this.
This can be done by checking its operational status as:
foreach (System.Net.NetworkInformation.NetworkInterface net in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
{
if (net.OperationalStatus ==
System.Net.NetworkInformation.OperationalStatus.Up)
Console.WriteLine("N/w connected");
else
Console.WriteLine("N/w not connected");
}
This links shows how to do it with Powershell, but one of the cases uses WMI.
http://www.powershellmagazine.com/2013/04/04/pstip-detecting-wi-fi-adapters/
And this links shows a interesting property that can help sometimes:
https://msdn.microsoft.com/en-us/library/aa394217(v=vs.85).aspx
GatewayCostMetric
Data type: uint16 array
Access type: Read-only Array
of integer cost metric values (ranging from 1 to 9999) to be used in
calculating the fastest, most reliable, or least resource-intensive
routes. This argument has a one-to-one correspondence with the
DefaultIPGateway property.
Related
I have an application in which I have to use the serial ports, so alright, it finds all right, but I thought and if the client has more than 1 COM port connected on the PC? How do I do when I checkbox and dial, when updating only my device appears? (My USB converter is no longer generic, it contains your own name and address).
Here is the function where I update the COM ports
public void AtualizarPortas()
{
PortasDisponiveis.Clear();
var portas = SerialPort.GetPortNames().OrderBy(x => x).ToList();
foreach (var porta in portas)
{
PortasDisponiveis.Add(porta);
}
PortaSelecionada = PortasDisponiveis.FirstOrDefault();
}
What could I do to get only my device to appear?
I need get it independent if the network connection is active or not.
I need get only dial up connection.
in this picture Claro is default netowork connection name.
Have no idea how do this. I hope this is clear. Thanks in advance!
To find the currently selected default connection for connecting to the internet, which can be set in a couple of ways, you need to read the registry key HKCU\RemoteAccess InternetProfile. This will contain the name of the adapter.
Now the fun part: you will need to use DotRas.
Once you have this downloaded, installed, and reference in your project, you can use code similar to the following:
// Get the default adapter
string defaultAdapter = Registry.GetValue(#"HKEY_CURRENT_USER\RemoteAccess", "InternetProfile", "") as string;
foreach (RasConnection connection in RasConnection.GetActiveConnections())
{
if (connection.EntryName.Equals(defaultAdapter, StringComparison.InvariantCultureIgnoreCase))
{
if (connection.GetConnectionStatus().ConnectionState == RasConnectionState.Connected)
{
// Do something
}
}
// Done searching
break;
}
is this what you where looking for?
using System.Net.NetworkInformation;
class Program
{
static void Main(string[] args)
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
Console.WriteLine(nic.NetworkInterfaceType);
Console.WriteLine(nic.Name);
}
}
}
if you find out what string it puts for NetworkInterfaceType with modems then you can put a if statement in there
I've been crawling in the web for about 5 hours now and couldn't find a solution for my problem:
My company is developing an educational game and I'm writing an autoupdater for it using Monotorrent. The game will be used in schools, but because most schools only have very weak internet connections there should only be one computer in the network that downloads from a httpseeder, and the others should leech from the one computer that is downloading from the httpseed.
So I get loads of IP-addresses from the tracker and need to filter out only the ones that are in the LAN.
Of course schools are sometimes quite strict with firewalls and there will be loads of routers and switches between some computers in a school.
I've already tried most solutions, things like
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface iface in interfaces)
{
IPInterfaceProperties properties = iface.GetIPProperties();
foreach (UnicastIPAddressInformation address in properties.UnicastAddresses)
{
Console.WriteLine(
"{0} (Mask: {1})",
address.Address,
address.IPv4Mask
);
}
}
Or similar techniques only deliver the information of the router/switch/whatever.
So in a nutshell, what I want to do is check if a given IP is accessible via LAN.
I'd really appreciate any help because this feature is the last one remaining :)
You could take advantage of TTL. With a TTL of 1 the packet won't be able to make it to the internet:
private static bool IsLanIP(IPAddress address)
{
var ping = new Ping();
var rep = ping.Send(address, 100, new byte[] { 1 }, new PingOptions()
{
DontFragment = true,
Ttl = 1
});
return rep.Status != IPStatus.TtlExpired && rep.Status != IPStatus.TimedOut && rep.Status != IPStatus.TimeExceeded;
}
However, remember that it is called an IPv4 mask for a reason - you can use it as one (so here is your algorithmic solution):
private static bool IsLanIP(IPAddress address)
{
var interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var iface in interfaces)
{
var properties = iface.GetIPProperties();
foreach (var ifAddr in properties.UnicastAddresses)
{
if (ifAddr.IPv4Mask != null &&
ifAddr.Address.AddressFamily == AddressFamily.InterNetwork &&
CheckMask(ifAddr.Address, ifAddr.IPv4Mask, address))
return true;
}
}
return false;
}
private static bool CheckMask(IPAddress address, IPAddress mask, IPAddress target)
{
if (mask == null)
return false;
var ba = address.GetAddressBytes();
var bm = mask.GetAddressBytes();
var bb = target.GetAddressBytes();
if (ba.Length != bm.Length || bm.Length != bb.Length)
return false;
for (var i = 0; i < ba.Length; i++)
{
int m = bm[i];
int a = ba[i] & m;
int b = bb[i] & m;
if (a != b)
return false;
}
return true;
}
Typically any IPs like 10.x.x.x (Class A) or 192.x.x.x (Class C) can be safely assumed to be inside a private local area network. IP Classications
One thing that you could possibly use is to try and communicate between clients using multicast. Most firewalls and routers would block multicast traffic (and ISPs most definitely), meaning that you wouldn't be able to join a multicast group if no other client is on the lan. A dumb switch would pass on the traffic, a layer 3-switch might block it, or could allow it depending on configuration. Either way, if the layer 3 switch block it, you are probably on different subnets altogether anyway so all other options would fail as well.
One technology that comes to mind is SSDP ( http://en.wikipedia.org/wiki/Simple_Service_Discovery_Protocol ) which would serve your purpose pretty good I believe. That way you don't really need to figure out if you are on a LAN or not, just search for another node that is actively downloading, if you can't find one, start downloading yourself.
Since SSDP is a standard used in uPnP you would probably be able to find decent implementations you could work with.
I have a need to figure out which adapter is used when a connection is created. In other words, if I have multiple NIC cards (i.e. wireless, lan, etc) on my machine, which card is being used for the connection?
If anyone can point me in the right direction...
In C#
foreach(var nic in NetworkInterface.GetAllNetworkInterfaces.Where(n => n.OperationalStatus == OperationStatus.UP)
{
if(nic.GetIsNetworkAvailable())
{
//nic is attached to some form of network
}
}
VB .NET
ForEach nic in NetworkInterface.GetAllNetworkInterfaces.Where(Function(n) n.OperationalStatus = OperationStatus.UP)
If nic.GetIsNetworkAvailable() Then
//nic is attached to some form of network
End If
Next
This will only test active working Network Interfaces that are connected to an active network.
Why don't you use the MAC address?
Maybe you could map it by the MAC Address:
var nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (var nic in nics)
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
var mac = nic.GetPhysicalAddress().ToString();
if (mac == "your:connections:mac:address")
{
/* ... */
}
}
}
The "your:connections:mac:address" part you can figure out following this method, using the IP address of the LocalEndPoint.
How do I obtain the physical (MAC) address of an IP address using C#?
It's not beautiful, but it could work.
I'm using ManagementEventWatcher to watch the disconnection of network cable using System.Management.
ManagementEventWatcher with the WQL: SELECT * FROM MSNdis_StatusMediaDisconnect,
and the following method is fired, when EventArrived:
private void ServiceNetWorkStatusWmiDisconnected(object sender, EventArrivedEventArgs args)
{
string instanceName = args.NewEvent.Properties["InstanceName"].Value as string;
ServiceNetWorkStatusWmi = string.Format("Network disconnected ({0})", instanceName);
Console.WriteLine(ServiceNetWorkStatusWmi);
}
The problem is:
I have 2 network interfaces, from the same manufacturer , and both case, the InstanceName has the same value and I can´t identify what network unplugged!
I have tried all properties from EventArrivedEventArgs, but they don´t have a constraint id for device... like an Device Id.
How can I find out witch network interface was unplugged?
Have a look to the "Win32_NetworkAdapter.NetConnectionID". This is - at my machine [!!] - the excact same string you'll see in the network connections [control panel] and it should be the same value, apearing in "MSNdis_EnumerateAdapter.InstanceName=".
May be, this helps!?
br--mabra