【问题标题】:get ip address from android in java i got some error在java中从android获取IP地址我遇到了一些错误
【发布时间】:2015-02-02 07:59:21
【问题描述】:

我试图在android中获取IP地址,但结果是这样的! 我想获取我的 wifi 范围的 IP 地址!我该怎么做?

 private String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress())
                {

                    return inetAddress.getHostAddress().toString();

                }
            }
        }
    } catch (SocketException ex) {
        Log.e("ServerActivity", ex.toString());
    }
    return null;
}

结果是这样的:fe80::38aa:3cff:feb3:1cef%p2p0 我也在 android mainfast 中添加了权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

【问题讨论】:

标签: java android


【解决方案1】:
Here You Will get All Details of Your Device !!!  

    //Main Classs 

         package com.example.devicedetail;

                import android.annotation.SuppressLint;
            import android.app.Activity;
            import android.content.Context;
            import android.os.Bundle;
            import android.telephony.TelephonyManager;
            import android.view.Menu;

            public class Device extends Activity {
            @SuppressLint("NewApi")
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_device);

                    String debug2 = System.getProperty("os.version");
                    String debug3 = android.os.Build.VERSION.RELEASE;
                    String debug4 = android.os.Build.DEVICE;
                    String debug5 = android.os.Build.MODEL;
                    String debug6 = android.os.Build.PRODUCT;
                    String debug7 = android.os.Build.BRAND;
                    String debug8 = android.os.Build.DISPLAY;
                    String debug9 = android.os.Build.CPU_ABI;
                    String debug10 = android.os.Build.CPU_ABI2;
                    String debug11 = android.os.Build.UNKNOWN;
                    String debug12 = android.os.Build.HARDWARE;
                    String debug13 = android.os.Build.ID;
                    String debug14 = android.os.Build.MANUFACTURER;
                    String debug15 = android.os.Build.SERIAL;
                    String debug16 = android.os.Build.USER;
                    String debug17 = android.os.Build.HOST;

                    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                    String imei = telephonyManager.getDeviceId();
                    String macwlan = Utils.getMACAddress("wlan0");
                    String macethr = Utils.getMACAddress("eth0");
                    String ip4 = Utils.getIPAddress(true); // IPv4
                    String ip36 = Utils.getIPAddress(true); // IPv6

                }

                @Override
                public boolean onCreateOptionsMenu(Menu menu) {
                    // Inflate the menu; this adds items to the action bar if it is present.
                    getMenuInflater().inflate(R.menu.activity_device, menu);
                    return true;
                }

            }



    ----------




        //Util Class

        package com.example.devicedetail;

        import android.annotation.SuppressLint;
        import java.io.*;
        import java.net.*;
        import java.util.*;   
        import org.apache.http.conn.util.InetAddressUtils;

        public class Utils {

            /**
             * Convert byte array to hex string
             * @param bytes
             * @return
             */
            public static String bytesToHex(byte[] bytes) {
                StringBuilder sbuf = new StringBuilder();
                for(int idx=0; idx < bytes.length; idx++) {
                    int intVal = bytes[idx] & 0xff;
                    if (intVal < 0x10) sbuf.append("0");
                    sbuf.append(Integer.toHexString(intVal).toUpperCase());
                }
                return sbuf.toString();
            }

            /**
             * Get utf8 byte array.
             * @param str
             * @return  array of NULL if error was found
             */
            public static byte[] getUTF8Bytes(String str) {
                try { return str.getBytes("UTF-8"); } catch (Exception ex) { return null; }
            }

            /**
             * Load UTF8withBOM or any ansi text file.
             * @param filename
             * @return  
             * @throws java.io.IOException
             */
            public static String loadFileAsString(String filename) throws java.io.IOException {
                final int BUFLEN=1024;
                BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN);
                try {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN);
                    byte[] bytes = new byte[BUFLEN];
                    boolean isUTF8=false;
                    int read,count=0;           
                    while((read=is.read(bytes)) != -1) {
                        if (count==0 && bytes[0]==(byte)0xEF && bytes[1]==(byte)0xBB && bytes[2]==(byte)0xBF ) {
                            isUTF8=true;
                            baos.write(bytes, 3, read-3); // drop UTF8 bom marker
                        } else {
                            baos.write(bytes, 0, read);
                        }
                        count+=read;
                    }
                    return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
                } finally {
                    try{ is.close(); } catch(Exception ex){} 
                }
            }

            /**
             * Returns MAC address of the given interface name.
             * @param interfaceName eth0, wlan0 or NULL=use first interface 
             * @return  mac address or empty string
             */
            @SuppressLint("NewApi")
            public static String getMACAddress(String interfaceName) {
                try {
                    List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
                    for (NetworkInterface intf : interfaces) {
                        if (interfaceName != null) {
                            if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
                        }
                        byte[] mac = intf.getHardwareAddress();
                        if (mac==null) return "";
                        StringBuilder buf = new StringBuilder();
                        for (int idx=0; idx<mac.length; idx++)
                            buf.append(String.format("%02X:", mac[idx]));       
                        if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
                        return buf.toString();
                    }
                } catch (Exception ex) { } // for now eat exceptions
                return "";
                /*try {
                    // this is so Linux hack
                    return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim();
                } catch (IOException ex) {
                    return null;
                }*/
            }

            /**
             * Get IP address from first non-localhost interface
             * @param ipv4  true=return ipv4, false=return ipv6
             * @return  address or empty string
             */
            public static String getIPAddress(boolean useIPv4) {
                try {
                    List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
                    for (NetworkInterface intf : interfaces) {
                        List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                        for (InetAddress addr : addrs) {
                            if (!addr.isLoopbackAddress()) {
                                String sAddr = addr.getHostAddress().toUpperCase();
                                boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); 
                                if (useIPv4) {
                                    if (isIPv4) 
                                        return sAddr;
                                } else {
                                    if (!isIPv4) {
                                        int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                                        return delim<0 ? sAddr : sAddr.substring(0, delim);
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception ex) { } // for now eat exceptions
                return "";
            }

        }



    ----------



        //PerMissions

        <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

【讨论】:

    【解决方案2】:

    答案没有错。如果您想将其作为ipv4 获取,这是ipv6 地址。你可以试试关注

     inetAddress.getLocalHost().getHostAddress();
    

    【讨论】:

    • 我的应用在我使用的时候会崩溃!!
    【解决方案3】:

    这就是我通过点击在设备的 IP 之间进行更改的方式,您可能需要使其适合您的喜好。仅限本地 IP,而非外部 IP。

    <uses-permission android:name="android.permission.INTERNET" />
    
    private Enumeration<NetworkInterface> networkInterfaces = null;
    private Enumeration<InetAddress> networkAddresses = null;
    
    ...
        if(wb == this.ipDisplayButton)
        {
            try
            {
                while(true)
                {
                    if(this.networkInterfaces == null)
                    {
                        networkInterfaces = NetworkInterface.getNetworkInterfaces();
                    }
                    if(networkAddresses == null || !networkAddresses.hasMoreElements())
                    {
                        if(networkInterfaces.hasMoreElements())
                        {
                            NetworkInterface networkInterface = networkInterfaces.nextElement();
                            networkAddresses = networkInterface.getInetAddresses();
                        }
                        else
                        {
                            networkInterfaces = null;
                        }
                    }
                    else
                    {
                        if(networkAddresses.hasMoreElements())
                        {
                            String address = networkAddresses.nextElement().getHostAddress();
                            if(address.contains(".")) //IPv4
                            {
                                ipDisplay.setText("IP Address: " + address);
                            }
                            break;
                        }
                        else
                        {
                            networkAddresses = null;
                        }
                    }
                }
            }
            catch(SocketException e)
            {
                e.printStackTrace();
            }
        }
    

    【讨论】:

      【解决方案4】:

      我用这个

      try{
                  WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
                  int ipAddress = wm.getDhcpInfo().ipAddress;
                  byte[] ipAddressbyte = BigInteger.valueOf(ipAddress).toByteArray();
                  for(int i = 0; i < ipAddressbyte.length / 2; i++){
                      int temp = ipAddressbyte[i];
                      ipAddressbyte[i] = ipAddressbyte[ipAddressbyte.length - i - 1];
                      ipAddressbyte[ipAddressbyte.length - i - 1] = (byte) temp;
      
                  }
      
                  InetAddress myaddr = InetAddress.getByAddress(ipAddressbyte);
                  String hostaddr = myaddr.getHostAddress(); // numeric representation (such as "127.0.0.1")
                  Log.d("INET",hostaddr);
              }catch (Exception e){
                  Log.d("Exception",e.getMessage());
              }
      

      【讨论】:

      • formatIpAddress 无法识别!!你能告诉我那是什么吗?
      • 我编辑了答案,因为你的 ip 地址可能是 ipv6
      • 我刚刚测试了我的答案中的代码,我得到了正确的 IP。可以试试吗?
      • 我测试了我的应用崩溃!!我不知道是什么原因!
      猜你喜欢
      • 2016-06-21
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 2011-03-14
      相关资源
      最近更新 更多