Created
January 4, 2019 05:08
-
-
Save xycui/57c5123765e8f4d34ca244e8ab264b56 to your computer and use it in GitHub Desktop.
Draft code for network related util code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
using System.Net.NetworkInformation; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace Helpers | |
{ | |
public class DeviceUtil | |
{ | |
public static IPAddress GetLocalIpv4Address() | |
{ | |
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces()) | |
{ | |
var ipProp = ni.GetIPProperties(); | |
var addr = ipProp.GatewayAddresses.FirstOrDefault(); | |
if (ni.OperationalStatus != OperationalStatus.Up) continue; | |
if (addr == null || addr.Address.ToString().Equals("0.0.0.0")) continue; | |
if (ni.NetworkInterfaceType != NetworkInterfaceType.Ethernet && | |
ni.NetworkInterfaceType != NetworkInterfaceType.Wireless80211) continue; | |
foreach (var ip in ipProp.UnicastAddresses) | |
{ | |
if (ip.Address.AddressFamily == AddressFamily.InterNetwork) | |
{ | |
return ip.Address; | |
} | |
} | |
} | |
var hostName = Dns.GetHostName(); | |
return | |
Dns.GetHostAddresses(hostName).First(item => item.AddressFamily == AddressFamily.InterNetwork && Dns.GetHostEntry(item).HostName.StartsWith(hostName)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment