I am working on a VERY SIMPLE chat client and server and I need to have a message on the server like this : (“IP: ” + ipAddr)
My problem is when trying to get the ipAddr of the server.
I want it to work exactly like “curl ifconfig.me” in the Terminal on Mac.
If I do curl ifconfig.me on my computer it will return : 76.xx.xxx.xxx
Parts hidden to protect myself.
I need my program to return this.
Currently with this code :
try {
InetAddress thisIp = InetAddress.getLocalHost();
System.err.println("IP: "+ thisIp.getHostAddress());
}
catch(Exception e) {
System.err.println("Error!");
}
}
It will return 127.0.0.1, The localhost IP addr. Can anyone help me with figuring out a program to do this?
Thanks!
ifconfig.me is a website, so when you curl it you are getting an external website telling you what it sees as you IP address. this information is not available inside the JVM (or really the computer) you need to request your ipaddress from something outside of your network to see your public ip address.
Now if you want to fetch the content of a website in Java you can do this:
note that this (updated) example will simulate exactly what cURL sends to the ifconfig.me site, so you will get the expected response. If you don’t send a User-Agent that looks like cURL then ifconfig.me will just send you the full HTML document that it sends to a web browser
Now this code uses the HttpComponents and IOUtils.toString() from Apache Commons IO. These projects will help make your chat client and server even simpler.