`
liufei.fir
  • 浏览: 675873 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论
阅读更多
public String getIpAddrByRequest(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

C#根据用户IP地址查询用户信息

调用接口来自sina,显示的信息较为全面。
接口地址为  http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip={ip}
返回json,格式为如下
{"ret":1,"start":"59.174.77.0","end":"59.174.80.156","country":"\u4e2d\u56fd",
"province":"\u6e56\u5317","city":"\u6b66\u6c49","district":"","isp":"\u7535\u4fe1","type":"","desc":""}
为了方便使用,加入类IpDetai解析json。
使用方式(ASP.NET):
Label1.Text = IpHelper.Get("xx.xx.xx.xxx",null).Province;
另外JSON解析用到了.net 3.5的System.Web.Script.Serialization.JavaScriptSerializer 

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

namespace IpUtils
{
	public class IpDetail
	{
		public String Ret { get; set; }

		public String Start { get; set; }

		public String End { get; set; }

		public String Country { get; set; }

		public String Province { get; set; }

		public String City { get; set; }

		public String District { get; set; }

		public String Isp { get; set; }

		public String Type { get; set; }

		public String Desc { get; set; }
	}

	public class IpHelper
	{
		/// <summary>
		/// 获取IP地址的详细信息,调用的借口为
		/// http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip={ip}
		/// </summary>
		/// <param name="ipAddress">请求分析得IP地址</param>
		/// <param name="sourceEncoding">服务器返回的编码类型</param>
		/// <returns>IpUtils.IpDetail</returns>
		public static IpDetail Get(String ipAddress,Encoding sourceEncoding)
		{
			String ip = string.Empty;
			if(sourceEncoding==null)
				sourceEncoding = Encoding.UTF8;
			using (var receiveStream = WebRequest.Create("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip="+ipAddress).GetResponse().GetResponseStream())
			{
				using (var sr = new StreamReader(receiveStream, sourceEncoding))
				{
					var readbuffer = new char[256];
					int n = sr.Read(readbuffer, 0, readbuffer.Length);
					int realLen = 0;
					while (n > 0)
					{
						realLen = n;
						n = sr.Read(readbuffer, 0, readbuffer.Length);
					}
					ip = sourceEncoding.GetString(sourceEncoding.GetBytes(readbuffer, 0, realLen));
				}
			}
			return  !string.IsNullOrEmpty(ip)?new JavaScriptSerializer().Deserialize<IpDetail>(ip):null;
		}
	}

	public class EncodingHelper
	{
		public static String GetString(Encoding source, Encoding dest, String soureStr)
		{
			return dest.GetString(Encoding.Convert(source, dest, source.GetBytes(soureStr)));
		}

		public static String GetString(Encoding source, Encoding dest, Char[] soureCharArr, int offset, int len)
		{
			return dest.GetString(Encoding.Convert(source, dest, source.GetBytes(soureCharArr, offset, len)));
		}
	}
}


获取 IP 地址对应的地区(JavaScript)
function detect_city($ip) {
        
        $default = 'Hollywood, CA';

        if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')
            $ip = '8.8.8.8';

        $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
        
        $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
        $ch = curl_init();
        
        $curl_opt = array(
            CURLOPT_FOLLOWLOCATION  => 1,
            CURLOPT_HEADER      => 0,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_USERAGENT   => $curlopt_useragent,
            CURLOPT_URL       => $url,
            CURLOPT_TIMEOUT         => 1,
            CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],
        );
        
        curl_setopt_array($ch, $curl_opt);
        
        $content = curl_exec($ch);
        
        if (!is_null($curl_info)) {
            $curl_info = curl_getinfo($ch);
        }
        
        curl_close($ch);
        
        if ( preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs) )  {
            $city = $regs[1];
        }
        if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs) )  {
            $state = $regs[1];
        }

        if( $city!='' && $state!='' ){
          $location = $city . ', ' . $state;
          return $location;
        }else{
          return $default; 
        }
        
    }


Android 获取 IP 地址
public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); 
		en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); 
		enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}


分析用户ip归属地
<?php
//这些是核心部分,可以写到一个单独的php里,用的时候直接include就可以
define('__QQWRY__' , dirname(__FILE__)."/qqwry.dat");
class QQWry{
    var $StartIP=0;
    var $EndIP=0;
    var $Country='';
    var $Local='';
    var $CountryFlag=0;
    var $fp;
    var $FirstStartIp=0;
    var $LastStartIp=0;
    var $EndIpOff=0 ;
    function getStartIp($RecNo){
     $offset=$this->FirstStartIp+$RecNo * 7 ;
     @fseek($this->fp,$offset,SEEK_SET) ;
     $buf=fread($this->fp ,7) ;
     $this->EndIpOff=ord($buf[4]) + (ord($buf[5])*256) + (ord($buf[6])* 256*256);
     $this->StartIp=ord($buf[0]) + (ord($buf[1])*256) + (ord($buf[2])*256*256) + (ord($buf[3])*256*256*256);
     return $this->StartIp;
    }
    function getEndIp(){
     @fseek ( $this->fp , $this->EndIpOff , SEEK_SET ) ;
     $buf=fread ( $this->fp , 5 ) ;
     $this->EndIp=ord($buf[0]) + (ord($buf[1])*256) + (ord($buf[2])*256*256) + (ord($buf[3])*256*256*256);
     $this->CountryFlag=ord ( $buf[4] ) ;
     return $this->EndIp ;
    }
    function getCountry(){
     switch ( $this->CountryFlag ) {
        case 1:
        case 2:
         $this->Country=$this->getFlagStr ( $this->EndIpOff+4) ;
         //echo sprintf('EndIpOffset=(%x)',$this->EndIpOff );
         $this->Local=( 1 == $this->CountryFlag )? '' : $this->getFlagStr ( $this->EndIpOff+8);
         break ;
        default :
         $this->Country=$this->getFlagStr ($this->EndIpOff+4) ;
         $this->Local=$this->getFlagStr ( ftell ( $this->fp )) ;
     }
    }
    function getFlagStr ($offset){
     $flag=0 ;
     while(1){
        @fseek($this->fp ,$offset,SEEK_SET) ;
        $flag=ord(fgetc($this->fp ) ) ;
        if ( $flag == 1 || $flag == 2 ) {
         $buf=fread ($this->fp , 3 ) ;
         if ($flag==2){
            $this->CountryFlag=2;
            $this->EndIpOff=$offset - 4 ;
         }
         $offset=ord($buf[0]) + (ord($buf[1])*256) + (ord($buf[2])* 256*256);
        }
        else{
         break ;
        }
     }
     if($offset<12)
        return '';
     @fseek($this->fp , $offset , SEEK_SET ) ;

     return $this->getStr();
    }
    function getStr ( )
    {
     $str='' ;
     while ( 1 ) {
        $c=fgetc ( $this->fp ) ;
        if(ord($c[0])== 0 )
         break ;
        $str.= $c ;
     }
     return $str ;
    }
    function qqwry ($dotip='') {
        if( !is_string($dotip) || $dotip==''){return;}
                if(preg_match("/^127/",$dotip)){$this->Country="本地网络";return ;}
        elseif(preg_match("/^192/",$dotip)) {$this->Country="局域网";return ;}

     $nRet;
     $ip=$this->IpToInt ( $dotip );
     $this->fp= fopen(__QQWRY__, "rb");
     if ($this->fp == NULL) {
         $szLocal= "OpenFileError";
        return 1;
     }
     @fseek ( $this->fp , 0 , SEEK_SET ) ;
     $buf=fread ( $this->fp , 8 ) ;
     $this->FirstStartIp=ord($buf[0]) + (ord($buf[1])*256) + (ord($buf[2])*256*256) + (ord($buf[3])*256*256*256);
     $this->LastStartIp=ord($buf[4]) + (ord($buf[5])*256) + (ord($buf[6])*256*256) + (ord($buf[7])*256*256*256);
     $RecordCount= floor( ( $this->LastStartIp - $this->FirstStartIp ) / 7);
     if ($RecordCount <= 1){
        $this->Country="FileDataError";
        fclose($this->fp) ;
        return 2 ;
     }
     $RangB= 0;
     $RangE= $RecordCount;
     while ($RangB < $RangE-1)
     {
     $RecNo= floor(($RangB + $RangE) / 2);
     $this->getStartIp ( $RecNo ) ;

        if ( $ip == $this->StartIp )
        {
         $RangB=$RecNo ;
         break ;
        }
     if ($ip>$this->StartIp)
        $RangB= $RecNo;
     else
        $RangE= $RecNo;
     }
     $this->getStartIp ( $RangB ) ;
     $this->getEndIp ( ) ;

     if ( ( $this->StartIp <= $ip ) && ( $this->EndIp >= $ip ) ){
        $nRet=0 ;
        $this->getCountry ( ) ;
        $this->Local=str_replace("(我们一定要解放台湾!!!)", "", $this->Local);
     }
     else{
        $nRet=3 ;
        $this->Country='未知' ;
        $this->Local='' ;
     }
     fclose ( $this->fp );
        return $nRet ;
    }
    function IpToInt($Ip) {
     $array=explode('.',$Ip);
     $Int=($array[0] * 256*256*256) + ($array[1]*256*256) + ($array[2]*256) + $array[3];
     return $Int;
    }
}
function GetIP(){//获取IP
    return $_SERVER[REMOTE_ADDR]?$_SERVER[REMOTE_ADDR]:$GLOBALS[HTTP_SERVER_VARS][REMOTE_ADDR];
}
?>

jQuery 如何获取浏览器所在的IP地址
$(function () {
    $("#btnGetIP").click(function () {
        var jqxhr = $.getJSON("http://jsonip.appspot.com?callback=?",
            function (data) {
                alert(data.ip);
            })
        .error(function () { alert("error"); })
    });
});

获取本机的真实IP地址
public class Main {

	public static void main(String[] args) throws SocketException {
		System.out.println(Main.getRealIp());
	}

	public static String getRealIp() throws SocketException {
		String localip = null;// 本地IP,如果没有配置外网IP则返回它
		String netip = null;// 外网IP

		Enumeration<NetworkInterface> netInterfaces = 
			NetworkInterface.getNetworkInterfaces();
		InetAddress ip = null;
		boolean finded = false;// 是否找到外网IP
		while (netInterfaces.hasMoreElements() && !finded) {
			NetworkInterface ni = netInterfaces.nextElement();
			Enumeration<InetAddress> address = ni.getInetAddresses();
			while (address.hasMoreElements()) {
				ip = address.nextElement();
				if (!ip.isSiteLocalAddress() 
						&& !ip.isLoopbackAddress() 
						&& ip.getHostAddress().indexOf(":") == -1) {// 外网IP
					netip = ip.getHostAddress();
					finded = true;
					break;
				} else if (ip.isSiteLocalAddress() 
						&& !ip.isLoopbackAddress() 
						&& ip.getHostAddress().indexOf(":") == -1) {// 内网IP
					localip = ip.getHostAddress();
				}
			}
		}
	
		if (netip != null && !"".equals(netip)) {
			return netip;
		} else {
			return localip;
		}
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics