且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#获取本机外网ip

更新时间:2021-07-11 15:28:30

由于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();
        }
    }
}


结果:

C#获取本机外网ip