c# 获取中国所有IP
作者:互联网
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { DateTime start = System.DateTime.Now; List<something> soms = GetIp(); DateTime end = System.DateTime.Now; WriteFile(soms); Console.WriteLine("执行时间为:" + (end - start).ToString("T")); Console.WriteLine("总IP数:" + soms.Count); Console.ReadLine(); } //获取最新中国地区IPV4地址段 public static List<something> GetIp() { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest"); request.Host = "ftp.apnic.net"; request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"; request.Headers.Add("Accept-Encoding", "gzip, deflate"); request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9"); request.Headers.Add("Cache-Control", "max-age=0"); request.Headers.Add("Cookie", "__cfduid=dbbe005c7bff8939bd00da2e62711b7481547619516; _ga=GA1.2.332852563.1547619523; _gid=GA1.2.1547830089.1547619523"); request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"; HttpWebResponse response; response = (HttpWebResponse)request.GetResponse(); Stream s; s = response.GetResponseStream(); string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "UTF-8"; //默认编码 } StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); string retString = reader.ReadToEnd(); int indexa = retString.IndexOf("2|"); string end = retString.Remove(0, indexa + 2); string[] striparr = end.Split(new string[] { "\n" }, StringSplitOptions.None); List<something> soms = new List<something>(); foreach (var item in striparr) { string[] i = item.Split('|'); if (i.Length == 7 && i[1] == "CN" && i[2] == "ipv4") { something som = new ConsoleApplication1.something(); som.org = i[0]; som.country = i[1]; som.type = i[2]; som.startIp = i[3]; som.ipCount = i[4]; som.setTime = i[5]; som.setType = i[6]; soms.Add(som); } } return soms; } public static void WriteFile(List<something> arr) { StreamWriter sw = new StreamWriter(@"\桌面\新建文件夹\ConsoleApplication1\IPS1.txt", true, System.Text.Encoding.Default); for (int i = 0; i < arr.Count; i++) { sw.WriteLine(arr[i].startIp); Console.WriteLine(arr[i].startIp); } sw.Close(); } } }
标签:string,som,c#,IP,request,System,获取,using,soms 来源: https://www.cnblogs.com/had3s/p/10372935.html