获取手机的ipv4地址

直接贴代码:

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的地址。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值