C#获取本机局域网ip和公网ip的方法

---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------

1。获取局域网ip   



先看下面一个方法
[C#]  纯文本查看 复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
///
      /// 获取IP地址(IPv4)
      ///
      ///
    public static string GetIPAddress()
      {
          try
          {
              IPAddress[] arrIPAddresses = Dns.GetHostAddresses(Dns.GetHostName());
              foreach (IPAddress ip in arrIPAddresses)
              {
                  if (ip.AddressFamily.Equals(AddressFamily.InterNetwork)) //IPv4
                  {
                      return ip.ToString();
                  }
              }
              return "unknow" ;
          }
          catch
          {
              return "unknow" ;
          }
          finally
          {
          }
      }


当然也要吧使用如下方法
[C#]  纯文本查看 复制代码
?
01
02
IPAddress ipAddr = Dns.Resolve(Dns.GetHostName()).AddressList[0]; //获得当前IP地址
string ip=ipAddr.ToString() ;

2.下面是如何获取外网IP的方法

这里我们使用IP138来获取
[C#]  纯文本查看 复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
private static string GetIP()
        {
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = "http://www.ip138.com/ips138.asp"
            };
            HttpResult result = http.GetHtml(item);
            string html = result.Html;
            string ip = Regex.Match(html, @"您的IP地址是:\[(\d{1,4}\.\d{1,4}\.\d{1,4}\.\d{1,4})\]" ).Groups[1].Value.ToString();
 
            return ip;
        }

这里主要是使用我的Htttphelper类来实现,
为什么要这样获取呢,大家都知道,本机的外网IP是不能直接获取的,只能获取到局域网的IP。的所以只能借助于外力了。
3.如果要获取Adsl的IP可以使用如下方法

[C#]  纯文本查看 复制代码
?
01
02
03
string tempIP = string .Empty;
if (System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.Length >1)
      tempIP = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[1].ToString();



---------------------- ASP.Net+Unity开发、 .Net培训、期待与您交流! ----------------------详细请查看: www.itheima.com

你可能感兴趣的:(.net)