Android obtains the IP address of the device.

Source: Internet
Author: User

Android obtains the IP address of the device.

Overall retrieval: You can use mobile data to access the Internet and obtain IP addresses. You can also use WiFi to obtain IP addresses.

public static String getPhoneIp() {     try {         for (Enumeration
 
   en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {             NetworkInterface intf = en.nextElement();             for (Enumeration
  
    enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {                 InetAddress inetAddress = enumIpAddr.nextElement();                 if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {                     // if (!inetAddress.isLoopbackAddress() && inetAddress                     // instanceof Inet6Address) {                     return inetAddress.getHostAddress().toString();                 }             }         }     } catch (Exception e) {     }     return "127.0.0.1"; }
  
 

How to obtain IP addresses through Wifi

Private String intToIp (int ip) {return (ip & 0xFF) + ". "+ (ip> 8) & 0xFF) + ". "+ (ip> 16) & 0xFF) + ". "+ (ip> 24) & 0xFF);} private String getIp () {// get wifi service WifiManager wifiManager = (WifiManager) getSystemService (Context. WIFI_SERVICE); // determines whether wifi is enabled if (wifiManager. isWifiEnabled () {// wifiManager. setWifiEnabled (true); WifiInfo wifiInfo = wifiManager. getConnectionInfo (); int ipAddress = wifiInfo. getIpAddress (); return intToIp (ipAddress);} return "127.0.0.1 ";}


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.