Q:-Now a days I am facing problem in getting IP address of android device using programming. Can any one give ma a code for solving that problem. I have already read lot of thread about it but not getting solid answer from that. Please give me any suggesting about it its appreciated. Thanks in advance.
Asked
Active
Viewed 7,648 times
3
-
Depends on what you mean by host IP; 1. IP address of the network interfaces? 2. External public IP address? – dacwe Jun 14 '12 at 10:20
-
i want to get public IP address – Amit kumar Jun 14 '12 at 10:27
2 Answers
4
The problem is that you cannot know if your current in use network device is really has a public IP. You could however check if this is the case but you need to contact a external server.
In this case we can use www.whatismyip.com to check (almost copied from another SO question):
public static InetAddress getExternalIp() throws IOException {
URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
URLConnection connection = url.openConnection();
connection.addRequestProperty("Protocol", "Http/1.1");
connection.addRequestProperty("Connection", "keep-alive");
connection.addRequestProperty("Keep-Alive", "1000");
connection.addRequestProperty("User-Agent", "Web-Agent");
Scanner s = new Scanner(connection.getInputStream());
try {
return InetAddress.getByName(s.nextLine());
} finally {
s.close();
}
}
To check that this ip is bound to one of your network interfaces:
public static boolean isIpBoundToNetworkInterface(InetAddress ip) {
try {
Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();
while (nets.hasMoreElements()) {
NetworkInterface intf = nets.nextElement();
Enumeration<InetAddress> ips = intf.getInetAddresses();
while (ips.hasMoreElements())
if (ip.equals(ips.nextElement()))
return true;
}
} catch (SocketException e) {
// ignore
}
return false;
}
Test code:
public static void main(String[] args) throws IOException {
InetAddress ip = getExternalIp();
if (!isIpBoundToNetworkInterface(ip))
throw new IOException("Could not find external ip");
System.out.println(ip);
}
2
For wifi:
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
Or a more complex solution:
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}

Thkru
- 4,218
- 2
- 18
- 37