networking - Getting IP address of Android when connected to Cellular Network -
is there simple way ip address of phone when connected internet through mobile data network. getting wifi ip address using following simple technique.
wifimanager wm = (wifimanager) getsystemservice(wifi_service); string ip = formatter.formatipaddress(wm.getconnectioninfo().getipaddress());
is there way similar above ip address of mobile data network.
i have used following code returns mac addresses ,ip addresses of both wifi , cellular network interested in cellular ip address.
string ipaddress = null; try { (enumeration<networkinterface> en = networkinterface.getnetworkinterfaces(); en.hasmoreelements();) { networkinterface intf = en.nextelement(); (enumeration<inetaddress> enumipaddr = intf.getinetaddresses(); enumipaddr.hasmoreelements();) { inetaddress inetaddress = enumipaddr.nextelement(); if (!inetaddress.isloopbackaddress()) { ipaddress = inetaddress.gethostaddress().tostring(); log.i("sarao5",ipaddress); } } } } catch (socketexception ex) {}
use below code use in app -
public static string getdeviceipaddress(boolean useipv4) { try { list<networkinterface> networkinterfaces = collections.list(networkinterface.getnetworkinterfaces()); (networkinterface networkinterface : networkinterfaces) { list<inetaddress> inetaddresses = collections.list(networkinterface.getinetaddresses()); (inetaddress inetaddress : inetaddresses) { if (!inetaddress.isloopbackaddress()) { string saddr = inetaddress.gethostaddress().touppercase(); boolean isipv4 = inetaddressutils.isipv4address(saddr); if (useipv4) { if (isipv4) return saddr; } else { if (!isipv4) { // drop ip6 port suffix int delim = saddr.indexof('%'); return delim < 0 ? saddr : saddr.substring(0, delim); } } } } } } catch (exception ex) { ex.printstacktrace(); } return ""; }
this best , easy way.
hope answer helpfull.
Comments
Post a Comment