Java获取本机的用户名和ip地址

本文介绍了一种使用Java方法获取本地IP地址以及通过IP地址获取地理位置的技术。首先,通过调用Jsoup连接到特定网站来抓取本地IP。其次,利用百度开放数据API,输入IP地址获取其对应的地理位置信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、获取本地ip

在这里插入图片描述

2、获取本机的网络ip

/**
	 * 获取本机ip
	 * @return
	 */
	public static String getIp(){
		try {
			Element element = Jsoup.connect("http://www.ip38.com/").get()
					.select("a[href^=/ip.php?ip]").first();
			if (element != null) {
				return element.text();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

在这里插入图片描述

3、根据ip获取所在地

/**
	 * 根据ip获取所在地
	 * @param ip
	 * @return
	 */
	public static String getAddressByIp(String ip){
		try{
			URL url=new URL("http://opendata.baidu.com/api.php?query="+ip+"&co=&resource_id=6006&t=1433920989928&ie=utf8&oe=utf-8&format=json");
			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();
			JSONObject jsStr=JSON.parseObject(result.toString());
			JSONArray jsData=(JSONArray)jsStr.get("data");
			JSONObject data=(JSONObject)jsData.get(0);//位置
			return(String)data.get("location");
		}catch(IOException e){
			return"读取失败";
		}
	}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值