用.NET(C#)實現IP定位地理位置 (1)

用.NET(C#)實現IP定位地理位置 (1)

網上實現IP定位地理位置的技術大部分是PHP和Java,.NET的我找了很久仍是還沒找到。黃某因而蚍蜉撼樹,通過幾個小時的找資料,寫代碼,終於皇天不負有心人,基於.net的IP定位地理位置的網頁實現了,若有同志有興趣,不妨看看,最還能提些意見,感激涕零!
1.準備工做:
要下載的東西是MaxMind的免費GeoLiteCity數據庫和C# API。地址www.maxmind.com 以下圖: 用.NET(C#)實現IP定位地理位置 <wbr>(1)

用.NET(C#)實現IP定位地理位置 <wbr>(1)

用.NET(C#)實現IP定位地理位置 <wbr>(1)

用.NET(C#)實現IP定位地理位置 <wbr>(1)

用.NET(C#)實現IP定位地理位置 <wbr>(1)

二進制數據可下載完成後,解壓GeoLiteCity.dat就能夠了。
而後在VS2008中新建一個網站和一個類庫,給網站添加Bin文件夾.
把下載下來的GeoIP-CSharp-1_2.zip解壓出來,把將CS文件添加到類庫中。其中有幾個以Example結尾的文件不用加。否則從新生成會報錯。而後將生成的dll文件添加到bin文件夾中。
這樣準備工做就完成了。 用.NET(C#)實現IP定位地理位置 <wbr>(1)

2.Ip地址搜索頁面的生成
用於往地圖頁面「傳輸」數據。
前臺頁面只要這句話就夠了:
<%@ Page Language="C#" CodeFile="SearchIP.aspx.cs" Inherits="SearchIP" %>
否則地圖頁面調用eval(data);會出錯;

後臺代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Data;
using System.Configuration;
using System.Net;

public partial class SearchIP : System.Web.UI.Page
{
    string IP="";
    string Domain="";
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            if (Request.QueryString.Count != 0)
                Domain = Request.QueryString["q"].ToString();
            if (Domain == "")
            {
                IP = IPAddress;
                if (IP == "" || IP.Equals(null))
                {
                    Response.Write("<script>alert(找不到IP地址!');</script>");
                    return;
                }
            }
            else
            {
                if (!IsIPAddress(Domain))
                {
                    IP = GetIPByDomain(Domain);
                    if (!IsIPAddress(IP))
                    {
                        Response.Write("<script>alert('找不到IP地址!');</script>");
                        return;
                    }
                }
                else
                    IP = Domain;
            }
           
        }
        catch (Exception e1)
        {
            Response.Write("<script>alert('出錯了!');</script>");
            return;
        }
          LoadPage();

    }
//獲取IP地址
    public static string IPAddress
    {
        get
        {
            string result = String.Empty;

            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (result != null && result != String.Empty)
            {
                //可能有代理
                if (result.IndexOf(".") == -1)     //沒有「.」確定是非IPv4格式
                    result = null;
                else
                {
                    if (result.IndexOf(",") != -1)
                    {
                        //有「,」,估計多個代理。取第一個不是內網的IP。
                        result = result.Replace(" ", "").Replace("'", "");
                        string[] temparyip = result.Split(",;".ToCharArray());
                        for (int i = 0; i < temparyip.Length; i++)
                        {
                            if (IsIPAddress(temparyip[i])
                                && temparyip[i].Substring(0, 3) != "10."
                                && temparyip[i].Substring(0, 7) != "192.168"
                                && temparyip[i].Substring(0, 7) != "172.16.")
                            {
                                return temparyip[i];     //找到不是內網的地址
                            }
                        }
                    }
                    else if (IsIPAddress(result)) //代理便是IP格式
                        return result;
                    else
                        result = null;     //代理中的內容 非IP,取IP
                }

            }

            string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            //if (IpAddress == "127.0.0.1" || IpAddress=="localhost")
            //    result = Dns.GetHostEntry(Dns.GetHostName()).AddressList[5].ToString();
            using (System.Net.WebClient wc = new System.Net.WebClient())
            {
                result = wc.DownloadString("http://www.zu14.cn/ip/");//用本身的電腦訪問http://www.zu14.cn/ip/獲取IP地址
            }


            if (null == result || result == String.Empty)
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (result == null || result == String.Empty)
                result = HttpContext.Current.Request.UserHostAddress;

            return result;
        }
    }

    public static bool IsIPAddress(string str1)//判斷是否是IP地址的格式
    {
        if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;
        string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
        Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
        return regex.IsMatch(str1);
    }

    public string GetIPByDomain(string url)//根據域名取得IP地址
    {
        if (url.Trim() == string.Empty)
            return "";
        try
        {
            System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry(url);
            return host.AddressList.GetValue(0).ToString();
        }
        catch
        {
            return "";
        }
    }

    public void LoadPage()
    {
        try
        {
            LookupService ls = new LookupService("C:/Users/hzh-PC/Desktop/GeoLiteCity.dat", LookupService.GEOIP_STANDARD);//使用MaxMind的API
            //get city location of the ip address
            if (IP != null)
            {
                Location l = new Location();
                 l = ls.getLocation(IP);
                if (l != null)
                {
                    string fun= "loadGeoInfo("+
                        '"' + Domain + "\"," +
                        '"'+ IP +"\","+
                        '"'+ l.countryCode + "\","+
                        '"'+ l.countryName +"\","+
                        '"'+ l.regionName +"\","+
                        '"' + l.city + "\"," +
                        l.latitude +',' +
                        l.longitude +")";                   
                    Response.Write(fun);
                   
                   
                }
                else
                {                   
                    Response.Write("<script>alert('找不到IP地址!');</script>");
                    return;
                }
            }
            else
            {
                Response.Write("<script>alert('找不到IP地址!!');</script>");
                return;
            }
        }
        catch (Exception e)
        {
            Response.Write("<script>alert('錯誤:" + e.Message + "');</script>");
        }
    }
}
該頁面的默認是得到本身電腦的IP的信息,能夠經過SearchIP?q=XXX來獲取特定IP或域名的信息。
運行結果:
用.NET(C#)實現IP定位地理位置 <wbr>(1)
相關文章
相關標籤/搜索