1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > java如何获得内网ip 外网ip 以及如何根据ip查询地址

java如何获得内网ip 外网ip 以及如何根据ip查询地址

时间:2021-11-27 04:18:16

相关推荐

java如何获得内网ip 外网ip 以及如何根据ip查询地址

今天突发奇想地想要用java写一个小的工具类。

用来实现如何获得本机的内网ip,外网ip和根据ip获得相应的地址。

花了几个小时才弄清,然后整理了一下,希望有用。

首先要明白以下三种ip地址的区别:

(1)127.0.0.1也就是localhost,这是本地ip地址,是只能用于本机访问本机的网络时使用的

(2)192.168.1.1 ~ 192.168.1.255,之类的内网ip地址是用于局域网内相互访问时的ip地址

是路由器给你分配的一个IP地址,只能在局域网中使用

(3)还有一种就是外网IP地址,最直接的查找本机IP地址的方式就是百度:(同一路由器下的外网ip相同)

外网IP地址是电脑在互联网中彼此区分的一个依据,你的外网IP地址直接可以确定你的位置。

可以直接在/service/getIpInfo.php?ip=后面输入ip地址来获得实际地址,

返回的是一个jason对象

在下面的案例中就是根据这个地址定位的。话不多说,直接上代码:

IP地址工具类(亲测可用):(复制粘贴好之后直接运行即可)

