巧用C# 取外網IP

iDotNetSpace發表於2010-09-07

// C# IP地址轉長整數
        public long ip2long(String ip)
        {
            System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse(ip);
            byte[] bytes = ipaddress.GetAddressBytes();
            Array.Reverse(bytes);
            return BitConverter.ToUInt32(bytes, 0);
        }

        static string GetIP()
        {
            string strUrl = "http://www.ip138.com/ip2city.asp"; //獲得IP的網址了
            Uri uri = new Uri(strUrl);
            WebRequest wr = WebRequest.Create(uri);
            Stream s = wr.GetResponse().GetResponseStream();
            StreamReader sr = new StreamReader(s, Encoding.Default);
            string all = sr.ReadToEnd(); //讀取網站的資料
            int i = all.IndexOf("[") + 1;
            string tempip = all.Substring(i, 15);
            string ip = tempip.Replace("]", "").Replace(" ", "");
            return ip;
        }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-672871/,如需轉載,請註明出處,否則將追究法律責任。

相關文章