【转】获取手机的ipv4地址

http://blog.csdn.net/yueqinglkong/article/details/17391051

直接贴代码:

[java] view plain copy
 
 print?在CODE上查看代码片派生到我的代码片
  1. public class GetLocalIpAddress extends Activity implements OnClickListener {  
  2.   
  3.     private TextView iplocal;  
  4.     private Button click;  
  5.   
  6.     @Override  
  7.     protected void onCreate(Bundle savedInstanceState) {  
  8.         // TODO Auto-generated method stub  
  9.         super.onCreate(savedInstanceState);  
  10.         setContentView(R.layout.acy_showipaddress);  
  11.         init();  
  12.     }  
  13.   
  14.     public void init() {  
  15.         iplocal = (TextView) findViewById(R.id.tv_ipaddress);  
  16.         click = (Button) findViewById(R.id.btn_click);  
  17.         click.setOnClickListener(this);  
  18.     }  
  19.   
  20.     public String GetIp() {  
  21.         try {  
  22.   
  23.             for (Enumeration<NetworkInterface> en = NetworkInterface  
  24.   
  25.             .getNetworkInterfaces(); en.hasMoreElements();) {  
  26.   
  27.                 NetworkInterface intf = en.nextElement();  
  28.   
  29.                 for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr  
  30.   
  31.                 .hasMoreElements();) {  
  32.   
  33.                     InetAddress inetAddress = ipAddr.nextElement();  
  34.                     // ipv4地址  
  35.                     if (!inetAddress.isLoopbackAddress()  
  36.                             && InetAddressUtils.isIPv4Address(inetAddress  
  37.                                     .getHostAddress())) {  
  38.   
  39.                         return inetAddress.getHostAddress();  
  40.   
  41.                     }  
  42.   
  43.                 }  
  44.   
  45.             }  
  46.   
  47.         } catch (Exception ex) {  
  48.   
  49.         }  
  50.   
  51.         return "";  
  52.   
  53.     }  
  54.   
  55.     @Override  
  56.     public void onClick(View v) {  
  57.         // TODO Auto-generated method stub  
  58.         if (v == click) {  
  59.             iplocal.setText(GetIp().toString());  
  60.         }  
  61.     }  
  62. }  


界面是添加的一个button和textview ,就不给xml了。

注意:

1.获取的地址分ipv4和ipv6地址,你需要加个判断获取ipv4的地址。

原文地址:https://www.cnblogs.com/exmyth/p/5474134.html