0

I'm trying to get the IPv4 string of ipconfig cmd using c# for consuming API on IIS server. I'm using this code

public static string GetLocalIPAddress()
{
    var host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (var ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            return ip.ToString();
        }
    }
    throw new Exception("No network adapters with an IPv4 address in the system!");
}

but the Ip I get from it is different from the one in ipconfig cmd. How can I get the exact IPv4 from ipconfig cmd using C#?

Mofi
  • 46,139
  • 17
  • 80
  • 143
Celty
  • 21
  • 3

2 Answers2

1

I don't know if this is what you want to do. But you can run the command "ipconfig" in c#
and use a regular expression to get the ip.
Like this:

System.Diagnostics.ProcessStartInfo procStartInfo =
    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + "ipconfig");
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Get IP
result = Regex.Match(result,@"IPv4.*:.(?'ip'([0-9]{0,3}\.){3}([0-9]{0,3}))").Groups["ip"].ToString();
// Display the command output.
Console.WriteLine(result);
  • I think this basically answers his question, but I also doubt that this is what he asked for. – ˈvɔlə Oct 28 '21 at 09:38
  • 1
    Thank you, this is what I'm looking for. It's a bit difficult for me to ask in English cause it's not my mother language. – Celty Oct 28 '21 at 10:13
0

You could also use this. To choose the interface you want to use. For example the interface type Ethernet and name "Ethernet" the name could also be "vEthernet" or "Virtualbox" ... Like this:

foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()){
  // Test connection type ip is Ethernet && Name == Ethernet
  if(ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet && ni.Name == "Ethernet")
  {
    // Console.WriteLine(ni.Name);
    foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
    {
      if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
      {
        //Console.WriteLine(ip.Address.ToString());
        return ip.Address.ToString();
      }
    }
  }
}

(this will be more optimized)