C#获取外网IP

思路是通过WebRequest连接一些网上提供IP查询服务的网站,下载到含有你的IP的网页,然后用正则表达式提取出IP来

 

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetExportIP());

            Console.ReadKey();
        }

        public static string GetExportIP() 
        {
            //获取外部IP
            string strUrl = "http://www.ip.cn/getip.php?action=getip&ip_url=&from=web";
            //string strUrl = "http://216.157.85.151/getip.php?action=getip&ip_url=&from=web";
            Uri uri = new Uri(strUrl);
            WebRequest webreq = WebRequest.Create(uri);
            Stream s = webreq.GetResponse().GetResponseStream();
            StreamReader sr = new StreamReader(s, Encoding.Default);
            string all = sr.ReadToEnd();
            all = Regex.Replace(all,@"(\d+)","000$1");
            all = Regex.Replace(all, @"0+(\d{3})", "$1");
            string reg = @"(\d{3}\.\d{3}\.\d{3}\.\d{3})";
            Regex regex = new Regex(reg);
            Match match = regex.Match(all);
            string ip = match.Groups[1].Value;
            return Regex.Replace(ip,@"0*(\d+)","$1");
        }
    }

  


 

posted @ 2013-07-02 22:24  liqipeng  阅读(344)  评论(0编辑  收藏  举报