C # obtain the local IP address (ipv4 ),

Source: Internet
Author: User
Tags nslookup

C # obtain the local IP address (ipv4 ),
Obtain all IP addresses of the local machine:

These addresses are ipv4 and ipv6 addresses that contain all NICs (Virtual NICS.

1 string name = Dns.GetHostName();  2 IPAddress[] ipadrlist = Dns.GetHostAddresses(name);  
Obtain all IPV4 addresses of the local machine:
1 string name = Dns.GetHostName();  2 IPAddress[] ipadrlist = Dns.GetHostAddresses(name);  3 foreach (IPAddress ipa in ipadrlist)  4 {  5             if (ipa.AddressFamily == AddressFamily.InterNetwork)  6             Console.Writeline(ipa.ToString());  7 }  

To obtain an ipv4 address, use the IPAdress. AddressFamily attribute to determine whether InterNetwork is returned for IPv4 addresses or InterNetworkV6 for IPv6 addresses.

However, if the local machine may have multiple ipv4 addresses, How can I obtain the NIC IP address used to access the default gateway. On the CSDN forum, I found a great way to query the route table of the local machine.

 

Obtain the ipv4 address in use on the local machine (IP address used to access the Internet)

Don't underestimate it. There are still many things to consider:
1. A computer has multiple NICs, wired, wireless, and vmare.
2. Even if there is only one Nic, the NIC is configured with n ip addresses, including ipv6 addresses.

1 /// <summary> 2 /// obtain the currently used IP address 3 /// </summary> 4 /// <returns> </returns> 5 public static string GetLocalIP () 6 {7 string result = RunApp ("route", "print", true); 8 Match m = Regex. match (result, @ "0.0.0.0 \ s + 0.0.0.0 \ s + (\ d +. \ d +. \ d +. \ d +) \ s + (\ d +. \ d +. \ d +. \ d +) "); 9 if (m. success) 10 {11 return m. groups [2]. value; 12} 13 else 14 {15 try 16 {17 System. net. sockets. tcpClient c = new System. net. sockets. tc PClient (); 18 c. connect ("www.baidu.com", 80); 19 string ip = (System. net. IPEndPoint) c. client. localEndPoint ). address. toString (); 20 c. close (); 21 return ip; 22} 23 catch (Exception) 24 {25 return null; 26} 27} 28} 29 30 // <summary> 31 // obtain the host's primary DNS 32 /// </summary> 33 // <returns> </returns> 34 public static string GetPrimaryDNS () 35 {36 string result = RunApp ("nslookup", "", true); 37 Matc H m = Regex. match (result, @ "\ d + \. \ d + \. \ d + \. \ d + "); 38 if (m. success) 39 {40 return m. value; 41} 42 else 43 {44 return null; 45} 46} 47 48 // <summary> 49 // run a console program and return its output parameters. 50 /// </summary> 51 /// <param name = "filename"> program name </param> 52 /// <param name = "arguments"> enter the Parameter </param> 53 // <returns> </returns> 54 public static string RunApp (string filename, string arguments, bool recordLog) 55 {56 try 57 {58 if (recordLog) 59 {60 Trace. writeLine (filename + "" + arguments); 61} 62 Process proc = new Process (); 63 proc. startInfo. fileName = filename; 64 proc. startInfo. creat ENoWindow = true; 65 proc. startInfo. arguments = arguments; 66 proc. startInfo. redirectStandardOutput = true; 67 proc. startInfo. useShellExecute = false; 68 proc. start (); 69 70 using (System. IO. streamReader sr = new System. IO. streamReader (proc. standardOutput. baseStream, Encoding. default) 71 {72 // string txt = sr. readToEnd (); 73 // sr. close (); 74 // if (recordLog) 75 // {76 // Trace. writeLine (txt); 77 //} 78 // if (! Proc. hasExited) 79 // {80 // proc. kill (); 81 //} 82 // The above mark is the original text. below is the 83 Thread that I modified after debugging errors. sleep (100); // it seems that the nslookup of the calling system has not returned data or the data has not been encoded, and the program has skipped and runs 84 // txt = sr. when ReadToEnd () is returned, the returned data is empty. Therefore, sleep causes the hardware to respond to 85 if (! Proc. hasExited) // After nslookup is called without a parameter, you can continue to enter the command to continue the operation. If the process is not stopped, run 86 directly {// txt = sr. the ReadToEnd () program is waiting for input and cannot be entered. It cannot continue running 87 proc. kill (); 88} 89 string txt = sr. readToEnd (); 90 sr. close (); 91 if (recordLog) 92 Trace. writeLine (txt); 93 return txt; 94} 95} 96 catch (Exception ex) 97 {98 Trace. writeLine (ex); 99 return ex. message; 100} 101}

You can use ipconfig to obtain the following information:

1 private void GetIP () 2 {3 Process cmd = new Process (); 4 cmd. startInfo. fileName = "ipconfig.exe"; // set the program name to 5 cmd. startInfo. arguments = "/all"; // parameter 6 // redirect standard output 7 cmd. startInfo. redirectStandardOutput = true; 8 cmd. startInfo. redirectStandardInput = true; 9 cmd. startInfo. useShellExecute = false; 10 cmd. startInfo. createNoWindow = true; // do not display the window (the console program is a black screen) 11 // cmd. startInfo. windowStyle = ProcessWindowSty Le. Hidden; // What do you mean for the moment? 12/* 13. Collect the information and prepare it. 14. About: How can I display ProcessWindowStyle. Hidden after hiding it? 15 hwndWin32Host = Win32Native. findWindow (null, win32Exinfo. windowsName); 16 Win32Native. showWindow (hwndWin32Host, 1); // find the window in FindWindow and then ShowWindow 17 */18 cmd. start (); 19 string info = cmd. standardOutput. readToEnd (); 20 cmd. waitForExit (); 21 cmd. close (); 22 textBox1.AppendText (info); 23}

 

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.