Home > Java > javaTutorial > How Can I Get My Machine\'s External IP Address in Java?

How Can I Get My Machine\'s External IP Address in Java?

DDD
Release: 2024-11-27 09:25:10
Original
1063 people have browsed it

How Can I Get My Machine's External IP Address in Java?

Determining the External IP Address in Java

In this inquiry, the objective is to retrieve the external IP address of a machine as it would appear to a computer outside the network. The provided IPAddress class only retrieves the local IP address, prompting the need for an alternative solution.

Solution Through External Services

Unfortunately, obtaining the external IP address from code running on the local machine may not be possible. However, we can utilize code running on a website and employ methods that reveal the IP address from which the request originates:

  • request.getRemoteAddr(): This method, when implemented in JSP, returns the IP address of the source of the request.
  • Third-Party Services: There are readily available services that provide this information. We can parse the response from these services to extract the external IP address.

Example Using AWS Service

import java.net.*;
import java.io.*;

URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));

String ip = in.readLine(); // Extract the IP address as a string
System.out.println(ip);
Copy after login

The above is the detailed content of How Can I Get My Machine\'s External IP Address in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template