如何获取手机IP

 手机上网传数据有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 
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.ACCESS_WIFI_STATE"/>

     <uses-permission android:name="android.permission.INTERNET"/>


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值