http://blog.csdn.net/yueqinglkong/article/details/17391051
直接贴代码:
- public class GetLocalIpAddress extends Activity implements OnClickListener {
- private TextView iplocal;
- private Button click;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.acy_showipaddress);
- init();
- }
- public void init() {
- iplocal = (TextView) findViewById(R.id.tv_ipaddress);
- click = (Button) findViewById(R.id.btn_click);
- click.setOnClickListener(this);
- }
- public String GetIp() {
- try {
- for (Enumeration<NetworkInterface> en = NetworkInterface
- .getNetworkInterfaces(); en.hasMoreElements();) {
- NetworkInterface intf = en.nextElement();
- for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr
- .hasMoreElements();) {
- InetAddress inetAddress = ipAddr.nextElement();
- // ipv4地址
- if (!inetAddress.isLoopbackAddress()
- && InetAddressUtils.isIPv4Address(inetAddress
- .getHostAddress())) {
- return inetAddress.getHostAddress();
- }
- }
- }
- } catch (Exception ex) {
- }
- return "";
- }
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- if (v == click) {
- iplocal.setText(GetIp().toString());
- }
- }
- }
界面是添加的一个button和textview ,就不给xml了。
注意:
1.获取的地址分ipv4和ipv6地址,你需要加个判断获取ipv4的地址。