package cn.com.infosec.IDCard.radius.util; /** * <p> * {此处加类的实现说明} * </p> * * <p> * 版权所有:北京信安世纪科技股份有限公司(c) 2020 * </p> * * @author: jlcui * @date: 2023-06-0713:15 */ import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.*; /** * 系统获取IP工具类 */ public final class IPUtil { /** * 取到当前机器的IP地址,这里可以直接获取该服务器的所有网卡ip,如果包括内外网网卡,就是两个ip,中间以,分隔。 */ public static String getIp() { String hostIp = null; List<String> ips = new ArrayList<String>(); Enumeration<NetworkInterface> netInterfaces = null; try { netInterfaces = NetworkInterface.getNetworkInterfaces(); while (netInterfaces.hasMoreElements()) { NetworkInterface netInterface = netInterfaces.nextElement(); Enumeration<InetAddress> inteAddresses = netInterface.getInetAddresses(); while (inteAddresses.hasMoreElements()) { InetAddress inetAddress = inteAddresses.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { ips.add(inetAddress.getHostAddress()); } } } } catch (SocketException ex) { ex.printStackTrace(); } hostIp = collectionToDelimitedString(ips, ","); return hostIp; } /** * 集合转化为连接字符串 */ private static String collectionToDelimitedString(Collection<String> coll, String delim) { if (coll == null || coll.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); Iterator<?> it = coll.iterator(); while (it.hasNext()) { sb.append(it.next()); if (it.hasNext()) { sb.append(delim); } } return sb.toString(); } /** * 获取服务器名称 */ public static String getHostName() { String hostName = null; try { hostName = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { e.fillInStackTrace(); } return hostName; } public static void main(String[] args) { System.out.println(IPUtil.getIp()); System.out.println(IPUtil.getHostName()); String[] strArr = {"Google", "Baidu", "IBM", "Github", "Stackoverflow"}; List<String> list = Arrays.asList(strArr); String result = collectionToDelimitedString(list, "、"); System.out.println(result); } }
标签:java,String,IP,return,获取,coll,netInterfaces,import,工具 From: https://www.cnblogs.com/cuijinlong/p/17463054.html