Android obtains the IP address of a mobile device.

Source: Internet
Author: User

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>

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.