一个获取本机内网IP和外网IP的类的完整程序

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace ipip
{
 /// <summary>
 /// Class1 的摘要说明。
 /// 获取本机上网IP和内网IP
 /// </summary>
 public class Class1
 {
 
  private string strgetIP;
  
  public Class1()
  {
   //
  
  netIP();
  getIP(); 
  }
  
  
   
  

  public string renetIP()
  {return netIP();}//返回网络IP

  public string regetIP()
  {return strgetIP;}//返回内网IP

  
  static string netIP()
  {
   Uri uri = new Uri("http://www.ikaka.com/ip/index.asp");//查本机网络IP的网页
   HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
   req.Method = "POST";
   req.ContentType = "application/x-www-form-urlencoded";
   req.ContentLength = 0;
   req.CookieContainer = new CookieContainer();
   req.GetRequestStream().Write(new byte [0], 0, 0);
   HttpWebResponse res = (HttpWebResponse)(req.GetResponse());
   StreamReader rs = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("GB18030"));
   string s = rs.ReadToEnd();
   rs.Close();
   req.Abort();
   res.Close();
   Match m = Regex.Match(s, @"IP:\[(?<IP>[0-9\.]*)\]");
   if (m.Success) return m.Groups["IP"].Value;
   string strnetIP= string.Empty;
   return strnetIP;
  }

  public string getIP()//注意与static 的区别
  {
   System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;//获取本机内网IP
  

    strgetIP = addressList[0].ToString();
    return strgetIP;
   
  }

  
 
 }

}

posted on 2006-08-19 17:07  石川  阅读(1093)  评论(0)    收藏  举报