Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the 'external' IP address in Java

I'm not too sure how to go about getting the external IP address of the machine as a computer outside of a network would see it.

My following IPAddress class only gets the local IP address of the machine.

public class IPAddress {      private InetAddress thisIp;      private String thisIpAddress;      private void setIpAdd() {         try {             InetAddress thisIp = InetAddress.getLocalHost();             thisIpAddress = thisIp.getHostAddress().toString();         } catch (Exception e) {         }     }      protected String getIpAddress() {         setIpAdd();         return thisIpAddress;     } } 
like image 894
Julio Avatar asked May 30 '10 15:05

Julio


People also ask

How do I find external source IP address?

Type "ipconfig" in the command prompt window and take note of the IP address displayed. If you have multiple network ports in use, like an Ethernet port and a Wi-Fi adaptor, you may see more than one. On a macOS or Linux system, you can use the similarly named "ifconfig" command line tool for the same purpose.

How do I find my Java IP address?

In Java, you can use InetAddress. getLocalHost() to get the Ip Address of the current Server running the Java app and InetAddress. getHostName() to get Hostname of the current Server name.

How do I find internal and external IP address?

Here are the instructions for windows:Type cmd and press enter. In this new windows type ipconfig and press enter. You will see a bit more information than you may want what your looking for is IPv4 Address. The number across from that is your local IP address.

What is an IP address in Java?

An IP address is either a 32-bit or 128-bit unsigned number used by IP, a lower-level protocol on which protocols like UDP and TCP are built. In Java, the InetAddress class represents an Internet Protocol (IP) address.


1 Answers

I am not sure if you can grab that IP from code that runs on the local machine.

You can however build code that runs on a website, say in JSP, and then use something that returns the IP of where the request came from:

request.getRemoteAddr()

Or simply use already-existing services that do this, then parse the answer from the service to find out the IP.

Use a webservice like AWS and others

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); 
like image 142
bakkal Avatar answered Sep 23 '22 14:09

bakkal