ip的获取与ping ip
import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetAddress; /** * IP工具 * @Author ChenWenChao */ public class IpUtils { /** * 获取真实IP * @param request 请求体 * @return 真实IP */ public static String getRealIp(HttpServletRequest request) { // 这个一般是Nginx反向代理设置的参数 String ip = request.getHeader("X-Real-IP"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 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(); } // 处理多IP的情况(只取第一个IP) if (ip != null && ip.contains(",")) { String[] ipArray = ip.split(","); ip = ipArray[0]; } return ip; } /** * ping ip * @param ip * @return true:ping通,false:ping不通 */ public static boolean pingIp(String ip) { Runtime runtime = Runtime.getRuntime(); // 获取当前程序的运行进对象 Process process = null; // 声明处理类对象 String line = null; // 返回行信息 InputStream is = null; // 输入流 InputStreamReader isr = null; // 字节流 BufferedReader br = null; boolean res = false; // 结果 try { process = runtime.exec("ping " + ip); // PING is = process.getInputStream(); // 实例化输入流 isr = new InputStreamReader(is, "gbk"); // 把输入流转换成字节流,传入参数为了解决"gbk"中文乱码问题 br = new BufferedReader(isr); // 从字节中读取文本 while ((line = br.readLine()) != null) { line = new String(line.getBytes("UTF-8"), "UTF-8"); if (line.contains("TTL")) { // 通了 res = true; System.out.println(line); break; } } is.close(); isr.close(); br.close(); } catch (IOException e) { System.out.println(e); runtime.exit(1); } return res; } /** * ping ip * @param ip * @param timeout 超时时间,单位毫秒(经过多次测试,时间建议设置超过3秒) * @return true:ping通,false:ping不通 */ public static boolean pingIp(String ip, int timeout) throws Exception { InetAddress address = InetAddress.getByName(ip); return address.isReachable(timeout); } }