C#獲取本機外網ip
阿新 • • 發佈:2019-02-10
由於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(); } } }
結果: