【问题标题】:get IP address of java client in java server [duplicate]在java服务器中获取java客户端的IP地址[重复]
【发布时间】:2023-04-08 23:55:01
【问题描述】:

我需要使用 IP 列表检查连接到我的 java 服务器的客户端 IP。

我用过

Sock.getRemoteSocketAddress().equals(ip).

但是 getRemoteSocketAddress() 给出 192.168.1.81:1115 但我只需要获取 IP 即 192.168.1.81

【问题讨论】:

    标签: java ip


    【解决方案1】:

    我想你想用InetSocketAddress.getAddress()like

    ((InetSocketAddress) Sock.getRemoteSocketAddress()).getAddress()
    

    或者,您可以使用 String.split(String) 喜欢

    Sock.getRemoteSocketAddress().toString().split(":")[0];
    

    【讨论】:

      【解决方案2】:

      req.getRemoteAddr()是方法

      如果你有servlet,那么

      public void doGet(HttpServletRequest req, HttpServletResponse resp)
       throws IOException {
      
              // Get client's IP address
              String ipAddress = req.getRemoteAddr(); // ip
      
              // Get client's hostname
              String hostname = req.getRemoteHost(); // hostname
          } 
      
      #
      import java.net.*;
      
      
      public class IP {
          public static void main(String[] args) throws Exception {
              System.out.println(InetAddress.getLocalHost());
              System.out.println(InetAddress.getByName("www.xxx.com"));
          }
      }
      

      【讨论】:

      • 导入 java.net.*;公共类 IP { public static void main(String[] args) 抛出异常 { System.out.println(InetAddress.getLocalHost()); System.out.println(InetAddress.getByName("www.xxx.com")); } }
      【解决方案3】:

      servletRequest.getRemoteAddr()

      String ipAddress = request.getRemoteAddr();

      【讨论】:

        猜你喜欢
        • 2021-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多