In cause of my latest project Simple Proxy Switch I had to face the challenge of detecting the setting of the current network the computer is connected to.
Now here’s my snippet how do I retrieve the current network setting:
// zero conf ip address IPAddress zeroConf = new IPAddress(0); // get current assigned addresses IPAddress[] hostAddresses = Dns.GetHostAddresses(Dns.GetHostName()); var networkData = NetworkInterface.GetAllNetworkInterfaces() // filter running network interfaces .Where(network => network.OperationalStatus == OperationalStatus.Up) // filter unknown interfaces .Where(network => network.NetworkInterfaceType != NetworkInterfaceType.Unknown) // filter loopback interfaces .Where(network => network.NetworkInterfaceType != NetworkInterfaceType.Loopback) // get the properties .Select(network => network.GetIPProperties()) // filter initialized gateways .Where(ipProps => ipProps.GatewayAddresses.All(gateway => gateway.Address != zeroConf)) // filter and get ip addresses .SelectMany(ipProps => ipProps.UnicastAddresses.Where(ucAddress => hostAddresses.Contains(ucAddress.Address))) .Where(ucAddress => hostAddresses.Contains(ucAddress.Address)) // simply use the first .FirstOrDefault();
Be the force with you!
No comments:
Post a Comment