This method passed the Motorola milestone test. This function is used to obtain the IP address and MAC address of the local machine. First, create a project and modify the androidmanifest. xml file to add user permissions, as shown below.
<Uses-Permission Android: Name = "android. permission. access_wifi_state "> </uses-Permission> <br/> <uses-Permission Android: Name =" android. permission. internet "> </uses-Permission>
Modify/RES/layout/Main. XML as follows.
<Textview <br/> Android: Id = "@ + ID/Hello" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/>
The main code is as follows (getipmac. Java ):
Package exp. getipmac; <br/> Import java.net. inetaddress; <br/> Import java.net. networkinterface; <br/> Import java.net. socketexception; <br/> Import Java. util. enumeration; <br/> Import android. app. activity; <br/> Import android. content. context; <br/> Import android.net. wiFi. wifiinfo; <br/> Import android.net. wiFi. wifimanager; <br/> Import android. OS. bundle; <br/> Import android. util. log; <br/> Import android. Widget. textview; <br/> public class getipmac extends activity {<br/> Public static string hostip; // local IP address <br/> Public static string hostmac; // local Mac </P> <p>/** called when the activity is first created. */<br/> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. main); <br/> textview TV = (textview) findviewbyid (R. I D. hello); </P> <p> hostip = getlocalipaddress (); // obtain the local IP address <br/> hostmac = getlocalmacaddress (); // obtain the MAC address of the Local Machine <br/>/* display the IP address and MAC address of the Local Machine */<br/> TV. settext ("hostip:" + hostip + "/nhostmac:" + hostmac ); <br/>/* output the local IP address and MAC address in the debugging information */<br/> If (hostip! = NULL) log. D ("getipmac", hostip); <br/> else log. D ("getipmac", "null"); <br/> log. D ("getipmac", hostmac); <br/>}</P> <p> Public String getlocalipaddress () {<br/> try {<br/> for (enumeration <networkinterface> en = networkinterface <br/>. getnetworkinterfaces (); en. hasmoreelements ();) {<br/> networkinterface INTF = en. nextelement (); <br/> for (enumeration <inetaddress> enumipaddr = INTF <br/>. getinetad Dresses (); enumipaddr. hasmoreelements ();) {<br/> inetaddress = enumipaddr. nextelement (); <br/> If (! Inetaddress. isloopbackaddress () {<br/> return inetaddress. gethostaddress (). tostring (); <br/>}< br/>}catch (socketexception ex) {<br/> log. E ("wifipreference IPaddress", Ex. tostring (); <br/>}< br/> return NULL; <br/>}</P> <p> Public String getlocalmacaddress () {<br/> wifimanager WiFi = (wifimanager) getsystemservice (context. wifi_service); <br/> wifiinfo info = wifi. getconnectioninfo (); <br/> return info. getmacaddress (); <br/>}< br/>}
Running effect: