您的位置:首页 > 其它

【转】获取手机的ipv4地址

2016-05-09 15:39 459 查看
http://blog.csdn.net/yueqinglkong/article/details/17391051

直接贴代码:

[java] view plain copy

print?





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的地址。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: