static string[] fetchDnsIpResult(string domain) { Form1.instance.Invoke(new Action(() => { Form1.instance.addItem(domain); })); string ip = ""; if (domain == Properties.Settings.Default.dnsServerName) return new string[] { Properties.Settings.Default.dnsServerIp }; if (dnsCache.ContainsKey(domain)) { ip = dnsCache[domain].ip; dnsCache[domain] = new CacheEntry(ip); return splitIps(ip); } string url = string.Format(Properties.Settings.Default.dnsServer, domain); WebRequest wr = WebRequest.Create(url); try { var sr = new System.IO.StreamReader(wr.GetResponse().GetResponseStream(), true); ip = sr.ReadToEnd(); } catch(Exception) { throw new NetworkInformationException(); } if (ip == "" || ip == domain) throw new NetworkInformationException(); if (dnsCache.Count > MaxCacheCount) { DateTime stamp = DateTime.Now; string victim = ""; foreach (KeyValuePair<string, CacheEntry> pair in dnsCache) { if (pair.Value.timeStamp < stamp) stamp = pair.Value.timeStamp; victim = pair.Key; } if (dnsCache.ContainsKey(victim)) dnsCache.Remove(victim); } try { dnsCache.Add(domain, new CacheEntry(ip)); } catch { } return splitIps(ip); }
private void button2_Click(object sender, EventArgs e) { new System.Threading.Thread(new System.Threading.ThreadStart(() => { Dictionary<string, string> hostsRecords = new Dictionary<string, string>(); foreach (string url in Properties.Settings.Default.hostsUpdate.Split('|')) { WebRequest wr = WebRequest.Create(url); try { StreamReader sr = new StreamReader(wr.GetResponse().GetResponseStream()); while (!sr.EndOfStream) { string line = sr.ReadLine().Trim(); if (line.StartsWith("#")) continue; string[] cols = line.Split(' ', '\t'); if (cols.Length < 2) continue; string domain = cols[cols.Length - 1]; if (!hostsRecords.ContainsKey(domain)) hostsRecords.Add(domain, ""); if (!hostsRecords[domain].Contains(cols[0] + "\r")) hostsRecords[domain] += cols[0] + "\r"; } } catch (Exception) { } } foreach (KeyValuePair<string, string> pair in hostsRecords) { CacheEntry entry = new CacheEntry(pair.Value); entry.timeStamp = DateTime.MaxValue; if (Program.dnsCache.ContainsKey(pair.Key)) Program.dnsCache[pair.Key] = entry; else Program.dnsCache.Add(pair.Key, entry); } MessageBox.Show("更新完毕!"); })).Start(); }