Results 1 to 3 of 3
Thread: IP Address
- 08-13-2012, 09:25 PM #1
Member
- Join Date
- Jul 2012
- Posts
- 7
- Rep Power
- 0
IP Address
How would I get a users IP address?
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
System.out.println("Current IP address : " + ip.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
That returns: 127.0.0.1
I know that is not my IP. How do I get a users IP using java..?Last edited by Gorilla Logic; 08-13-2012 at 09:27 PM. Reason: Typo
- 08-13-2012, 10:58 PM #2
Member
- Join Date
- Jul 2012
- Posts
- 7
- Rep Power
- 0
Re: IP Address
Anyone?
- 08-14-2012, 12:03 AM #3
Re: IP Address
Here is how I do it.
The comments in the code will explain why each part does what it does. But what you are looking for is the user's public ip address. The first link on google after entering "gettting a user's public ip address in java" would have gotten you on the right track to figuring this out. The only reason why I do not stop there is the fact that it took some round-about method to get it done and I believe that placing some sample code on this thread will not do any harm.
hope this helps!Java Code:import java.net.*; import java.io.*; public class PublicIP { public static void main(String[] args) { try { /** Basic URL object. * The actual URL (try it out in your browser) is an automated page that * quickly prints the usre who accessed the website's IP address. * It was ment for programmers. * Check out this page to see what the terms of use are for this page: * http://www.whatismyip.com/faq/automation.asp */ URL getPublicIP = new URL("http://automation.whatismyip.com/n09230945.asp"); //You will need URLConnection for this. URLConnection c = getPublicIP.openConnection(); /** VERY IMPORTANT. * If you read the terms, you would have seen that you cannot parse the page without having a user-agent, * such as the one that I have set below. You will get a 403 FORBIDDEN reply from the server otherwise. */ c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0"); //BufferReader to read input. BufferedReader in = new BufferedReader(new InputStreamReader( c.getInputStream())); //the site is in plain text so you do not have to worry about html tags. String inputLine = in.readLine(); System.out.println(inputLine); // alwasy close your connections :) in.close(); } catch (IOException e) { System.out.println("IOException Alert: "+e.getMessage()); } } }My API:Java Code:cat > a.out || cat > main.class
Similar Threads
-
One row help with Locking Java to MAC Adress
By Darkbound in forum New To JavaReplies: 1Last Post: 04-28-2011, 07:42 PM -
Get Ip adress?
By Godsent in forum NetworkingReplies: 2Last Post: 07-11-2009, 02:15 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks