java inetaddress examples
InetAddress
is a class in the java.net
package that represents an IP address. Here are some examples of how to use InetAddress
:
- Get the IP address of the local machine:
InetAddress localAddress = InetAddress.getLocalHost(); System.out.println("Local IP address: " + localAddress.getHostAddress());Sw:ecruoww.theitroad.com
- Get the IP address of a remote host:
InetAddress remoteAddress = InetAddress.getByName("example.com"); System.out.println("Remote IP address: " + remoteAddress.getHostAddress());
- Get the host name from an IP address:
InetAddress address = InetAddress.getByName("172.217.6.78"); System.out.println("Host name: " + address.getHostName());
- Check if a host is reachable:
InetAddress address = InetAddress.getByName("example.com"); boolean reachable = address.isReachable(5000); // 5 seconds timeout System.out.println("Is reachable: " + reachable);
- Get a list of IP addresses for a host:
InetAddress[] addresses = InetAddress.getAllByName("example.com"); for (InetAddress address : addresses) { System.out.println("IP address: " + address.getHostAddress()); }
These examples show some of the basic functionality of the InetAddress
class. Note that InetAddress
also provides methods for getting the canonical host name, checking if an address is a loopback address, and comparing addresses.