I want to know the whether IP address of an Android device is Data IP or Wifi IP.
1) Device as is connected to 3G first, now the Device will be assigned to Netwo
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.
Try this code
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.Toast;
import com.blundell.tut.R;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkAvailableConnection();
}
void checkAvailableConnection() {
ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) {
WifiManager myWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
int ipAddress = myWifiInfo.getIpAddress();
System.out.println("WiFi address is "
+ android.text.format.Formatter.formatIpAddress(ipAddress));
} else if (mobile.isAvailable()) {
GetLocalIpAddress();
Toast.makeText(this, "3G Available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "No Network Available", Toast.LENGTH_LONG)
.show();
}
}
private 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) {
return "ERROR Obtaining IP";
}
return "No IP Available";
}
}
Found the trick.. http://developer.android.com/reference/java/net/NetworkInterface.html#getName()
getName for WiFi will start with wlan..using this validate WiFi IP.