C # implementation based on network IP display Location Function Example _ practical skills

Source: Internet
Author: User
The User Information table is available in most systems. We also know that there will usually be a field similar to the registered IP and the last login IP to store the IP address of the user at the time of registration and the IP address of the last login.

Get such an address, in the Background display xxx.xxx.xxx.xxx address section, let people see very unnatural, simply do not know the specific geographical location.

Now we can simply implement this function.
Used to read the common components of the pure IP database qqwry.net This component, the author Abu. (thank him for sharing)
Also to download the latest pure IP address library, download to get QQWry.dat
Finally, please out of JS in the little girl, jquery-1.3.1.js
Create a new Web project AJAXIP and add QQWry.dat to App_Data.
Then add the Qqwry.net component class, as follows:
Copy Code code as follows:

Code highlighting produced by Actipro Codehighlighter (freeware) http://www.codehighlighter.com/--> 1 using System;
Using System.Collections.Generic;
Using System.Text;
Using System.IO;
Using System.Text.RegularExpressions;
Using System.Net;
Using System.Net.Sockets;
Namespace Ajaxip
{
public class Iplocation
{
public string IP {get; set;}
public string Country {get; set;}
public string Local {get; set;}
}
public class Qqwrylocator
{
static Encoding Encoding = Encoding.GetEncoding ("GB2312");
Private byte[] data;
int firststartipoffset;
int laststartipoffset;
int ipcount;
public int Count {get {Ipcount}}
Public Qqwrylocator (String datapath)
{
using (FileStream fs = new FileStream (DataPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
data = new Byte[fs. Length];
Fs. Read (data, 0, data.) Length);
}
Firststartipoffset = (int) data[0] + (((int) data[1]) << 8) + (((int) data[2]) << ((int) data[3]) << 24);
Laststartipoffset = (int) data[4] + (((int) data[5]) << 8) + (((int) data[6]) << (((int) data[7]) << 2 4);
Ipcount = (laststartipoffset-firststartipoffset)/7 + 1;
if (Ipcount <= 1)
{
throw new ArgumentException ("IP filedataerror");
}
}
public static UINT Iptoint (string IP)
{
string[] Strarray = IP. Split ('. ');
return (UINT. Parse (Strarray[0]) <<) + (UINT. Parse (strarray[1]) <<) + (UINT. Parse (strarray[2]) << 8) + UINT. Parse (Strarray[0]);
return (UINT) ipaddress.hosttonetworkorder (int) (Ipaddress.parse (IP). address));
byte[] bytes = Ipaddress.parse (IP). Getaddressbytes ();
return (UINT) bytes[3] + ((UINT) bytes[2]) << 8) + (((UINT) bytes[1]) << (((UINT) bytes[0)) << 24);
}
public static string Inttoip (UINT ip_int)
{
return new IPAddress (Ip_int). ToString ();
}
Public iplocation Query (string IP)
{
IPAddress address = Ipaddress.parse (IP);
if (address. AddressFamily!= AddressFamily.InterNetwork)
{
throw new ArgumentException ("Do not support non-IPV4 addresses");
}
if (Ipaddress.isloopback (address))
{
return new Iplocation () {IP = IP, Country = "Native internal loopback address", local = string. Empty};
}
UINT INTIP = (UINT) ipaddress.hosttonetworkorder (int) address. address);
if (((Intip >= iptoint ("0.0.0.0") && (Intip <= iptoint ("2.255.255.255")) | | ((Intip >= iptoint ("64.0.0.0")) && Intip <= ("Iptoint"))) ||
((Intip >= iptoint ("58.0.0.0")) && Intip <= ("Iptoint")))
if (intip <= 50331647 | | (Intip >= 1073741824 && intip <= 2130706431) | | (Intip >= 973078528 && intip <= 1023410175))
//{
return new Iplocation () {IP = IP, Country = "Network reservation address", local = string. Empty};
//}
Iplocation iplocation = new Iplocation () {IP = IP};
UINT right = (uint) Ipcount;
UINT left = 0;
UINT middle = 0;
UINT StartIP = 0;
UINT Endipoff = 0;
UINT ENDIP = 0;
int countryflag = 0;
while (left < (right-1))
{
Middle = (right + left)/2;
StartIP = Getstartip (middle, out endipoff);
if (Intip = = StartIP)
{
left = Middle;
Break
}
if (Intip > StartIP)
{
left = Middle;
}
Else
{
right = Middle;
}
}
StartIP = Getstartip (left, out Endipoff);
EndIP = Getendip (Endipoff, out Countryflag);
if ((StartIP <= intip) && (EndIP >= intip))
{
String Local;
Iplocation.country = Getcountry (Endipoff, Countryflag, out);
iplocation.local = local;
}
Else
{
Iplocation.country = "Unknown";
Iplocation.local = string. Empty;
}
return iplocation;
}
Private UINT Getstartip (uint left, out uint Endipoff)
{
int leftoffset = (int) (Firststartipoffset + (left * 7));
Endipoff = (UINT) Data[4 + LeftOffset] + (((UINT) data[5 + leftoffset]) << 8) + (((UINT) data[6 + leftoffset]) << 16);
return (UINT) Data[leftoffset] + ((UINT) data[1 + leftoffset]) << 8) + (((UINT) data[2 + leftoffset]) << 16) + ( ((UINT) data[3 + leftoffset]) << 24);
}
Private UINT Getendip (UINT endipoff, out int countryflag)
{
Countryflag = data[4 + Endipoff];
return (UINT) Data[endipoff] + ((UINT) data[1 + Endipoff]) << 8) + ((UINT) data[2 + Endipoff]) << ((UINT ) Data[3 + Endipoff]) << 24);
}
<summary>
Gets the country.
</summary>
<param name= "Endipoff" >the End IP off.</param>
<param name= "Countryflag" >the country flag.</param>
<param name= "local" >the local.</param>
<returns>country</returns>
private string Getcountry (uint endipoff, int countryflag, out string local)
{
String country = string. Empty;
UINT offset = Endipoff + 4;
Switch (Countryflag)
{
Case 1:
Case 2:
Country = GETFLAGSTR (ref offset, ref countryflag, ref Endipoff);
offset = Endipoff + 8;
Local = (1 = countryflag)? String. EMPTY:GETFLAGSTR (ref offset, ref countryflag, ref Endipoff);
Break
Default
Country = GETFLAGSTR (ref offset, ref countryflag, ref Endipoff);
Local = GETFLAGSTR (ref offset, ref countryflag, ref Endipoff);
Break
}
return country;
}
private string GETFLAGSTR (ref UINT offset, ref int countryflag, ref uint Endipoff)
{
int flag = 0;
while (true)
{
flag = Data[offset];
No redirection
if (flag!= 1 && flag!= 2)
{
Break
}
if (flag = 2)
{
Countryflag = 2;
Endipoff = offset-4;
}
offset = (UINT) Data[1 + offset] + ((UINT) data[2 + offset]) << 8) + (((UINT) data[3 + offset]) << 16);
}
if (Offset < 12)
{
return string. Empty;
}
return Getstr (ref offset);
}
<summary>
Read string ...
</summary>
<param name= "offset" ></param>
<returns></returns>
private string GETSTR (ref UINT offset)
{
byte lowbyte = 0;
byte highbyte = 0;
StringBuilder StringBuilder = new StringBuilder (16);
while (true)
{
Lowbyte = data[offset++];
if (lowbyte = 0)
{
return stringbuilder.tostring ();
}
if (Lowbyte > 0x7f)
{
Highbyte = data[offset++];
if (highbyte = 0)
{
return stringbuilder.tostring ();
}
Stringbuilder.append (encoding. GetString (new byte[] {lowbyte, highbyte}));
}
Else
{
Stringbuilder.append ((char) lowbyte);
}
}
}
}
}

