Method in java to get the Ip address of the current server

  • 2020-06-03 06:41:33
  • OfStack

1. tomcat is a free open source Web server. If deployed locally, the corresponding server is localhost and the corresponding address is

Example: This can be accessed via the http://localhost:8080/ project root value or via the project root value.

If you deploy to a server (linux) system class, you need to access it through the server's Ip address.

2. Here's how to get the Ip address:

Get the local Ip address:

public static void main(String[] args) {
    try {
       InetAddress address = InetAddress.getLocalHost();// The fetch is local IP address  //PC-20140317PXKX/
       String hostAddress = address.getHostAddress());//      
       InetAddress address1 = InetAddress.getByName("");// Access is for the website ip Address, like all of our requests go through nginx So what we're getting here is actually theta nginx The server's IP to  
       String hostAddress1 = address1.getHostAddress());// 
       InetAddress[] addresses = InetAddress.getAllByName("");// Returns all of its possible values based on the host name InetAddress object  
       for(InetAddress addr:addresses){ 
    } catch (UnknownHostException e) { 

Get the Ip address of the server (written by someone else)

   *  Fetch server IP address 
   * @return
  public static String getServerIp(){
    String SERVER_IP = null;
    try {
      Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
      InetAddress ip = null;
      while (netInterfaces.hasMoreElements()) {
        NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
        ip = (InetAddress) ni.getInetAddresses().nextElement();
        SERVER_IP = ip.getHostAddress();
        if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
            && ip.getHostAddress().indexOf(":") == -1) {
          SERVER_IP = ip.getHostAddress();
        } else {
          ip = null;
    } catch (SocketException e) {
      // TODO Auto-generated catch block
    return SERVER_IP;

The farming log in the agricultural Internet of Things intelligent farming system based on SSM framework requires 1 picture to be uploaded to the server. When testing locally, because the saved path was on the local disk E, the background got the resource file directly from the local. When passed into the server hu, the file could not be found. It is estimated that the IP address could not be obtained, but only the corresponding file path. Based on this, we tried to design to read the file information from the server, but failed. Later, it was found that localhost and were 1, which reminded me to use the server IP address instead of localhost to complete the reading operation, but the essence was still the reading of the foreground interface.

Related articles: