首页

关于camel-core源码包中HostUtils主机工具类获取本地网路IP地址、主机名称相关值源码说明

标签:HostUtils,主机工具类,camel-core     发布时间:2018-04-04   

一、前言

关于camel-core源码包中org.apache.camel.util.HostUtils主机及本地工具类,主要获取网络接口地址集getNetworkInterfaceAddresses、获取网络地址InetAddress类集getAddresses、获取本地主机名称getLocalHostName、获取本地IP地址getLocalIp等

二、源码说明

package org.apache.camel.util;@b@@b@import java.net.InetAddress;@b@import java.net.NetworkInterface;@b@import java.net.UnknownHostException;@b@import java.util.Enumeration;@b@import java.util.LinkedHashSet;@b@import java.util.Map;@b@import java.util.Map.Entry;@b@import java.util.Set;@b@import java.util.TreeMap;@b@@b@public final class HostUtils@b@{@b@  public static Map<String, Set<InetAddress>> getNetworkInterfaceAddresses()@b@  {@b@    Map interfaceAddressMap = new TreeMap();@b@    try {@b@      ifaces = NetworkInterface.getNetworkInterfaces();@b@      while (ifaces.hasMoreElements()) {@b@        NetworkInterface iface = (NetworkInterface)ifaces.nextElement();@b@@b@        if ((iface.isUp()) && (!(iface.isLoopback())) && (!(iface.isPointToPoint()))) {@b@          String name = iface.getName();@b@          Enumeration ifaceAdresses = iface.getInetAddresses();@b@          while (ifaceAdresses.hasMoreElements()) {@b@            InetAddress ia = (InetAddress)ifaceAdresses.nextElement();@b@@b@            if ((!(ia.isLoopbackAddress())) && (!(ia.getHostAddress().contains(":")))) {@b@              Set addresses = (Set)interfaceAddressMap.get(name);@b@              if (addresses == null)@b@                addresses = new LinkedHashSet();@b@@b@              addresses.add(ia);@b@              interfaceAddressMap.put(name, addresses);@b@            }@b@          }@b@        }@b@      }@b@    }@b@    catch (java.net.SocketException ifaces) {@b@    }@b@    return interfaceAddressMap;@b@  }@b@@b@  public static Set<InetAddress> getAddresses()@b@  {@b@    Set allAddresses = new LinkedHashSet();@b@    Map interfaceAddressMap = getNetworkInterfaceAddresses();@b@    for (Map.Entry entry : interfaceAddressMap.entrySet()) {@b@      Set addresses = (Set)entry.getValue();@b@      if (!(addresses.isEmpty()))@b@        for (InetAddress address : addresses)@b@          allAddresses.add(address);@b@@b@    }@b@@b@    return allAddresses;@b@  }@b@@b@  private static InetAddress chooseAddress()@b@    throws UnknownHostException@b@  {@b@    Set addresses = getAddresses();@b@    if (addresses.contains(InetAddress.getLocalHost()))@b@    {@b@      return InetAddress.getLocalHost(); }@b@    if ((addresses != null) && (!(addresses.isEmpty())))@b@    {@b@      return ((InetAddress[])addresses.toArray(new InetAddress[addresses.size()]))[0];@b@    }@b@@b@    return InetAddress.getLocalHost();@b@  }@b@@b@  public static String getLocalHostName()@b@    throws UnknownHostException@b@  {@b@    return chooseAddress().getHostName();@b@  }@b@@b@  public static String getLocalIp()@b@    throws UnknownHostException@b@  {@b@    return chooseAddress().getHostAddress();@b@  }@b@}
<<热门下载>>