系统获取 IP 工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | 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); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述