3

Possible Duplicate:
how to get users ip address in java
Get IP address with URL string? (Java)

link is :

"http://automation.whatismyip.com/n09230945.asp"

the above link return External IP.

I try to make my own code to get my IP like above link

my code is

String my_own_ip =InetAddress.getLocalHost().getHostAddress();

so how to get this IP

in this code return my internal IP

I am in LAN Connection my LAN IP is 192.168.0.109

and external IP is 27.54.180.156

I want 27.54.180.156

Thanks in Advance

Community
  • 1
  • 1
Hardik Lotiya
  • 371
  • 3
  • 9
  • 28

3 Answers3

3

Don't use getLocalHost() - that will return your local host.

InetAddrsss addy = InetAddress.getByName("www.stackoverflow.com");
System.out.println(addy.getHostAddress());

Note that you'll want to omit the protocol, http://:

InetAddrsss addy = InetAddress.getByName("http://www.stackoverflow.com"); // throws an exception
System.out.println(addy.getHostAddress());

... and equally the path:

InetAddrsss addy = InetAddress.getByName("www.stackoverflow.com/questions"); // throws an exception
System.out.println(addy.getHostAddress());
Richard JP Le Guen
  • 28,364
  • 7
  • 89
  • 119
1

The problem is that you assume your computer has access to the external IP address when, in fact, it does not. Only the router and outside connections have access to the IP address.

That being said, your best option is to use a website like http://icanhazip.com or http://checkip.dyndns.org (or the one you supplied, for that matter, http://automation.whatismyip.com/n09230945.asp) and connect to it using an HTTP Get on your Java client, like in this question or this question. Once you get the HTML page back, parse it to find the IP address. This can be done using regex since these are very simple HTML pages that don't require extensive DOM parsing:

String html = ... ;
Pattern pattern = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3}");
Matcher matcher = pattern.matcher(html);
matcher.find();
String ip = matcher.group(0);

The trick is finding a website with a free API that you can call as many times as you want. The two I listed above don't have any limits as far as I know.

Community
  • 1
  • 1
Brian
  • 17,079
  • 6
  • 43
  • 66
-1

You can simply use the bit of code in a jsp page and print it into the body of the document.

<%@page import="java.net.InetAddress" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <% String my_own_ip =InetAddress.getLocalHost().getHostAddress();%>
    <%=my_own_ip%>
</body>
</html>