C#获取本机外网ip

来源:互联网 发布:大数据如何分析 编辑:程序博客网 时间:2024/06/01 07:52

由于ip地址是变动的,所以我们需要自动获取到外网的ip,然后我就写了一段code来自动获取到外网的ip,就不需要每次手写了,就方便多了。

using System;using System.Net;using System.Text.RegularExpressions;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            try            {                WebClient client = new WebClient();                client.Encoding = System.Text.Encoding.Default;                string response = client.UploadString("http://iframe.ip138.com/ipcity.asp", "");                Match mc = Regex.Match(response, @"location.href=""(.*)""");                if (mc.Success && mc.Groups.Count > 1)                {                    response = client.UploadString(mc.Groups[1].Value, "");                    string[] str1 = response.Split('[');                    response = str1[1];                    string [] str = response.Split(']');                    response = str[0];                    Console.Write(response);                }            }            catch (System.Exception e)            {            }            Console.Read();        }    }}


结果:



原创粉丝点击