精华内容
下载资源
问答
  • 本文介绍了JAVA如何获取客户端IP地址和MAC地址 ,分享给大家,具体如下:1.获取客户端IP地址public String getIp(HttpServletRequest request) throws Exception {String ip = request.getHeader("X-Forwarded-For")...

    本文介绍了JAVA如何获取客户端IP地址和MAC地址 ,分享给大家,具体如下:

    1.获取客户端IP地址

    public String getIp(HttpServletRequest request) throws Exception {

    String ip = request.getHeader("X-Forwarded-For");

    if (ip != null) {

    if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {

    int index = ip.indexOf(",");

    if (index != -1) {

    return ip.substring(0, index);

    } else {

    return ip;

    }

    }

    }

    ip = request.getHeader("X-Real-IP");

    if (ip != null) {

    if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {

    return ip;

    }

    }

    return request.getRemoteAddr();

    }

    为什么不直接使用request.getRemoteAddr();而要在之前判断两个请求头"X-Forwarded-For"和"X-Real-IP"

    X-Forwarded-For: client1, proxy1, proxy2, proxy3

    其中的值通过一个 逗号+空格 把多个IP地址区分开, 最左边(client1)是最原始客户端的IP地址, 代理服务器每成功收到一个请求,就把请求来源IP地址添加到右边。

    所有我们只取第一个IP地址

    X-Real-IP,一般只记录真实发出请求的客户端IP

    解决用localhost访问ip为0:0:0:0:0:0:0:1的问题

    public String getIp(HttpServletRequest request) throws Exception {

    String ip = request.getHeader("X-Forwarded-For");

    if (ip != null) {

    if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {

    int index = ip.indexOf(",");

    if (index != -1) {

    return ip.substring(0, index);

    } else {

    return ip;

    }

    }

    }

    ip = request.getHeader("X-Real-IP");

    if (ip != null) {

    if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {

    return ip;

    }

    }

    ip = request.getHeader("Proxy-Client-IP");

    if (ip != null) {

    if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {

    return ip;

    }

    }

    ip = request.getHeader("WL-Proxy-Client-IP");

    if (ip != null) {

    if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {

    return ip;

    }

    }

    ip = request.getRemoteAddr();

    return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;

    }

    2.获取客户端MAC地址

    UdpGetClientMacAddr umac = new UdpGetClientMacAddr(sip);

    String smac = umac.GetRemoteMacAddr();

    添加一个获取MAC的时间限制

    final UdpGetClientMacAddr umac = new UdpGetClientMacAddr(sip);

    //---长时间获取不到MAC地址则放弃

    ExecutorService exec = Executors.newFixedThreadPool(1);

    Callable call = new Callable() {

    public String call() throws Exception {

    return umac.GetRemoteMacAddr();

    }

    };

    try {

    Future future = exec.submit(call);

    String smac = future.get(1000 * 1, TimeUnit.MILLISECONDS);

    loginMonitor.setMacAddress(smac);

    } catch (TimeoutException ex) {

    loginMonitor.setMacAddress("获取失败");

    logger.info("获取MAC地址超时");

    ex.printStackTrace();

    }

    // 关闭线程池

    exec.shutdown();

    //---

    需要先获取IP地址作为参数构造一个UdpGetClientMacAddr

    UdpGetClientMacAddr.java

    package shmc.commonsys.security.controller;

    import java.io.IOException;

    import java.net.DatagramPacket;

    import java.net.DatagramSocket;

    import java.net.InetAddress;

    /**

    * 主机A向主机B发送“UDP-NetBIOS-NS”询问包,即向主机B的137端口,发Query包来询问主机B的NetBIOS Names信息。

    * 其次,主机B接收到“UDP-NetBIOS-NS”询问包,假设主机B正确安装了NetBIOS服务........... 而且137端口开放,则主机B会向主机A发送一个“UDP-NetBIOS-NS”应答包,即发Answer包给主机A。

    * 并利用UDP(NetBIOS Name Service)来快速获取远程主机MAC地址的方法

    *

    */

    public class UdpGetClientMacAddr {

    private String sRemoteAddr;

    private int iRemotePort=137;

    private byte[] buffer = new byte[1024];

    private DatagramSocket ds=null;

    public UdpGetClientMacAddr(String strAddr) throws Exception{

    sRemoteAddr = strAddr;

    ds = new DatagramSocket();

    }

    public final DatagramPacket send(final byte[] bytes) throws IOException {

    DatagramPacket dp = new DatagramPacket(bytes,bytes.length,InetAddress.getByName(sRemoteAddr),iRemotePort);

    ds.send(dp);

    return dp;

    }

    public final DatagramPacket receive() throws Exception {

    DatagramPacket dp = new DatagramPacket(buffer,buffer.length);

    ds.receive(dp);

    return dp;

    }

    public byte[] GetQueryCmd() throws Exception {

    byte[] t_ns = new byte[50];

    t_ns[0] = 0x00;

    t_ns[1] = 0x00;

    t_ns[2] = 0x00;

    t_ns[3] = 0x10;

    t_ns[4] = 0x00;

    t_ns[5] = 0x01;

    t_ns[6] = 0x00;

    t_ns[7] = 0x00;

    t_ns[8] = 0x00;

    t_ns[9] = 0x00;

    t_ns[10] = 0x00;

    t_ns[11] = 0x00;

    t_ns[12] = 0x20;

    t_ns[13] = 0x43;

    t_ns[14] = 0x4B;

    for(int i = 15; i < 45; i++){

    t_ns[i] = 0x41;

    }

    t_ns[45] = 0x00;

    t_ns[46] = 0x00;

    t_ns[47] = 0x21;

    t_ns[48] = 0x00;

    t_ns[49] = 0x01;

    return t_ns;

    }

    public final String GetMacAddr(byte[] brevdata) throws Exception {

    // 获取计算机名

    int i = brevdata[56] * 18 + 56;

    String sAddr="";

    StringBuffer sb = new StringBuffer(17);

    // 先从第56字节位置,读出Number Of Names(NetBIOS名字的个数,其中每个NetBIOS Names Info部分占18个字节)

    // 然后可计算出“Unit ID”字段的位置=56+Number Of Names×18,最后从该位置起连续读取6个字节,就是目的主机的MAC地址。

    for(int j = 1; j < 7;j++)

    {

    sAddr = Integer.toHexString(0xFF & brevdata[i+j]);

    if(sAddr.length() < 2)

    {

    sb.append(0);

    }

    sb.append(sAddr.toUpperCase());

    if(j < 6) sb.append(':');

    }

    return sb.toString();

    }

    public final void close() throws Exception {

    ds.close();

    }

    public final String GetRemoteMacAddr() throws Exception {

    byte[] bqcmd = GetQueryCmd();

    send(bqcmd);

    DatagramPacket dp = receive();

    String smac = GetMacAddr(dp.getData());

    close();

    return smac;

    }

    public static void main(String args[]) throws Exception{

    UdpGetClientMacAddr umac=new UdpGetClientMacAddr("172.19.1.198");

    umac=new UdpGetClientMacAddr("192.168.16.83");

    System.out.println(umac.GetRemoteMacAddr());

    }

    }

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    展开全文
  • I need client IP address using ... I have tried below code but its not working in server:from socket import gethostname, gethostbynameip = gethostbyname(gethostname())print ipOn the server, I get ...

    I need client IP address using python. I have tried below code but its not working in server:

    from socket import gethostname, gethostbyname

    ip = gethostbyname(gethostname())

    print ip

    On the server, I get '127.0.0.1' every time. Is there any way to find IP address of the client?

    解决方案

    You're getting the IP address of your server, not of your server's clients.

    You want to look at the request's REMOTE_ADDR, like this:

    from bottle import Bottle, request

    app = Bottle()

    @app.route('/hello')

    def hello():

    client_ip = request.environ.get('REMOTE_ADDR')

    return ['Your IP is: {}\n'.format(client_ip)]

    app.run(host='0.0.0.0', port=8080)

    EDIT #1: Some folks have observed that, for them, the value of REMOTE_ADDR is always the same IP address (usually 127.0.0.1). This is because they're behind a proxy (or load balancer). In this case, the client's original IP address is typically stored in header HTTP_X_FORWARDED_FOR. The following code will work in either case:

    @app.route('/hello')

    def hello():

    client_ip = request.environ.get('HTTP_X_FORWARDED_FOR') or request.environ.get('REMOTE_ADDR')

    return ['Your IP is: {}\n'.format(client_ip)]

    EDIT #2: Thanks to @ArtOfWarfare's comment, I learned that REMOTE_ADDR is not required per PEP-333. Couple of observations:

    The CGI spec does require REMOTE_ADDR:

    The REMOTE_ADDR variable MUST be set to the network address of the client sending the request to the server.

    However, PEP-333 does not explicitly require HTTP_REMOTE_ADDR, only going as far as this (emphasis mine):

    A server or gateway SHOULD attempt to provide as many other CGI variables as are applicable.

    All of the (admittedly few) web frameworks that I'm familiar with set HTTP_REMOTE_ADDR. AFAICT, it's a de facto "standard." But technically, YMMV.

    展开全文
  • 除了thinkphp内置get_client_ip函数外,也可使用下面函数获取客户端IP地址。 $type表示返回类型 0 返回IP地址, 1 返回IPV4地址数字 分享代码如下 function get_client_ip($type = 0) { $type = $type ? 1 : 0; ...
  • php如何获取客户端请求ip地址的方法获取客户端ip地址的函数 获取客户端ip地址的函数 function getip() { $ip = false; if (!empty($_SERVER["HTTP_CLIENT_IP"])) { $ip = $_SERVER["HTTP_CLIENT_IP"]; } if ...

    php如何获取客户端请求ip地址的方法

    获取客户端ip地址的函数

        function getip()
        {
            $ip = false;
            if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
                $ip = $_SERVER["HTTP_CLIENT_IP"];
            }
            if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
                if ($ip) {
                    array_unshift($ips, $ip);
                    $ip = FALSE;
                }
                for ($i = 0; $i < count($ips); $i++) {
                    if (!preg_match("/^(10│172.16│192.168)./i", $ips[$i])) {
                        $ip = $ips[$i];
                        break;
                    }
                }
            }
            return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
        }
    
    $ip = getip();
    
    展开全文
  • 您可以使用以下示例在Applet中获取客户端IP地址。 该过程并非如此简单,您必须从加载Applet的位置获取当前主机和端口,并将其转换为Socket对象。 Socket socket = new Socket(getDocumentBase().getHost(), port);...

    您可以使用以下示例在Applet中获取客户端IP地址。 该过程并非如此简单,您必须从加载Applet的位置获取当前主机和端口,并将其转换为Socket对象。

    Socket socket = new Socket(getDocumentBase().getHost(), port);
    ip = socket.getLocalAddress().getHostAddress();

    在Applet中获取IP地址的示例

    package com.mkyong.applet;
    
    import java.applet.*;
    import java.awt.Graphics;
    import java.io.IOException;
    import java.net.Socket;
    
    public class AppletExample extends Applet {
    
    	String ip;
    	
    	public void init() {
    		
    	  try{
    		int port;
    			
    		if(getDocumentBase().getPort()!=-1){
    			port = getDocumentBase().getPort();
    		}else{
    			port = 80;
    		}
    	
    	        Socket socket = new Socket(getDocumentBase().getHost(), port);
    		ip = socket.getLocalAddress().getHostAddress();
    		
                }catch(IOException io){
    		System.out.println(io.getMessage());
    	    }
    	}
       
    	public void paint( Graphics g ) {
    	  
    	   StringBuffer sb = new StringBuffer()
       		.append(" IP address : ").append(ip);
    	   
    	   g.drawString(sb.toString(), 0,100);
    	}
       
    }

    翻译自: https://mkyong.com/applet/how-to-get-client-ip-address-in-applet/

    展开全文
  • c#如何获取客户端IP

    千次阅读 2008-02-16 10:33:00
    //获取客户端IP地址 TextBox1.Text = Request.UserHostAddress; //获取服务器的主机名 string hostName = Dns.GetHostName(); //获取服务器的IP地址 IPAddress[] ips; ips = Dns.GetHost
  • Struts2中获得request及ip  //在struts2中获得request  HttpServletRequest request = ServletActionContext. getRequest();  //获得ip地址(防止代)
  • 在项目中获取客户端IP地址

    千次阅读 2013-09-12 09:46:26
    在项目中记录日志时一般需要记录客户端IP地址如何获取呢?下面是一个封装的方法: /** * 获取Ip地址 * @return */ protected String getIpAddr() { HttpServletRequest request = ServletActionContext.get...
  • 客户端ip:Request.ServerVariables.Get("Remote_Addr").ToString();客户端主机名:Request.ServerVariables.Get("Remote_Host").ToString();客户端浏览器IE:Request.Browser.Browser;客户端浏览器 版本号:Request....
  • 通过负载设备后,TongWeb上的应用通过request.getRemoteAddr()方式得到的是负载设备的IP,而得不到真实的客户端IP。 解决办法: 经过代理以后,由于在客户端和服务之间增加了中间层,因此服务器无法直接拿到...
  • <p>How to get ip address of client. <p>I have checked through proxy REMOTE_ADDR,HTTP_X_FORWARDED_FOR but both not giving me correct ip</p> <p>REMOTE_ADDR_IP is not working. </div>
  • How do I get the IP and port of a client with PHP?I tried the script below but it only gives me the IP address.解决方案Port is defined in http server (Apache or other and mostly it is 80 or 443)I am ...
  • C#如何获取客户端/服务端IP地址

    千次阅读 2011-10-24 16:57:00
    客户端ip: Request.ServerVariables.Get("Remote_Addr").ToString(); 客户端主机名: Request.ServerVariables.Get("Remote_Host").ToString(); 客户端浏览器IE: Request.Browser.Browser; 客户端浏览器 版本...
  • 如何使用grpc-java从请求元数据中获取客户端ip(How to get client ip from request metadata with grpc-java)我使用grpc-java并通过ServerInterceptor获取元数据,但我得到以下信息没有客户端IP地址,权限是服务器IP...
  • <a href="/questions/3003145/how-to-get-the-client-ip-address-in-php" dir="ltr">How to get the client IP address in PHP [duplicate] 30 answers <p>I tried like this <pre><code>echo ...
  • 客户端ip:Request.ServerVariables.Get("Remote_Addr").ToString();客户端主机名:Request.ServerVariables.Get("Remote_Host").ToString();客户端浏览器IE:Request.Browser.Browser;客户端浏览器 版本号:Request....
  • php 如何获取真实的客户端ip

    千次阅读 2018-08-21 14:42:23
    最近在做一个需求,需要获取客户端ip,使用的是$_SERVER[”REMOTE_ADDR’],测试发现不真实 使用下列代码即可获取真实ip,亲测有效 //获取用户IP地址 public function getIp() { if(!empty($_SERVER["...
  • Liferay portlet 如何取得客户端IP地址(portal get remote IP)分类: 开发随笔liferaystruts22010-11-22 09:30179人阅读评论(0)收藏举报方案一Liferay 屏蔽了获取remot
  • private static string getIPAddress(){ System.Net.IP...// 获得拨号动态分配IP地址addr = new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address) ;return addr.ToSt
  • PHP获取客户端IP常用方法及安全隐患

    千次阅读 2018-08-14 11:57:00
    如何获取IP归属地,请参照我另一篇博文:第三方接口获取IP归属地 目前网上获取IP的常见代码如下: /** * 获取ip地址 * @return string|null */ public static function getIp() { $ip = ''; if ($_SERVER...
  • 如何获取伪装ip下的真实ip地址

    千次阅读 2018-06-12 20:46:11
    客户端ip其实不是个简单的活儿,因为存在Ip欺骗,和代理问题,所以获取客户端的IP的真实性会打折扣的,不能百分百准确.但是我们还是尽量找一个比较完善的获取客户端真正ip方法.使用php获取IP的方法能找到很多. ...
  • <p>then I do <code>ip := net.ParseIP(s)</code> and then <code>ip = ip.To4()</code> to get the IPv4 address. <p>I am on Windows and have this in my hosts file: (The rest is commented out.) <pre><code...
  • 一种127.0.0.1解析不了 我知道, 可是真实IP地址也解析不了 例如:59.56.127.226 这个就解析不了。 而192.168.19.14 类似这样就可以解析的了.. 请问这是什么原因造成的呢? [code="java"] public final String ...
  • 在Web应用开发中,经常会需要获取客户端IP地址。一个典型的例子就是投票系统,为了防止刷票,需要限制每个IP地址只能投票一次。 如何获取客户端IP 在Java中,获取客户端IP最直接的方式就是使用request.getR...
  • I tried using the following code to get the IP address but for localhost it gives me <code>::1:56797</code> as output. My server is running on <code>localhost:8080</code></p> <pre><code>ip, port, ...
  • tornado获得客户端设备信息和ip地址

    千次阅读 2016-01-13 12:38:06
    tornado如何获取客户端设备信息 其实torando中有已经提供好的接口可以获取所有HTTPServerRequest中的信息 先看一下HTTPServerRequest中可以获取的信息都有哪些 HTTPServerRequest( protocol='http', host='192.168....
  • 这里的难点主要在于如何通过PHP获取客户端IP地址,以及如何GET方式向服务接口发送请求和获取相应。 ====================获取IP地址===================== 通常情况下只需要 $_SERVER['REM...
  • 资料参考www.dingniuw.com 通过HttpServletRequest对象可以获得 Java code /** * 获取客户端IP地址 */ public final String getRemoteIP() { HttpServletRequest request = getRequest(); if...
  • 1 // 在客户端显示端点连接IP及端口号信息 2 static void show_endpoint(const Ice::ObjectPrx &proxy) 3 { 4 Ice::ConnectionPtr conn = proxy->ice_getConnection(); 5 if(conn) 6 { 7 ...
  • 查阅资料发现,这种情况出现在服务器与客户端在同一地址的时候,比如楼主是通过 subject.getSession().getHost() 来获取登录者的IP地址,当本地登录时自然就是获取到0:0:0:0:0:0:0:1这个值了。 那如何获取到...

空空如也

空空如也

1 2 3 4 5
收藏数 94
精华内容 37
关键字:

如何获取客户端ip地址getip