mainactivity:
Package CN. testip; import java.net. inetaddress; import java.net. networkinterface; import java.net. socketexception; import Java. util. enumeration; import android. OS. bundle; import android. app. activity;/*** demo Description: * get the IP address of a mobile device */public class mainactivity extends activity {@ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); string I P = getip (); system. out. println ("the IP of this handset is:" + IP);} private string getip () {string IP = NULL; stringbuilder ipstringbuilder = new stringbuilder (); try {enumeration <networkinterface> networkinterfaceenumeration = networkinterface. getnetworkinterfaces (); While (networkinterfaceenumeration. hasmoreelements () {networkinterface = networkinterfaceenumeration. nextelement (); Enum Eration <inetaddress> inetaddressenumeration = networkinterface. getinetaddresses (); While (inetaddressenumeration. hasmoreelements () {inetaddress = inetaddressenumeration. nextelement (); If (! Inetaddress. isloopbackaddress ()&&! Inetaddress. islinklocaladdress () & inetaddress. issitelocaladdress () {ipstringbuilder. append (inetaddress. gethostaddress (). tostring () + "\ n") ;}}} catch (socketexception ex) {} IP = ipstringbuilder. tostring (); Return IP ;}}
Main. XML is as follows:
<Relativelayout xmlns: Android = "http://schemas.android.com/apk/res/android" xmlns: Tools = "http://schemas.android.com/tools" Android: layout_width = "match_parent" Android: layout_height = "match_parent"> <textview Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: text = "Get device IP" Android: layout_centerinparent = "true" Android: textsize = "28sp"/> </relativelayout>