Get the IP Address of the device - android

From inside my activity, I am trying to get the ip address of my device. I am using the following code to do this:
public static 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() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
But this function does not return me the correct ip address (possibly its returning the router ip and not the proxy ip given for my device). I went through lot of threads on StackOverflow but non of them helped.
Also, I dont plan to use :
WifiManager wifiMan = (WifiManager) this.getSystemService(this.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
int ipAddress = wifiInf.getIpAddress();
as in some cases my devices is wired connected and not wireless
Can someone suggest me how to get the correct ip address of my device from code?
Ideally, I would want that weather the device is wired/wireless connected, it should give the correct ip address of the device. In some situations, my device is wired connected.
Thanks for any help.

Related

Getting the IP Address of an Android Device using it's hotspot from another android device

I have two android enabled devices.On one device i turned on the hotspot and from other device i am connecting to that hotspot. Now i want to get the IP address of the first device. How can i get it. Because i want to send a file to the first device that's why i need the IP address of that device.I am assuming WifiManager will be used for this purpose but i don't know how. I read some other threads that are using NetworkInterface for this purpose.
-Usman
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("ServerActivity", ex.toString());
}

How do I get IP_ADDRESS in IPV4 format

I am trying to get the IP address of an device i.e using WIFI or 3G connection. I am getting the ip address in IPV6 format which is not understandable. I want in IPV4 format IP address.I have done google but dint found any proper solutions.
here is code which I am using to get IP address of an device
public String getLocalIpAddress() {
try {
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();
System.out.println("ip1--:" + inetAddress);
System.out.println("ip2--:" + inetAddress.getHostAddress());
if (!inetAddress.isLoopbackAddress()) {
String ip = inetAddress.getHostAddress().toString();
System.out.println("ip---::" + ip);
EditText tv = (EditText) findViewById(R.id.ipadd);
tv.setText(ip);
return inetAddress.getHostAddress().toString();
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
I am getting this ouput :
ip1--:/fe80::5054:ff:fe12:3456%eth0%2
ip2--:fe80::5054:ff:fe12:3456%eth0
It should be displayed like this :
192.168.1.1
please help me out..
After trying many tricks.. finally I can get the IP address in IPV4 format.. Here is my code..
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();
System.out.println("ip1--:" + inetAddress);
System.out.println("ip2--:" + inetAddress.getHostAddress());
// for getting IPV4 format
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())) {
String ip = inetAddress.getHostAddress().toString();
System.out.println("ip---::" + ip);
EditText tv = (EditText) findViewById(R.id.ipadd);
tv.setText(ip);
// return inetAddress.getHostAddress().toString();
return ip;
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
Added if condition as shown below
/**This shows IPV4 format IP address*/
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())){}
instead of this
/**This shows IPV6 format IP address*/
if (!inetAddress.isLoopbackAddress()){}
Many Thanks..
Rahul
An alternative for checking if the address is a version 4 address is:
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address)
You cannot assume that any device has just one network address. You also cannot assume that it will have any IPv4 - it may be IPv6 only, so your application will need to be able to handle both IPv4 and IPv6 address displays.
Typically, an Android phone has at least two interfaces that get assigned usable ip addresses, rmnet0 for the 3G data, which for IPv4 is often carrier-grade NATed and so cannot accept incoming socket connections, and may also have an IPv6 address; and wlan0 for the wifi, which will have whatever IPv4 and/or IPv6 address it can negotiate with the network it attaches to.
Some versions of Android will intentionally drop the (typically more expensive) rmnet0 link when it attaches to wifi - in an attempt to reduce 3G data usage. This behaviour is a problem when the wifi has attached to something that is a captive portal that requires a manual sign-in.
It seems there is a seperate class Inet4Address in the Java API for IPv4 addresses.
Following is a simple way to check either if it's IPv4 or IPv6:
InetAddress address = InetAddress.getByName(ip);
if (address instanceof Inet6Address) {
// It's ipv6
} else if (address instanceof Inet4Address) {
// It's ipv4
}

android: get IP over WIFI on ICS

