android手机两种方式获取IP地址
1.使用WIFI
首先设置用户权限
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
- <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
- <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
其次,代码如下
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //获取wifi服务
- WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
- //判断wifi是否开启
- if (!wifiManager.isWifiEnabled()) {
- wifiManager.setWifiEnabled(true);
- }
- WifiInfo wifiInfo = wifiManager.getConnectionInfo();
- int ipAddress = wifiInfo.getIpAddress();
- String ip = intToIp(ipAddress);
- EditText et = (EditText)findViewById(R.id.EditText01);
- et.setText(ip);
- }
- private String intToIp(int i) {
- return (i & 0xFF ) + "." +
- ((i >> 8 ) & 0xFF) + "." +
- ((i >> 16 ) & 0xFF) + "." +
- ( i >> 24 & 0xFF) ;
- }
2.使用GPRS
首先,设置用户上网权限
- <uses-permission android:name="android.permission.INTERNET"></uses-permission>
其次,代码如下
- 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())
- {
- return inetAddress.getHostAddress().toString();
- }
- }
- }
- }
- catch (SocketException ex)
- {
- Log.e("WifiPreference IpAddress", ex.toString());
- }
- return null;
- }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。