Get remote IP address in .Net

Sometimes we need an application to identify the machine’s IP address, this is an easy task if the machine uses a single Network card and is a standalone machine.

If these were your requirement, the following code will return the machine’s IP Address

var currentIp = (
          from address in Dns.GetHostEntry(Dns.GetHostName()).AddressList
          where address.AddressFamily == AddressFamily.InterNetwork
          select address.ToString()
   ).FirstOrDefault();

But what if the machine is a server with multiple NICs and part of a network connected via a hub or a router?

If you use the previous code snippet, the returned IP Address will not be the remote IP Address, what you will get is the NAT address like something like 192.168.2.10

Since the framework does not have a utility or method to provide us with the remote address, we will have to be either creative or utilize external services or purchase commercial components. The only way I found to be valid and doesn't have any dependencies on external services or require buying components, is using the ole ping command.

The ping command uses different switches; we will be using two of them, “ping google.com -r x –n x”, where the x represent a numeric value.

if you run the following command from the command window, the result will be

C:\Users\sammy>ping google.com -r 1 -n 1
Pinging google.com [74.125.226.68] with 32 bytes of data
Reply from 74.125.226.68: bytes=32 time=25ms TTL=55
    Route: 70.50.75.187
Ping statistics for 74.125.226.68:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 25ms, Maximum = 25ms, Average = 25ms

The command explained;
ping google.com and Record route for 1 hop one time only.

Given this data, we can use the following code to return the remote address.

public static string RemoteIP(string hosttoping = "google.com")
       {
           string ipAddress = string.Empty;
           string pingResult = string.Empty;
 
           using (var pingProcess = new Process())
           {
               //the command arguments
               string param = String.Format("/c ping -r 1 -n 1 {0}", hosttoping);
               pingProcess.StartInfo = new ProcessStartInfo("cmd.exe", param) { RedirectStandardOutput = true, UseShellExecute = false };
               pingProcess.Start();
               pingResult = pingProcess.StandardOutput.ReadToEnd();
               // Set the regular expression to match IP addresses
               string ipPattern = @"Route: \b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b";
 
 
               var regex = new Regex(ipPattern, RegexOptions.Compiled);
 
               var match = regex.Match(pingResult);
               if (match.Success)
               {
                   //remote the word Route from the string and return only the IP Address
                   ipAddress = match.Value.Replace("Route: ", string.Empty);
               }
           }
           return ipAddress;
       }

Comments (2) -

Great post.

Marionnette 2/11/2014 6:39:05 PM

Yeah ! Thanks !

Pingbacks and trackbacks (1)+

Add comment