I want to get the IP used by WIFI connection(not 3G). Does anybody know how to do it?
I used:
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;
}
but it returns the 3G ip on ICS.
Thanks,
Alex
You cant detect connection type based on IP address because your mobile network and home WiFi network, both can assign private IP address.
What you need to do is to first detect either you have mobile network or WiFi connection, and then based on that info get the IP address of that connection.
See this thread in SO it's the same issue as your on ICS
WifiInfo winfo = ((WifiManager)this.getSystemService(Context.WIFI_SERVICE)).getConnectionInfo();
winfo.getIpAddress();
You may want to check if you are connected to Wifi prior to doing the above

InetAddress.getLocalHost().getHostAddress() returns 127.0.0.1 in Android

My application uses multicast to send a beacon in periods along with protocol message and ip of the host joining the multicast group. In android device it is returning 127.0.0.1. I have looked around and found that many people suggested changing a host file. But, in case of android it is not possible in my context. How do I get real IP of the device, not the loopback address..
private void getLocalAddress()
{
try {
String localHost = InetAddress.getLocalHost().getHostAddress();
servers.add(localHost);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
Modified few bits and this one is working as desired for getting IPv4 addresses. !inetAddress.isLoopbackAddress() removes all the loopback address. !inetAddress.isLinkLocalAddress() and inetAddress.isSiteLocalAddress()) removes all IPv6 addresses. I hope this will help someone in here.
StringBuilder IFCONFIG=new StringBuilder();
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() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
IFCONFIG.append(inetAddress.getHostAddress().toString()+"\n");
}
}
}
} catch (SocketException ex) {
Log.e("LOG_TAG", ex.toString());
}
servers.add(IFCONFIG.toString());
Try this:-
String hostname = args[0];
try
{
InetAddress ipaddress = InetAddress.getByName(hostname);
System.out.println("IP address: " + ipaddress.getHostAddress());
}
catch ( UnknownHostException e )
{
System.out.println("Could not find IP address for: " + hostname);
}
From my tries, the maximum I could get was the wifi network address.
I don't know any other way rather than actually calling a webserver that returns the ip address. Obviously, the problem with this is that it uses the phone data.

Android Tablet IP Address

Here I am facing an issue regarding obtaining Android Tablet IP address.
I am using the following code for the tablet IP addess in a generic way.
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();
}
}
}
inetAddress.getHostAddress() method returns IP address as fe80::9a4b:4aff:fe00:a6e1 ,which is a different format rather than 122.xx.xxx.xxx
format.
When I use Wifimanager class to obtain tablet IP address it returns 122.xx.xxx.xxx in this format only.
But using the generic way I don't know why it is giving as wrong format.
Can any one please help me on this issue...
Thanks in advance.
fe80::9a4b:4aff:fe00:a6e1 is not wrong at all. It is just new-style, IPv6.
New appliactions always should be designed to be able to work in both formats.
That is an IPv6 address. Have a look at wikipedia article for a start. It may be possible to convert an IPv6 address to an IPv4 address (i.e. xxx.xxx.xxx.xxx) but it's not guaranteed.
/* look through the available network interfaces and pick the first "decent" IPv4 address.
* As the emulator uses 10.0.2.15 by default, only use it if nothing better is available. */
public String getMyIp() {
Set<String> eligible = eligibleIpAddresses();
/* For the emulator, prefer an IP address other than 10.0.2.15 (default emulator address)
* but use it if it is the only one. */
if (eligible.size() > 1) {
eligible.remove("10.0.2.15");
return eligible.iterator().next();
} else if (eligible.size() == 1) {
return eligible.iterator().next();
} else {
Log.w("Using local IP address, no external objects will be discovered","---");
return "127.0.0.1";
}
}
public static Set<String> eligibleIpAddresses() {
Set<String> eligible = new HashSet<String>();
try {
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
InetAddress addr = address.nextElement();
if (!addr.isLoopbackAddress() && !(addr.getHostAddress().indexOf(":") > -1)) {
eligible.add(addr.getHostAddress());
}
}
}
} catch (Exception e) {
}
return eligible;
}

Categories

Resources