简体   繁体   中英

C# - How to get IP Address when connected to (RAS) VPN

Good afternoon,

Can anyone give any examples of how to obtain the IP Address of the local machine when it's connected to a remote windows domain network via VPN (RAS)? ie I need the VPN address and not the remote users local network address.

For example, my Server Side Windows Service communicates with my client side application and needs to create a log of all connected users and their IP Addresses.

This solution is easy enough when using a computer on the local network, but I wondered how I can go about getting the IP addresses of the users who are connected to the server via VPN. Please note that the IP address get method will be executed client side and sent to the server.

Here's my current code that works only when locally connected to the domain network:

public static string GetLocalIPv4()
{
    string ipv4Address = String.Empty;

    foreach (IPAddress currrentIPAddress in Dns.GetHostAddresses(Dns.GetHostName()))
    {
        if (currrentIPAddress.AddressFamily.ToString() == System.Net.Sockets.AddressFamily.InterNetwork.ToString())
        {
            ipv4Address = currrentIPAddress.ToString();
            break;
        }
    }

    return ipv4Address;
}

Our internal network is controlled by Windows SBS and uses a domain such as mycompany.local.

Thank you very much for your time and I look forward to reading your responses.

Rob

As the comment from @MarcB notes, cannot think of a good reason why you might want that info... so would be interesting if you could explain a use for this in an application just out of curiosity.

However, there are a lot of incorrect answers on here and online regarding enumerating IP addresses for a machine by using Dns.GetHostAddresses. It appears most people are not realizing the difference between looking up a machine name in the configured DNS resolver versus enumerating the machine address. These are very different things and while it might seem to return the right results in many cases, this is absolutely the wrong way to go about it because they are not the same thing. For example, see this link to an article on here where the original poster flagged an incorrect response as the answer but the correct response is below by @StephanCleary. See: Get IPv4 Addresses

The difference is you want to look at the machines configuration and enumerate whatever IP address you are interested in locating from the machines own TCPIP stack. The code above and many of the incorrect responses try to lookup the name in the DNS resolver. Once you have that part correct, then you should be able to determine the VPN connection based on the network adaptor (by name or other attribute).

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