C Get Native IP Address (ipv4)

  • 2021-12-12 05:25:20
  • OfStack

Get all IP addresses on this machine:

These addresses are ipv4 and ipv6 addresses that contain all the network cards (virtual network cards).


 string name = Dns.GetHostName(); 
 IPAddress[] ipadrlist = Dns.GetHostAddresses(name); 

Get all IPV4 addresses on this machine:


string name = Dns.GetHostName(); 
IPAddress[] ipadrlist = Dns.GetHostAddresses(name); 
foreach (IPAddress ipa in ipadrlist) 
{ 
  if (ipa.AddressFamily == AddressFamily.InterNetwork) 
  Console.Writeline(ipa.ToString()); 
}

To get the ipv4 address alone, you can use the IPAdress. AddressFamily attribute to judge: for IPv4, return InterNetwork;; For IPv6, return InterNetworkV6.

However, if this machine may have multiple addresses for ipv4, how do you get the network card IP used to access the default gateway? In the CSDN forum, I found a great God's method, which is to query the native routing table.

Get the address of ipv4 being used by this machine (IP for accessing the Internet)

Don't underestimate, there are still many things to consider:

1.1 A computer has multiple network cards, wired, wireless, and vmare virtual two network cards.

2. Even if there is only one network card, the network card is configured with N IP addresses, including ipv6 addresses.


/// <summary> 
 ///  Gets the currently used IP 
 /// </summary> 
 /// <returns></returns> 
 public static string GetLocalIP() 
 { 
 string result = RunApp("route", "print",true); 
 Match m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)"); 
 if (m.Success) 
 { 
  return m.Groups[2].Value; 
 } 
 else 
 { 
  try 
  { 
  System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient(); 
  c.Connect("www.baidu.com", 80); 
  string ip = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address.ToString(); 
  c.Close(); 
  return ip; 
  } 
  catch (Exception) 
  { 
  return null; 
  } 
 } 
 } 
 /// <summary> 
 ///  Get the native owner DNS 
 /// </summary> 
 /// <returns></returns> 
 public static string GetPrimaryDNS() 
 { 
 string result = RunApp("nslookup", "",true); 
 Match m = Regex.Match(result, @"\d+\.\d+\.\d+\.\d+"); 
 if (m.Success) 
 { 
  return m.Value; 
 } 
 else 
 { 
  return null; 
 } 
 } 
 /// <summary> 
 ///  Run 1 Console program and returns its output parameters.  
 /// </summary> 
 /// <param name="filename"> Program name </param> 
 /// <param name="arguments"> Input parameters </param> 
 /// <returns></returns> 
 public static string RunApp(string filename, string arguments,bool recordLog) 
 { 
 try 
 { 
  if (recordLog) 
  { 
  Trace.WriteLine(filename + " " + arguments); 
  } 
  Process proc = new Process(); 
  proc.StartInfo.FileName = filename; 
  proc.StartInfo.CreateNoWindow = true; 
  proc.StartInfo.Arguments = arguments; 
  proc.StartInfo.RedirectStandardOutput = true; 
  proc.StartInfo.UseShellExecute = false; 
  proc.Start(); 
  using (System.IO.StreamReader sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default)) 
  { 
  //string txt = sr.ReadToEnd(); 
  //sr.Close(); 
  //if (recordLog) 
  //{ 
  // Trace.WriteLine(txt); 
  //} 
  //if (!proc.HasExited) 
  //{ 
  // proc.Kill(); 
  //} 
  // The above mark is the original text, and the following is my own debugging error and self-modification  
  Thread.Sleep(100);  // Seems to call the system nslookup Before the data is returned or the data is coded, the program has skipped direct execution  
      //txt = sr.ReadToEnd() The result is that the returned data is empty, so sleep makes the hardware react  
  if (!proc.HasExited)  // In the parameterless call nslookup After, you can continue to enter the command to continue the operation, and if the process does not stop, you can directly execute it  
  {    //txt = sr.ReadToEnd() The program is waiting for input, and it can't be input, so it can't continue to run directly  
   proc.Kill(); 
  } 
  string txt = sr.ReadToEnd(); 
  sr.Close(); 
  if (recordLog) 
   Trace.WriteLine(txt); 
  return txt; 
  } 
 } 
 catch (Exception ex) 
 { 
  Trace.WriteLine(ex); 
  return ex.Message; 
 } 
 }

Another method is obtained by using ipconfig:


private void GetIP() 
 { 
 Process cmd = new Process(); 
 cmd.StartInfo.FileName = "ipconfig.exe";// Set the program name  
 cmd.StartInfo.Arguments = "/all"; // Parameter  
 // Redirect standard output  
 cmd.StartInfo.RedirectStandardOutput = true; 
 cmd.StartInfo.RedirectStandardInput = true; 
 cmd.StartInfo.UseShellExecute = false; 
 cmd.StartInfo.CreateNoWindow = true;// Do not display windows (console program is black screen)  
 //cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;// I don't understand what it means for the time being  
 /* 
  Collect 1 Under   Be prepared  
  About :ProcessWindowStyle.Hidden How to show after hiding?  
 hwndWin32Host = Win32Native.FindWindow(null, win32Exinfo.windowsName); 
 Win32Native.ShowWindow(hwndWin32Host, 1); // First FindWindow Find the window and then ShowWindow 
 */ 
 cmd.Start(); 
 string info = cmd.StandardOutput.ReadToEnd(); 
 cmd.WaitForExit(); 
 cmd.Close(); 
 textBox1.AppendText(info); 
 } 

Related articles: