Programming Tutorials

InetAddress get local and remote IP in Java

By: Grenfel in Java Tutorials on 2022-09-15  

Here's an example program that uses InetAddress class to retrieve and display information about the local and remote IP addresses:

import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressExample {
    public static void main(String[] args) {
        try {
            // Get the local host address
            InetAddress localAddress = InetAddress.getLocalHost();
            System.out.println("Local Host:");
            System.out.println("Host Name: " + localAddress.getHostName());
            System.out.println("IP Address: " + localAddress.getHostAddress());

            // Get the remote host address
            InetAddress remoteAddress = InetAddress.getByName("www.google.com");
            System.out.println("\nRemote Host (www.google.com):");
            System.out.println("Host Name: " + remoteAddress.getHostName());
            System.out.println("IP Address: " + remoteAddress.getHostAddress());

        } catch (UnknownHostException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Here is a sample output

Local Host:
Host Name: My-PC  
IP Address: 172.24.96.1

Remote Host (www.google.com):
Host Name: www.google.com
IP Address: 64.233.170.147

This program first retrieves the IP address of the local host using the getLocalHost() method of InetAddress. It then displays the host name and IP address of the local host using the getHostName() and getHostAddress() methods respectively.

Next, it retrieves the IP address of a remote host (in this case, www.google.com) using the getByName() method of InetAddress. It then displays the host name and IP address of the remote host using the same methods.

If the specified host is not found, the UnknownHostException is thrown, and the program prints an error message.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)