Again, create a new Ipsearch.ashx file, as follows:
Copy Code code as follows:

Code highlighting produced by Actipro Codehighlighter (freeware) http://www.codehighlighter.com/--> 1 using System;
Using System.Collections;
Using System.Data;
Using System.Linq;
Using System.Web;
Using System.Web.Services;
Using System.Web.Services.Protocols;
Using System.Xml.Linq;
Namespace Ajaxip
{
<summary>
Summary description of IP query
</summary>
public class Ipsearch:ihttphandler
{
public void ProcessRequest (HttpContext context)
{
Context. Response.ContentType = "Text/plain";
String IP = context. request["IP"];
String ipfilepath = @ "\app_data\qqwry.dat";
Qqwrylocator Qqwry = new Qqwrylocator (Ipfilepath);
Iplocation loc = Qqwry.query (IP);
Context. Response.Write (String. Format (' {0} {1} ', loc. Country,loc. local));
}
public bool IsReusable
{
Get
{
return false;
}
}
}
}

Finally, write down the Default.aspx page, JS and the user information with IP, as follows:
Copy Code code as follows:

Code highlighting produced by Actipro Codehighlighter (freeware) http://www.codehighlighter.com/--> 1 <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<script language= "javascript" src= "Js/jquery-1.3.1.js" ></script>
<script language= "JavaScript" >
$ (document). Ready (function () {
$ ("#tb tr"). each (function () {
var obj = $ (this). Children ("Td:eq (2)");
Searchip (obj);
});
})
function Searchip (obj) {
$.ajax ({
Type: "Get",
URL: "ipsearch.ashx?ip=" + obj.text (),
Success:function (data) {
Obj.text (data);
}
});
}
</script>
<body>
<form id= "Form1" runat= "Server" >
<div>
<table id= "TB" style= "width:100%;" >
<thead>
<th>321321</th>
<th>321321</th>
<th>321321</th>
</thead>
<tr>
<td>
Omega</td>
<td>
0</td>
<td>
122.229.191.8</td>
</tr>
<tr>
<td>
Famine </td>
<td>
900,000</td>
<td>
110.87.98.30</td>
</tr>
<tr>
<td>
Cold Princess </td>
<td>
1,854,257,979</td>
<td>
220.188.193.72</td>
</tr>
<tr>
<td>
Harbin Small Earth </td>
<td>
600,100</td>
<td>
220.188.193.72</td>
</tr>
<tr>
<td>
Makeup styling </td>
<td>
400,100</td>
<td>
220.188.193.72</td>
</tr>
</table>
</div>
</form>
</body>

This way our backend user information is no longer an unfriendly IP address segment.
Run it and see how it works.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.