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; } }
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With