Reputation: 632
I need to know the IP address of a machine connected to a VPN. I have used the following algorithm to do so:
if (NetworkInterface.GetIsNetworkAvailable()) { // First check if any connections are present
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
bool vpnExists=false;
string ipAddr="?";
foreach (NetworkInterface Interface in interfaces)
{ // Loop through all interfaces present
if (Interface.OperationalStatus == OperationalStatus.Up)
{ // consider only if an interface is currently active
if (Interface.NetworkInterfaceType == NetworkInterfaceType.Tunnel) // refering to vpn
{ // vpn found
vpnExists=true;
foreach (UnicastIPAddressInformation ip in Interface.GetIPProperties().UnicastAddresses) {
// Program control reaches here without any problem
if (ip.Address.AddressFamily==AddressFamily.InterNetwork) { // this block does not execute as expected
ipAddr=ip.Address.ToString();
}
}
}
else
{ // vpn not found
continue; // Goto another interface
}
}
}
}
/*
Final state of variables:
vpnExists: true
ipAddr: "?"
*/
The code functions perfectly till the VPN checking part (for all networks I've tried on) but does not display the IP address after the detection of VPN. I don't understand why the statement (ip.Address.AddressFamily==AddressFamily.InterNetwork)
returns false as I believe that it is the correct way to get IP addresses.
Can anyone please point out why is this happening? And an in-depth explanation would also be helpful.
Thanks in advance.
UPDATE: This issue has been solved by mapping the IP address manually. Anyways, thanks to everyone who took interest and helped to solve.
Upvotes: 0
Views: 1565
Reputation: 6744
If your network also supports IPv6 you should check for both i.e. instead of
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
use:
if (ip.Address.AddressFamily == AddressFamily.InterNetwork
|| ip.Address.AddressFamily == AddressFamily.InterNetworkV6)
You can see all the values of the AddressFamily
enum here on MSDN.
Upvotes: 1