Reputation: 1
I have an app with a form that when submitted it gets the ip address. Unfortunately the app gets the ip from the router like 192.168.1.4 or sometimes even 0.0.0.0
Here is the code i use
String hostaddr="";
public String getLocalIpAddress() {
WifiManager wifiMan = (WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
int ipAddress = wifiInf.getIpAddress();
String ip = String.format("%d.%d.%d.%d", (ipAddress & 0xff),(ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff));
return ip;
}
How can i get the right ip address?
Upvotes: 0
Views: 290
Reputation: 57336
You are getting the IP address assigned to your phone's network interface. If you need to get your public IP address, you have two options:
(1) somehow query the router's default gateway and recursively do so until you get the public IP address.
(2) Connect to some service on the internet, which will tell you back what IP address you connected from. There are plenty of services that do that, for example:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://icanhazip.com/");
HttpResponse resp = client.execute(get);
InputStream content = resp.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String myIP = trim(buffer.readLine());
buffer.close();
content.close();
Now variable myIP
will contain your public IP address. Of course, you'll need to add exception handling. Note that I haven't tested this code, so you may need to do some minor debugging on it.
Upvotes: 2