Java.Utils:网络工具包

Don’t say much, just go to the code.

package org.bood.shimmer.common.utils;

import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

/**
 * 网络工具包
 *
 * @author bood
 * @since 2020/9/25
 */
public class NetUtils {

    private NetUtils() {
    }


    /**
     * <p>
     * 获取请求中的 IP
     * </p>
     *
     * @param request:
     * @return:java.lang.String
     * @author:bood
     * @date:2020/9/25
     */
    public static String getIpAddress(HttpServletRequest request) {
        String[] ipHeaders = {"x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
        String[] localhostIp = {"127.0.0.1", "0:0:0:0:0:0:0:1"};
        String ip = request.getRemoteAddr();
        for (String header : ipHeaders) {
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                break;
            }
            ip = request.getHeader(header);
        }
        for (String local : localhostIp) {
            if (ip != null && ip.equals(local)) {
                try {
                    ip = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException ignored) {
                }
                break;
            }
        }
        if (ip != null && ip.length() > 15 && ip.contains(",")) {
            ip = ip.substring(0, ip.indexOf(','));
        }
        return ip;
    }

    /**
     * <p>
     * IP 转 Integer
     * </p>
     *
     * @param ip: IP 地址
     * @return:java.lang.Integer
     * @author:bood
     * @date:2020/9/25
     */
    public static Integer ipToInteger(String ip) {
        String[] ips = ip.split("\\.");
        int ipFour = 0;
        for (String ip4 : ips) {
            Integer ip4a = Integer.parseInt(ip4);
            ipFour = (ipFour << 8) | ip4a;
        }
        return ipFour;
    }

    /**
     * <p>
     * Integer 转 IP
     * </p>
     *
     * @param ip: IP 地址
     * @return:java.lang.String
     * @author:bood
     * @date:2020/9/25
     */
    public static String IntegerToIp(Integer ip) {
        StringBuilder sb = new StringBuilder();
        for (int i = 3; i >= 0; i--) {
            int ipa = (ip >> (8 * i)) & (0xff);
            sb.append(ipa + ".");
        }
        sb.delete(sb.length() - 1, sb.length());
        return sb.toString();
    }

    /**
     * <p>
     * IP 地址是否可达
     * </p>
     *
     * @param ip: IP 地址
     * @return:boolean
     * @author:bood
     * @date:2020/9/25
     */
    public static boolean isReachable(String ip) {
        InetAddress address;
        try {
            address = InetAddress.getByName(ip);
            if (address.isReachable(5000)) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * <p>
     * 根据 url 和请求参数获取 URI
     * </p>
     *
     * @param url:    请求地址
     * @param params: 请求参数
     * @return:java.net.URI
     * @author:bood
     * @date:2020/9/25
     */
    public static URI getURIwithParams(String url, MultiValueMap<String, String> params) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParams(params);
        return builder.build().encode().toUri();
    }

    /**
     * <p>
     * 判断网址是否有效
     * 对于404页面,如果被电信或者联通劫持了,也会返回200的状态,这个是不准确的
     * </p>
     *
     * @param url: 请求地址
     * @return:boolean
     * @author:bood
     * @date:2020/9/25
     */
    public static boolean isReachable(URL url) {
        boolean reachable = false;
        HttpURLConnection httpconn = null;
        HttpsURLConnection httpsconn = null;
        int code = 0;

        try {
            if ("https".equals(url.getProtocol())) {
                httpsconn = (HttpsURLConnection) url.openConnection();
                code = httpsconn.getResponseCode();
            } else {
                httpconn = (HttpURLConnection) url.openConnection();
                code = httpconn.getResponseCode();
            }
            if (code == 200) {
                reachable = true;
            }
        } catch (Exception e) {
            reachable = false;
        }

        return reachable;
    }

    /**
     * <p>
     * 实现 Ping 命令
     * Ping 的字符串换行使用 java 的换行符"\n",如果 ping 不同返回 null
     * </p>
     *
     * @param ip: IP 地址
     * @return:java.lang.String
     * @author:bood
     * @date:2020/9/25
     */
    public static String ping(String ip) {
        String res = "";
        String line = null;
        try {
            Process pro = Runtime.getRuntime().exec("ping " + ip);
            BufferedReader buf = new BufferedReader(new InputStreamReader(pro.getInputStream(), "GBK"));
            while ((line = buf.readLine()) != null) {
                if (!"".equals(line)) {
                    res += line + "\n";
                }
            }
        } catch (Exception e) {
            res = null;
        }
        return res;
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值