Android获取公网IP以及局域网IP

本文是从网上其余大佬那里拿过来的,自己保存备用。

private String getNetIp(Context ctx){
		try { 
			NetworkInfo info = ((ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
			if (info != null && info.isConnected()) {
				URL url = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
				URLConnection conn = url.openConnection();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(conn.getInputStream(),
								"utf-8"));
				String line = null;
				StringBuffer result = new StringBuffer();
				while ((line = reader.readLine()) != null) {
					result.append(line);
				}
				reader.close();
				String rString = result.toString().replace("var returnCitySN = ", "");
				rString = rString.substring(0, rString.length() - 1);
				JSONObject jsonObject = new JSONObject(rString);
				return jsonObject.getString("cip");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "";
	}
	
	private String getWifiIp(Context ctx){
		try { 
			NetworkInfo info = ((ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
			if (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI) {
				WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
				WifiInfo infowifi = wifiManager.getConnectionInfo();
				String ip = intIP2StringIP(infowifi.getIpAddress());
				return ip;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "";
	}
	
	public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }
与运算:取二进制值,不同位则为0

位&运算:
    int a = 15;    //x等于二进制数的00001111
    int b = 6;     //y等于二进制数的00000110
    int c = x&y    //z等于二进制数的00000110
结果为:二进制数的00000110


位移:

取二进制,>>为去掉最右边,>>后面是几,就去掉几位

<<为在最右边加上一个0,<<后面是几,就加上几个0

然后取值。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值