java解析ip地址归属地,ip地址的解析

发布时间:2022-11-18

本文目录一览:

  1. java如何查询本机ip地址和mac地址
  2. java 如何计算一个ip的归属地
  3. 如何用java获取本地ip地址
  4. java IP查询方法
  5. java中获取本地IP地址

java如何查询本机ip地址和mac地址

Java中可以使用程序来获取本地ip地址和mac地址,使用InetAddress这个工具类,示例如下:

import java.net.*;
public class NetInfo {
    public static void main(String[] args) {
        new NetInfo().say();
    }
    public void say() {
        try {
            InetAddress i = InetAddress.getLocalHost();
            System.out.println(i);            //计算机名称和IP
            System.out.println(i.getHostName());    //名称
            System.out.println(i.getHostAddress()); //只获得IP
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

也可以通过命令行窗口来查看本地ip和mac地址,输入命令:ipconfig

java 如何计算一个ip的归属地

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Test {
    public static void main(String[] args) throws Exception {
        //查询IP的接口;ip=123.115.132.140appkey=10003sign=b59bc3ef6191eb9f747dd4e83c99f2a4format=json
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("请输入要查询的IP地址:");
        String ip = br.readLine();
        String str_url = ";ip=" + ip + "appkey=10003sign=b59bc3ef6191eb9f747dd4e83c99f2a4format=json";
        URL url = new URL(str_url);
        URLConnection conn = url.openConnection();
        BufferedReader retun = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        //这里返回的是一个JSON的格式,自己解析吧。
        System.out.println(retun.readLine());
        retun.close();
    }
}

如何用java获取本地ip地址

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
 * @author Becolette
 * @description TODO
 * @date 2015-11-5 下午01:58:46
 */
public class IpAddress {
    public static String find() {
        List<String> ips = new ArrayList<String>();
        // 返回所有网络接口的一个枚举实例
        Enumeration<?> allNetInterfaces = null;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        InetAddress ip = null;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                // 获得当前网络接口
                ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address && ip.getHostAddress().indexOf(".") != -1) {
                    ips.add(ip.getHostAddress());
                }
            }
        }
        if (ips.size() == 1) {
            return ips.get(0);
        } else {
            for (String ipa : ips) {
                if (!"127.0.0.1".equals(ipa)) {
                    return ipa;
                }
            }
        }
        return MacAddress.find();
    }
}

java IP查询方法

Java编程查询IP地址归属地,可以调用淘宝提供的service查询,并且解析http请求返回的json串,代码如下:

package getAddressByIp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.sf.json.JSONObject;
public class GetAddressByIp {
    /**
     *
     * @param IP
     * @return
     */
    public static String GetAddressByIp(String IP) {
        String resout = "";
        try {
            String str = getJsonContent("" + IP);
            System.out.println(str);
            JSONObject obj = JSONObject.fromObject(str);
            JSONObject obj2 = (JSONObject) obj.get("data");
            String code = (String) obj.get("code");
            if (code.equals("0")) {
                resout = obj2.get("country") + "--" + obj2.get("area") + "--" + obj2.get("city") + "--" + obj2.get("isp");
            } else {
                resout = "IP地址有误";
            }
        } catch (Exception e) {
            e.printStackTrace();
            resout = "获取IP地址异常:" + e.getMessage();
        }
        return resout;
    }
    public static String getJsonContent(String urlStr) {
        try {
            // 获取HttpURLConnection连接对象
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            // 设置连接属性
            httpConn.setConnectTimeout(3000);
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("GET");
            // 获取相应码
            int respCode = httpConn.getResponseCode();
            if (respCode == 200) {
                return ConvertStream2Json(httpConn.getInputStream());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    private static String ConvertStream2Json(InputStream inputStream) {
        String jsonStr = "";
        // ByteArrayOutputStream相当于内存输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        // 将输入流转移到内存输出流中
        try {
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }
            // 将内存流转换为字符串
            jsonStr = new String(out.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonStr;
    }
}

java中获取本地IP地址

方法如下:

方法一,使用CMD命令:

public static String getLocalIPForCMD() {
    StringBuilder sb = new StringBuilder();
    String command = "cmd.exe /c ipconfig | findstr IPv4";
    try {
        Process p = Runtime.getRuntime().exec(command);
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = line.substring(line.lastIndexOf(":") + 2, line.length());
            sb.append(line);
        }
        br.close();
        p.destroy();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return sb.toString();
}

方法二,使用Java方法:

public static String getLocalIPForJava() {
    StringBuilder sb = new StringBuilder();
    try {
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface intf = (NetworkInterface) en.nextElement();
            Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
            while (enumIpAddr.hasMoreElements()) {
                InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()
                        && inetAddress.isSiteLocalAddress()) {
                    sb.append(inetAddress.getHostAddress().toString() + "\n");
                }
            }
        }
    } catch (SocketException e) {
    }
    return sb.toString();
}