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

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

Mary-Kate Olsen
Release: 2024-11-28 21:03:15
Original
544 people have browsed it

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

Getting the Machine's External IP Address in Java

Locating a machine's external IP address, as viewed by devices outside its network, can be a challenge in Java. The provided IpAddress class only fetches the local IP address. To obtain the external IP, consider the following solutions:

External Services

It may not be feasible to retrieve the external IP from code running on the local machine. Instead, you can:

  • Use a website with a service that returns the IP address: This involves creating code that accesses the website (e.g., using JSP) and parsing the returned information to extract the IP address.
  • Utilize existing websites or services: These services provide the external IP when queried. You can then parse the response to obtain the desired information.

Web Services

One effective method involves employing web services like AWS:

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(); //you get the IP as a String
System.out.println(ip);
Copy after login

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

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template