C#获取内、外网IP的类

//创建类

//www.wanyouc.com  www.cnhgds.com  www.yunweis.com

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

///


///GetOutIP 的摘要说明
///

public class GetOutIP
{
    private string strgetIP;


    public GetOutIP()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
        netIP();
        getIP();

    }

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

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


    static string netIP()
    {
        Uri uri = new Uri("http://www.ip138.com/ip2city.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();
        s = s.Substring(s.IndexOf('[') + 1, s.Length - s.LastIndexOf(']') -11);      //自己灵活取出IP
        return s;
        //Match m = Regex.Match(s, @"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;

    }

}

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