2014-02-14 13 views
0

我想这代码 公共类MainActivity扩展活动{越来越格式化自己的设备的IP地址的Android

private static final String TAG = null; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    TextView tv= (TextView) findViewById(R.id.textView2); 
    String a=getLocalIpAddress(); 
     tv.setText(a); 

} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 
public 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()) { 
        String a= inetAddress.getHostAddress(); 

        return a; 
        } 
       } 
      } 
     } catch (SocketException ex) { 
      // Log.e(tag, ex.toString()); 
     } 
     return ""; 
    } 
} 

这给了我IP地址就像00FF:22ff:.... ,但我希望它像192.168 .3.3 ... 格式的IP地址是贬值的 是否有任何其他方法,以便我可以得到格式的地址

+0

你得到一个物理MAC地址,而不是IP地址。 –

+0

你有没有看过在这里的任何十几个相同的问题的答案? – 323go

+1

@CiaranBaselmans,不,他正在获取IPv6地址。 – 323go

回答

-1

您得到的地址是IPv6的。你正在试图获得是IPv4,所以请尝试使用:

if ((!inetAddress.isLoopbackAddress()) && (InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress()))) { ... } 

相反的:

if (!inetAddress.isLoopbackAddress()) { ... } 
+0

它的工作thanku :) – user3297438

+0

然后请接受这个问题,无论是为了声誉,但总体而言,为了让其他用户有同样的问题知道这个解决方案为你工作。 – nKn

+0

请不要回答已经回答的问题 - 尤其是不止一次。此外,您的答案只是部分,而新进程只会找到不是回送的* first * ip4地址。在具有多个接口(即WiFi和4G)的设备上,这可能不会返回活动连接。 – 323go