package Util;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import .HttpURLConnection;import .InetAddress;import .MalformedURLException;import workInterface;import .SocketException;import .URL;import .URLDecoder;import java.util.Enumeration;import java.util.Scanner;import java.util.regex.Matcher;import java.util.regex.Pattern;/*** * ip地址工具类* * @author ACGkaka* ** */public class AddressUtils {/*** 获取本机的内网ip地址** @return* @throws SocketException*/public String getInnetIp() throws SocketException {String localip = null;// 本地IP,如果没有配置外网IP则返回它String netip = null;// 外网IPEnumeration<NetworkInterface> netInterfaces;netInterfaces = NetworkInterface.getNetworkInterfaces();InetAddress ip = null;boolean finded = false;// 是否找到外网IPwhile (netInterfaces.hasMoreElements() && !finded) {NetworkInterface ni = netInterfaces.nextElement();Enumeration<InetAddress> address = ni.getInetAddresses();while (address.hasMoreElements()) {ip = address.nextElement();if (!ip.isSiteLocalAddress() &&!ip.isLoopbackAddress() &&ip.getHostAddress().indexOf(":") == -1){// 外网IPnetip = ip.getHostAddress();finded = true;break;} else if (ip.isSiteLocalAddress() &&!ip.isLoopbackAddress() &&ip.getHostAddress().indexOf(":") == -1){// 内网IPlocalip = ip.getHostAddress();}}}if (netip != null && !"".equals(netip)) {return netip;} else {return localip;}}/*** 获取本机的外网ip地址** @return*/public String getV4IP() {String ip = "";String chinaz = "";StringBuilder inputLine = new StringBuilder();String read = "";URL url = null;HttpURLConnection urlConnection = null;BufferedReader in = null;try {url = new URL(chinaz);urlConnection = (HttpURLConnection) url.openConnection();in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));while ((read = in.readLine()) != null) {inputLine.append(read + "\r\n");}//System.out.println(inputLine.toString());} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}Pattern p = pile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");Matcher m = p.matcher(inputLine.toString());if (m.find()) {String ipstr = m.group(1);ip = ipstr;//System.out.println(ipstr);}return ip;}/*** 解析ip地址* * 设置访问地址为/service/getIpInfo.php* 设置请求参数为ip=[已经获得的ip地址]* 设置解码方式为UTF-8* ** @param content 请求的参数 格式为:ip=192.168.1.101* @param encoding 服务器端请求编码。如GBK,UTF-8等* @return* @throws UnsupportedEncodingException*/public String getAddresses(String content, String encoding) throws UnsupportedEncodingException {//设置访问地址String urlStr = "/service/getIpInfo.php";// 从取得IP所在的省市区信息String returnStr = this.getResult(urlStr, content, encoding);if (returnStr != null) {// 处理返回的省市区信息// System.out.println(returnStr);String[] temp = returnStr.split(",");if (temp.length < 3) {return "0";// 无效IP,局域网测试}String country = ""; //国家String area = ""; //地区String region = ""; //省份String city = ""; //市区String county = ""; //地区String isp = ""; //ISP公司for (int i = 0; i < temp.length; i++) {switch (i) {case 2:country = (temp[i].split(":"))[1].replaceAll("\"", "");country = URLDecoder.decode(country, encoding);// 国家break;case 3:area = (temp[i].split(":"))[1].replaceAll("\"", "");area = URLDecoder.decode(area, encoding);// 地区break;case 4:region = (temp[i].split(":"))[1].replaceAll("\"", "");region = URLDecoder.decode(region, encoding);// 省份break;case 5:city = (temp[i].split(":"))[1].replaceAll("\"", "");city = URLDecoder.decode(city, encoding);// 市区if ("内网IP".equals(city)) {return "地址为:内网IP";}break;case 6:county = (temp[i].split(":"))[1].replaceAll("\"", "");county = URLDecoder.decode(county, encoding);// 地区break;case 7:isp = (temp[i].split(":"))[1].replaceAll("\"", "");isp = URLDecoder.decode(isp, encoding); // ISP公司break;}}return new StringBuffer("地址为:" + country + ",").append(region + "省,").append(city + "市,").append(county + ",").append("ISP公司:" + isp).toString();}return null;}/*** 访问目标地址并获取返回值** @param urlStr 请求的地址* @param content 请求的参数 格式为:ip=192.168.1.101* @param encoding 服务器端请求编码。如GBK,UTF-8等* @return*/private String getResult(String urlStr, String content, String encoding) {URL url = null;HttpURLConnection connection = null;try {url = new URL(urlStr);connection = (HttpURLConnection) url.openConnection();// 新建连接实例connection.setConnectTimeout(2000);// 设置连接超时时间,单位毫秒connection.setReadTimeout(33000);// 设置读取数据超时时间,单位毫秒connection.setDoOutput(true);// 是否打开输出流 true|falseconnection.setDoInput(true);// 是否打开输入流true|falseconnection.setRequestMethod("POST");// 提交方法POST|GETconnection.setUseCaches(false);// 是否缓存true|falseconnection.connect();// 打开连接端口DataOutputStream out = new DataOutputStream(connection.getOutputStream());// 打开输出流往对端服务器写数据out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxxout.flush();// 刷新out.close();// 关闭输出流BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据// ,以BufferedReader流来读取StringBuffer buffer = new StringBuffer();String line = "";while ((line = reader.readLine()) != null) {buffer.append(line);}reader.close();return buffer.toString();} catch (IOException e) {e.printStackTrace();} finally {if (connection != null) {connection.disconnect();// 关闭连接}}return null;}/*** 测试方法* 获取本机的内网ip,外网ip和指定ip的地址** @param args*/public static void main(String[] args) {AddressUtils addressUtils = new AddressUtils();//step1.获得内网ip和外网ip,并输出到控制台String ip1 = "";try {ip1 = addressUtils.getInnetIp(); //局域网的ip地址,比如:192.168.1.101} catch (SocketException e1) {e1.printStackTrace();}System.out.println("内网ip:" + ip1);String ip2 = addressUtils.getV4IP(); //用于实际判断地址的ipSystem.out.println("外网ip:" + ip2);//step2.根据外网ip地址,得到市级地理位置String address = "";try {address = addressUtils.getAddresses("ip=" + ip2, "utf-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}// 输出地址,比如:中国,山东省,济南市,联通System.out.println("您的" + address);System.out.println("******************************");System.out.println("请输入想要查询的ip地址(输入exit退出):");Scanner scan = new Scanner(System.in);String ip = "";while (!"exit".equals(ip = scan.next())) {try {address = addressUtils.getAddresses("ip=" + ip, "utf-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}// 输出地址,比如:中国,山东省,济南市,联通System.out.println(ip + "的" + address);System.out.println("******************************");System.out.println("请输入想要查询的ip地址(输入exit退出):");}scan.close();System.out.println("再见");}}

上面的代码最多只能定位到市级位置,下面再给大家提供两个可以对ip地址进行比较精确定位的地址:

网址一:/

网址二:/Data/IP/LocHighAcc.aspx

工具类还不是很健全,目前还在学习,欢迎各位大佬批评指正~

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。