Friday, March 13, 2009

写了个小程序,parse网页的traceroute信息

动态域名服务商基本都被屏蔽了,DNS解析不了,只能通过IP访问。写了个程序解决这个问题。

 

以google为例子,程序会抓取信息,然后放到你的hosts文件里面,这样www.google.com就可以直接用了。 目标地址是 http://www.telstra.net.au/cgi-bin/trace?www.google.com 如果你的机器能够访问的话,应该程序就能使。代码如下,想修改的自己可以拿c#改。


static void Main(string[] args)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                byte[] buf = new byte[8192];
                // prepare the web page we will be asking for
                HttpWebRequest request = (HttpWebRequest)
                    WebRequest.Create(@"http://www.telstra.net.au/cgi-bin/trace?www.google.com");
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream resStream = response.GetResponseStream();
                string tempString = null;
                int count = 0;
                do
                {
                    count = resStream.Read(buf, 0, buf.Length);
                    if (count != 0)
                    {
                        // translate from bytes to ASCII text
                        tempString = Encoding.ASCII.GetString(buf, 0, count);
                        sb.Append(tempString);
                    }
                } while (count > 0);
                string resovle_to_ip = "\twww.google.com";
                string regexPattern = @"traceroute to www.l.google.com \((?<ip>[^a-zA-Z]+)\),";
                Regex re = new Regex(regexPattern, RegexOptions.ExplicitCapture);
                Match m = re.Match(sb.ToString());
                resovle_to_ip = m.Groups["ip"].Value + resovle_to_ip;
                try
                {
                    using (StreamReader rfile = new StreamReader(@"C:\WINDOWS\system32\drivers\etc\hosts"))
                    {
                        using (StreamWriter wfile = new StreamWriter(@"C:\WINDOWS\system32\drivers\etc\hosts_temp"))
                        {
                            string line;
                            while ((line = rfile.ReadLine()) != null)
                            {
                                if (!line.Contains("www.google.com"))
                                    wfile.WriteLine(line);
                            }
                            wfile.WriteLine(resovle_to_ip);
                            wfile.Close();
                        }
                        rfile.Close();
                    }
                    File.Copy(@"C:\WINDOWS\system32\drivers\etc\hosts_temp", @"C:\WINDOWS\system32\drivers\etc\hosts", true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                Console.WriteLine("({0}) successfully written to hosts file.", resovle_to_ip);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

No comments: