How to get client Ip Address in Java HttpServletRequest

前端 未结 4 1036
时光取名叫无心
时光取名叫无心 2020-12-25 12:07

I am trying to develop a Java web application (Servlet) which I need to get clients IP address.

Following is my code so far:



        
4条回答
  •  清歌不尽
    2020-12-25 12:33

     import java.net.UnknownHostException;
    
    /**
     * Simple Java program to find IP Address of localhost. This program uses
     * InetAddress from java.net package to find IP address.
     *
     */
    public class IPTest { 
    
    public static void main(String args[]) throws UnknownHostException {
    
        InetAddress addr = InetAddress.getLocalHost();
    
        //Getting IPAddress of localhost - getHostAddress return IP Address
        // in textual format
        String ipAddress = addr.getHostAddress();
    
        System.out.println("IP address of localhost from Java Program: " + ipAddress);
    
        //Hostname
        String hostname = addr.getHostName();
        System.out.println("Name of hostname : " + hostname);     
    }
    }
    

    Output:

    IP address of localhost from Java Program: 190.12.209.123
    Name of hostname : PCLOND3433
    

提交回复
热议问题