手机上网传数据有3种形式:
2G/3G、WI-FI、蓝牙。
下面2种网络获取手机IP注意事项:
1、通过WI-FI上网手机会获得一个WI-FI型的IP地址,前提是手机要支持WI-FI。注意:手机要先开启WI-FI,设置好上网点,不是飞行模式。
2、通过2G/3G网络上网手机会获得一个2G/3G型的Ip地址,前提是手机要支持2G/3G网络。注意,不是飞行模式。
访问网站后,点击自己的Android工程图标应用,就可显示IP了。
代码:
public class GetIP extends Activity
{ /** Called when the activity is first created. */ String str = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView et = (TextView)findViewById(R.id.tv); et.setText(getLocalIpAddress()); } private String intToIp(int i) { return (i & 0xFF ) + "." + ((i >> 8 ) & 0xFF) + "." + ((i >> 16 ) & 0xFF) + "." + ( i >> 24 & 0xFF) ; }
//获取wifi ip 和 mac
public String getLocalMacAddress(Context context) { //获取wifi服务 WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); //判断wifi是否开启,wifi未开启时,返回的ip为0.0.0.0 if (!wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(true); } WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String Ip = intToIp(wifiInfo.getIpAddress()); String Mac = wifiInfo.getMacAddress(); return "WiFi->Ip:"+ Ip + "\nWiFi->Mac:" + Mac; }
//Get IP address
权限:<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>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) { } return null; }
<uses-permission android:name="android.permission.INTERNET"/>