2014-12-24 65 views
-3

在我的應用程序中,我寫了查找用戶的IP地址。如何防止用戶從兩個ip地址登錄?

HttpServletRequest httpRequest = (HttpServletRequest) request; 
String userIpAddress = httpRequest.getHeader("X-Forwarded-For"); 

     HttpServletRequest.getLocalAddr(); 

和獲取服務器的IPS,可以這樣做:

Inet4Address.getLocalHost().getHostAddress(); 

因此,如果用戶已經從一個IP地址登錄,如何限制他從另一個IP地址登錄?

+0

InetAddress.getLocalHost()。getHostAddress(); –

回答

2

嘗試下面的代碼:

Inet4Address address=(Inet4Address) Inet4Address.getLocalHost(); 
System.out.println(address.getHostAddress()); 

Inet4Address來自java.net.Inet4Address;

0

最好的方式找到局域網中的主機地址可以如下進行:

System.out.println(InetAddress.getByName("anyhostname").getHostAddress()); 
0

試試這個,它會枚舉本地機器的所有接口地址。

try { 
     Enumeration<NetworkInterface> interfaceEnumeration = 
       NetworkInterface.getNetworkInterfaces(); 
     while (interfaceEnumeration.hasMoreElements()) { 
      Enumeration<InetAddress> inetAddressEnumeration = 
        interfaceEnumeration.nextElement().getInetAddresses(); 
      while (inetAddressEnumeration.hasMoreElements()) { 
       System.out.println(inetAddressEnumeration.nextElement().getHostAddress()); 
      } 
     } 
    } catch (SocketException e) { 
     e.printStackTrace(); 
    } 

但是下面的方法不可靠,在我的測試環境中,它總是返回環回接口地址。

try { 
     InetAddress inetAddress[] = InetAddress.getAllByName("localhost"); 
     for (InetAddress address : inetAddress) { 
      System.out.println(address.getHostAddress()); 
     } 
    } catch (UnknownHostException e) { 
     e.printStackTrace(); 
    }