作为一个屌丝程序员不得不收藏的工具类 一 IP获取工具类

来源:互联网 发布:台湾进出口数据 编辑:IT博客网 时间:2019/10/18 01:32
import java.net.Inet4Address;import java.net.InetAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.net.UnknownHostException;import java.util.Enumeration;import javax.servlet.http.HttpServletRequest;/** * IP工具类 *  * @author LSM *  */public class IpUtil {/** * 获取request中的IP地址 *  * @param request * @return */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();}if (ip.equals("0:0:0:0:0:0:0:1")) {ip = "本地";}return ip;}/** * 获取本机IP *  * @return * @throws SocketException */public static String getLocalIp() throws SocketException {Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();InetAddress ip = null;while (allNetInterfaces.hasMoreElements()) {NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();Enumeration addresses = netInterface.getInetAddresses();while (addresses.hasMoreElements()) {ip = (InetAddress) addresses.nextElement();if (ip != null && ip instanceof Inet4Address) {return ip.getHostAddress();}}}return null;}/** * 获取本机IP *  * @return * @throws SocketException */public static String getLocalIp(){InetAddress address = null;try {address = InetAddress.getLocalHost();} catch (UnknownHostException e) {e.printStackTrace();}return address.getHostAddress();}}

0 0