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()

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

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 -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 -r 1 -n 1
Pinging [] with 32 bytes of data
Reply from bytes=32 time=25ms TTL=55
Ping statistics for
    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 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 = "")
           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 };
               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)+

Comments are closed