Detailed code case for C # getting a native IP address (IPv4)

Source: Internet
Author: User
Tags nslookup
This paper mainly introduces the method of acquiring all IP addresses of native computer in C #, the method of acquiring native IP address (IPv4) in C #, etc. Has a good reference value. Let's take a look at the little series.

Get all IP addresses for this machine:

These addresses are IPv4 and IPv6 addresses that contain all network cards (virtual network cards).

String name = Dns.gethostname ();  ipaddress[] ipadrlist = dns.gethostaddresses (name);

Get all IPV4 addresses for 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 simply, you can use the Ipadress.addressfamily property to determine: For IPV4, return internetwork; for IPV6, return InterNetworkV6.

However, if the machine may have more than one IPv4 address, how to obtain the network card IP that is used when accessing the default gateway. In the CSDN forum found the method of the great God, with the query native routing table.

Get the IPv4 address that the computer is using (IP that accesses the Internet)

Do not underestimate, or there are a lot to consider:

1. A computer has multiple network cards, wired, wireless, and Vmare virtual two network cards.

2. Even if there is only one network adapter, the NIC is configured with n IP addresses. It also includes the IPv6 address.

<summary>///Get the IP currently used///</summary>//<returns></returns> public static string Getloc  Alip () {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 native Primary DNS///</summary>//<returns></returns> public static Strin  G 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 a console program and return 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 ();  }//above is marked with the original text, the following is my own debugging error after self-modification thread.sleep (100); It seems that the nslookup of the calling system has not returned data or the data is not encoded, and the program has skipped direct execution//txt = Sr. ReadToEnd (), causing the returned data to be empty, so that sleep causes the hardware to react if (!proc. hasexited)//in no parameterAfter calling Nslookup, you can continue with the input command and execute {//txt = SR directly if the process does not stop. The ReadToEnd () program is waiting for input and cannot be entered, and the proc cannot continue running.   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 to obtain by using Ipconfig:

private void GetIP ()  {  process cmd = new process ();  Cmd. Startinfo.filename = "Ipconfig.exe";//Set Program name  cmd. startinfo.arguments = "/all"; Parameters  //redirect standard output  cmd. Startinfo.redirectstandardoutput = true;  Cmd. Startinfo.redirectstandardinput = true;  Cmd. Startinfo.useshellexecute = false;  Cmd. Startinfo.createnowindow = true;//does not display the window (the console program is a black screen)  //cmd. Startinfo.windowstyle = processwindowstyle.hidden;//don't understand what it means.  * * Collect some preparedness  about: How to display Processwindowstyle.hidden 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 Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.