I want to find the ip that my computer connects to the internet correctly.I have questions about a few things I have tried. Firstly :
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) {
var addr = ni.GetIPProperties().GatewayAddresses.FirstOrDefault();
if (addr != null && ni.OperationalStatus == OperationalStatus.Up) {
switch (ni.NetworkInterfaceType) {
case NetworkInterfaceType.Wireless80211:
case NetworkInterfaceType.Ethernet:
{
foreach(UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) {
if (ip.Address.AddressFamily == AddressFamily.InterNetwork) {
return ip.Address.ToString();
}
}
break;
}
}
}
}
When I tried the code above, if my computer has a virtual adapter installed (for example vpn), the vpn adapter is also detected as ethernet and operational status up. When I run vpn, there are two strings ip like (192.168.1.24 and 25.25.1.150). As a result of this error, I decided to find the name of my computer and ping it and find a rope with the returned result. like the code below:
int timeout = 10000;
Ping ping = new Ping();
try {
PingReply pingreply = ping.Send(Environment.MachineName.ToString(), timeout);
if (pingreply.Status == IPStatus.Success) {
return pingreply.Address.ToString();
}
}
catch(Exception ex) {
LogHelper.WriteErrorLog(ex);
return String.Empty;
}
return String.Empty;
The code above works fine, but there are a few things I can't be sure of. Is there a possibility that the hostname with the second code will be return null? If there are two computer names in the same domain(can be possible?), can I get the correct result from the ping result? Is there any other way than these two codes find correctly under all circumstances? Thank you.