Method 1: Fetching Local IP Address
Java’s built-in networking libraries make it straightforward to retrieve your local IP address. Here’s a simple example:
<code>
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetLocalIPAddress {
public static void main(String[] args) {
try {
// Get the local host address
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("Local IP Address: " + localHost.getHostAddress());
} catch (UnknownHostException e) {
System.err.println("Error retrieving local IP address: " + e.getMessage());
}
}
}
</code>
This method uses InetAddress.getLocalHost() to retrieve the IP address of the local machine.
The getHostAddress() method converts it to a readable String.
Note: This gives you the local machine’s IP address, which might be 127.0.0.1 if you’re running on localhost.
Fetching Public IP Address Using api.ipquery.io
To retrieve your public IP address, you’ll need to use an external service like api.ipquery.io. This API is free and doesn’t require an API key. Java’s HTTP client makes it easy to consume REST APIs.
Here’s how you can do it:
<code>
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetPublicIPAddress {
public static void main(String[] args) {
String apiURL = "https://api.ipquery.io/";
try {
URL url = new URL(apiURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println("Public IP Address (Response): " + response.toString());
} else {
System.err.println("Error: Unable to fetch public IP. Response code: " + responseCode);
}
} catch (Exception e) {
System.err.println("Error retrieving public IP address: " + e.getMessage());
}
}
}
</code>
The URL returns your public IP address in plain text.
We use Java’s HttpURLConnection to make a GET request.
The response is read using a BufferedReader and printed to the console.
You can parse the JSON response from the API using a library like Jackson or Gson if you need specific fields like ip, city, or country.