这是一个功能强大,使用的ip工具类,生成中碰到的大部分功能都已经处理,建议收藏,关注,精彩无限!
package com.utils;import jodd.util.StringUtil;import org.springframework.util.ObjectUtils;import javax.servlet.http.HttpServletRequest;import java.io.IOException;import java.io.InputStreamReader;import java.io.LineNumberReader;import java.net.*;import java.util.Enumeration;import java.util.regex.Matcher;import java.util.regex.Pattern;/*** 描述: 获取ip帮助类 <br>* 作者: IT学习道场 <br>* 实践: 2019-12-5 4:41:58 <br>*/public class IPUtil {private static final String UNKNOWN = "unknown";private static final Pattern PATTERN = Pattern.compile("^((2([0-4]\\d|5[0-5])|[01]?\\d{1,2})\\.){3}(2([0-4]\\d|5[0-5])|[01]?\\d{1,2})$");protected IPUtil(){}/*** 获取 IP地址* 使用 Nginx等反向代理软件, 则不能通过 request.getRemoteAddr()获取 IP地址* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,* X-Forwarded-For中第一个非 unknown的有效IP字符串,则为真实IP地址*/public static String getIpAddr(HttpServletRequest request) {String ip = request.getHeader("x-forwarded-for");if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("Proxy-Client-IP");}if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("WL-Proxy-Client-IP");}if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {ip = request.getRemoteAddr();}return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;}/*** ip转换成long** @param ip ip* @return long*/public static Long ipToLong(String ip) {//校验ip是否正确Matcher matcher = PATTERN.matcher(ip);if (!matcher.find()) {throw new RuntimeException("ip 格式不正确");}String[] split = ip.split("\\.");return (Long.parseLong(split[0]) << 24) + (Long.parseLong(split[1]) << 16)+ (Long.parseLong(split[2]) << 8) + Long.parseLong(split[3]);}/*** 将long类型转换成ip** @param ipLong ip的long类型* @return ip*/public static String longToIp(Long ipLong) {StringBuilder ip = new StringBuilder();ip.append(ipLong >>> 24).append(".");ip.append((ipLong >>> 16) & 0xFF).append(".");ip.append((ipLong >>> 8) & 0xFF).append(".");ip.append(ipLong & 0xFF);return ip.toString();}/*** 检查是否为内部IP地址** @param ip IP地址* @return 结果*/public static boolean internalIp(String ip){byte[] addr = textToNumericFormatV4(ip);return internalIp(addr) || "127.0.0.1".equals(ip);}/*** 检查是否为内部IP地址** @param addr byte地址* @return 结果*/private static boolean internalIp(byte[] addr){if (ObjectUtils.isEmpty(addr) || addr.length < 2){return true;}final byte b0 = addr[0];final byte b1 = addr[1];// 10.x.x.x/8final byte SECTION_1 = 0x0A;// 172.16.x.x/12final byte SECTION_2 = (byte) 0xAC;final byte SECTION_3 = (byte) 0x10;final byte SECTION_4 = (byte) 0x1F;// 192.168.x.x/16final byte SECTION_5 = (byte) 0xC0;final byte SECTION_6 = (byte) 0xA8;switch (b0) {case SECTION_1:return true;case SECTION_2:if (b1 >= SECTION_3 && b1 <= SECTION_4) {return true;}case SECTION_5:switch (b1) {case SECTION_6:return true;}default:return false;}}/*** 将IPv4地址转换成字节** @param text IPv4地址* @return byte 字节*/public static byte[] textToNumericFormatV4(String text){if (text.length() == 0) {return null;}byte[] bytes = new byte[4];String[] elements = text.split("\\.", -1);try {long l;int i;switch (elements.length) {case 1:l = Long.parseLong(elements[0]);if ((l < 0L) || (l > 4294967295L)) {return null;}bytes[0] = (byte) (int) (l >> 24 & 0xFF);bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);bytes[3] = (byte) (int) (l & 0xFF);break;case 2:l = Integer.parseInt(elements[0]);if ((l < 0L) || (l > 255L)) {return null;}bytes[0] = (byte) (int) (l & 0xFF);l = Integer.parseInt(elements[1]);if ((l < 0L) || (l > 16777215L)) {return null;}bytes[1] = (byte) (int) (l >> 16 & 0xFF);bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);bytes[3] = (byte) (int) (l & 0xFF);break;case 3:for (i = 0; i < 2; ++i) {l = Integer.parseInt(elements[i]);if ((l < 0L) || (l > 255L)) {return null;}bytes[i] = (byte) (int) (l & 0xFF);}l = Integer.parseInt(elements[2]);if ((l < 0L) || (l > 65535L)) {return null;}bytes[2] = (byte) (int) (l >> 8 & 0xFF);bytes[3] = (byte) (int) (l & 0xFF);break;case 4:for (i = 0; i < 4; ++i) {l = Integer.parseInt(elements[i]);if ((l < 0L) || (l > 255L)) {return null;}bytes[i] = (byte) (int) (l & 0xFF);}break;default:return null;}}catch (NumberFormatException e) {return null;}return bytes;}/*** 获取本地IP地址 <br>* 注意:linux中会拿host文件中的ip,大部分没有配置的话会拿出127.0.0.1 <br>* 非docker容器中的程序可以采用下方 getLocalIp()方法* @return 本地IP地址*/public static String getHostIp() {try {return InetAddress.getLocalHost().getHostAddress();} catch (UnknownHostException e) {e.printStackTrace();}return "127.0.0.1";}/*** 根据网卡获取本机ip <br>* 注意:若是在docker容器中跑的程序,会拿到 docker的ip <br>* 若是想拿宿主机的ip,加以调用下方 getLocalNetCardAdd() 方法* @return 本地IP地址*/public static String getLocalNetCardIp() {InetAddress inetAddress = null;boolean isFind = false; // 返回标识Enumeration<NetworkInterface> networkInterfaceLists = null;try {// 获取网络接口networkInterfaceLists = (Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces();} catch (SocketException e) {e.printStackTrace();}while (networkInterfaceLists.hasMoreElements()) {NetworkInterface networkInterface = (NetworkInterface) networkInterfaceLists.nextElement();Enumeration<InetAddress> ips = networkInterface.getInetAddresses();// 遍历所有ip,获取本地地址中不是回环地址的ipv4地址while (ips.hasMoreElements()) {inetAddress = (InetAddress) ips.nextElement();if (inetAddress instanceof Inet4Address && inetAddress.isSiteLocalAddress()&& !inetAddress.isLoopbackAddress()) {isFind = true;break;}}if (isFind) {break;}}return inetAddress == null ? "" : inetAddress.getHostAddress();}/*** 根据网卡获得IP地址<br>* 获取到本机网卡ip,就是在docker里跑的程序,也获取的是宿主机的ip地址* @return 本地IP地址*/public static String getLocalNetCardAdd() {String ip="";try {for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {NetworkInterface intf = en.nextElement();String name = intf.getName();if (!name.contains("docker") && !name.contains("lo")) {for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {//获得IPInetAddress inetAddress = enumIpAddr.nextElement();if (!inetAddress.isLoopbackAddress()) {String ipaddress = inetAddress.getHostAddress().toString();if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {if(!"127.0.0.1".equals(ip)){ip = ipaddress;}}}}}}} catch (SocketException e) {e.printStackTrace();}return ip;}/*** 获取主机名* @return 本地主机名*/public static String getHostName() {try {return InetAddress.getLocalHost().getHostName();}catch (UnknownHostException e) {e.printStackTrace();}return "未知";}/*** 从多级反向代理中获得第一个非unknown IP地址* @param ip 获得的IP地址* @return 第一个非unknown IP地址*/public static String getMultistageReverseProxyIp(String ip) {// 多级反向代理检测if (ip != null && ip.indexOf(",") > 0) {final String[] ips = ip.trim().split(",");for (String subIp : ips) {if (false == isUnknown(subIp)) {ip = subIp;break;}}}return ip;}/*** 检测给定字符串是否为未知,多用于检测HTTP请求相关* @param checkString 被检测的字符串* @return 是否未知*/public static boolean isUnknown(String checkString) {return ObjectUtils.isEmpty(checkString) || "unknown".equalsIgnoreCase(checkString);}/*** 获取客户端Mac地址* @param ip* @return*/public static String getMACAddress(String ip) {String str = "";String macAddress = "";if(StringUtil.isEmpty(ip)){return macAddress;}try {Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);InputStreamReader ir = new InputStreamReader(p.getInputStream());LineNumberReader input = new LineNumberReader(ir);for (int i = 1; i < 100; i++) {str = input.readLine();if (str != null) {if (str.indexOf("MAC Address") > 1) {macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());break;}}}} catch (IOException e) {return "";}return macAddress;}public static void main(String[] args) {Long ipToLong = ipToLong("147.111.90.201");System.out.println(ipToLong);System.out.println(longToIp(ipToLong));}}
文章转载自IT学习道场,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




