Java InetAddress Tutorial 🎯

beginner
7 min

Java InetAddress Tutorial 🎯

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!

Understanding InetAddress 📝

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.

Getting an InetAddress 💡

There are multiple ways to get an InetAddress object. Here, we'll focus on two methods: getLocalHost() and getByName().

1. Getting Local Host Address 💡

To get the IP address of your local machine, use the getLocalHost() method:

java
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.

2. Getting an IP Address by Hostname 💡

To get the IP address of a host (like google.com), use the getByName() method:

java
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.

InetAddress Types 📝

Java's InetAddress can handle both IPv4 and IPv6 addresses. You can check the address type using the getAddressType() method:

java
int addressType = localAddress.getAddressType(); System.out.println("Address type: " + addressType);

Quiz 💡

Quick Quiz
Question 1 of 1

What method is used to get the local machine's IP address?

Wrapping Up 🎯

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! 🚀