c#获取本机内网和外网IP

 1 //获取内网IP

 2 private string GetInternalIP()

 3 {

 4     IPHostEntry host;

 5     string localIP = "?";

 6     host = Dns.GetHostEntry(Dns.GetHostName());

 7     foreach (IPAddress ip in host.AddressList)

 8     {

 9         if (ip.AddressFamily.ToString() == "InterNetwork")

10         {

11             localIP = ip.ToString();

12             break;

13         }

14     }

15     return localIP;

16 }
 1 //获取外网IP

 2 private string GetExternalIP()

 3 {

 4     string direction = "";

 5     WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");

 6     using (WebResponse response = request.GetResponse())

 7     using (StreamReader stream = new StreamReader(response.GetResponseStream()))

 8     {

 9         direction = stream.ReadToEnd();

10     }

11     int first = direction.IndexOf("Address:") + 9;

12     int last = direction.LastIndexOf("</body>");

13     direction = direction.Substring(first, last - first);

14     return direction;

15 }

 

你可能感兴趣的:(C#)