简体   繁体   中英

Get the IP address of a machine connected to/in a VPN network

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.

If your network also supports IPv6 you should check for both ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM