Welcome to our comprehensive Java InetAddress tutorial! In this lesson, we'll explore the InetAddress class, which is a fundamental tool for working with Internet protocol (IP) addresses and domain names in Java. Let's dive in!
The InetAddress class is used to convert a hostname (like google.com) or an IP address (like 192.168.1.1) into a Java object. This object can then be used for various network operations.
There are multiple ways to get an InetAddress object. Here, we'll focus on two methods: getLocalHost() and getByName().
To get the IP address of your local machine, use the getLocalHost() method:
InetAddress localAddress = InetAddress.getLocalHost();
System.out.println("Local IP Address: " + localAddress.getHostAddress());Run this code, and you'll see the IP address of your local machine printed on the console.
To get the IP address of a host (like google.com), use the getByName() method:
InetAddress googleAddress;
try {
googleAddress = InetAddress.getByName("google.com");
System.out.println("Google IP Address: " + googleAddress.getHostAddress());
} catch (UnknownHostException e) {
System.err.println("Error looking up Google's IP address: " + e.getMessage());
}This code tries to get the IP address of google.com. If the hostname is unknown, the program will print an error message.
Java's InetAddress can handle both IPv4 and IPv6 addresses. You can check the address type using the getAddressType() method:
int addressType = localAddress.getAddressType();
System.out.println("Address type: " + addressType);What method is used to get the local machine's IP address?
In this lesson, we've explored the basics of Java's InetAddress class, learning how to get the IP address of the local machine and a remote host. We also looked at the address types supported by InetAddress.
Stay tuned for more tutorials on Java networking, and happy coding! 🚀