博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

.net获取本机公网IP代码

Posted on 2016-01-04 16:57  preface小贝  阅读(249)  评论(0)    收藏  举报

using System;

using System.Net;
using System.Text.RegularExpressions;
 
namespace Keleyi.Com
{
    public class GetInternetIP
    {
        public static string GetIP()
        {
            using (var webClient = new WebClient())
            {
                try
                {
                    var temp = webClient.DownloadString("http://iframe.ip138.com/ic.asp");
                    var ip = Regex.Match(temp, @"\[(?<ip>\d+\.\d+\.\d+\.\d+)]").Groups["ip"].Value;
                    return !string.IsNullOrEmpty(ip) ? ip : null;
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
        }
    }
}