类java.net.NetworkInterface源码实例Demo

下面列出了怎么用java.net.NetworkInterface的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: hottub   文件: NetworkPrefixLength.java
public static void main(String[] args) throws Exception {
    Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();

    while (nics.hasMoreElements()) {
        NetworkInterface nic = nics.nextElement();
        for (InterfaceAddress iaddr : nic.getInterfaceAddresses()) {
            boolean valid = checkPrefix(iaddr);
            if (!valid) {
                passed = false;
                debug(nic.getName(), iaddr);
            }
            InetAddress ia = iaddr.getAddress();
            if (ia.isLoopbackAddress() && ia instanceof Inet4Address) {
                // assumption: prefix length will always be 8
                if (iaddr.getNetworkPrefixLength() != 8) {
                    out.println("Expected prefix of 8, got " + iaddr);
                    passed = false;
                }
            }
        }
    }

    if (!passed)
        throw new RuntimeException("Failed: some interfaces have invalid prefix lengths");
}
 
源代码2 项目: TencentKona-8   文件: JdpBroadcaster.java
/**
 * Create a new broadcaster
 *
 * @param address - multicast group address
 * @param srcAddress - address of interface we should use to broadcast.
 * @param port - udp port to use
 * @param ttl - packet ttl
 * @throws IOException
 */
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
        throws IOException, JdpException {
    this.addr = address;
    this.port = port;

    ProtocolFamily family = (address instanceof Inet6Address)
            ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;

    channel = DatagramChannel.open(family);
    channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);

    // with srcAddress equal to null, this constructor do exactly the same as
    // if srcAddress is not passed
    if (srcAddress != null) {
        // User requests particular interface to bind to
        NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
        try {
            channel.bind(new InetSocketAddress(srcAddress, 0));
        } catch (UnsupportedAddressTypeException ex) {
            throw new JdpException("Unable to bind to source address");
        }
        channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
    }
}
 
源代码3 项目: jdk8u_jdk   文件: SocksIPv6Test.java
private boolean ensureIPv6OnLoopback() throws Exception {
    boolean ipv6 = false;

    List<NetworkInterface> nics = Collections.list(NetworkInterface.getNetworkInterfaces());
    for (NetworkInterface nic : nics) {
        if (!nic.isLoopback()) {
            continue;
        }
        List<InetAddress> addrs = Collections.list(nic.getInetAddresses());
        for (InetAddress addr : addrs) {
            if (addr instanceof Inet6Address) {
                ipv6 = true;
                break;
            }
        }
    }
    if (!ipv6)
        System.out.println("IPv6 is not enabled on loopback. Skipping test suite.");
    return ipv6;
}
 
源代码4 项目: codewind-eclipse   文件: PlatformUtil.java
public static String getHostName() throws SocketException {
  	Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
    NetworkInterface n = (NetworkInterface) e.nextElement();
    Enumeration<InetAddress> ee = n.getInetAddresses();
    while (ee.hasMoreElements())
    {
        InetAddress i = (InetAddress) ee.nextElement();
        if (!i.isSiteLocalAddress() && !i.isLinkLocalAddress() && !i.isLoopbackAddress() && !i.isAnyLocalAddress() && !i.isMulticastAddress()) {
        	return i.getHostName();
        }
    }
}
throw new SocketException("Failed to get the IP address for the local host");
  }
 
源代码5 项目: openmessaging-storage-dledger   文件: IOUtils.java
public static List<String> getLocalInetAddress() {
    List<String> inetAddressList = new ArrayList<String>();
    try {
        Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
        while (enumeration.hasMoreElements()) {
            NetworkInterface networkInterface = enumeration.nextElement();
            Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
            while (addrs.hasMoreElements()) {
                inetAddressList.add(addrs.nextElement().getHostAddress());
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException("get local inet address fail", e);
    }

    return inetAddressList;
}
 
源代码6 项目: PowerFileExplorer   文件: FTPService.java
public static boolean isConnectedToLocalNetwork(Context context) {
    boolean connected = false;
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    connected = ni != null
            && ni.isConnected()
            && (ni.getType() & (ConnectivityManager.TYPE_WIFI | ConnectivityManager.TYPE_ETHERNET)) != 0;
    if (!connected) {
        Log.d(TAG, "isConnectedToLocalNetwork: see if it is an USB AP");
        try {
            for (NetworkInterface netInterface : Collections.list(NetworkInterface
                    .getNetworkInterfaces())) {
                if (netInterface.getDisplayName().startsWith("rndis")) {
                    connected = true;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
    return connected;
}
 
源代码7 项目: hottub   文件: SetGetNetworkInterfaceTest.java
private static boolean isIpAddrAvailable (NetworkInterface netIf) {
    boolean ipAddrAvailable = false;
    byte[] nullIpAddr = {'0', '0', '0', '0'};
    byte[] testIpAddr = null;

    Enumeration<InetAddress> ipAddresses = netIf.getInetAddresses();
    while (ipAddresses.hasMoreElements()) {
        InetAddress testAddr = ipAddresses.nextElement();
        testIpAddr = testAddr.getAddress();
        if ((testIpAddr != null) && (!Arrays.equals(testIpAddr, nullIpAddr))) {
            ipAddrAvailable = true;
            break;
        } else {
            System.out.println("ignore netif " + netIf.getName());
        }
    }
    return ipAddrAvailable;
}
 
源代码8 项目: ApplicationPower   文件: IpUtil.java
/**
 * 获取所有ipv6地址
 *
 * @return hash map
 */
public static Map<String, String> getLocalIPV6() {
    Map<String, String> map = new HashMap<>();
    InetAddress ip = null;
    try {
        Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
        while (netInterfaces.hasMoreElements()) {
            NetworkInterface ni = netInterfaces.nextElement();
            Enumeration<InetAddress> ips = ni.getInetAddresses();
            while (ips.hasMoreElements()) {
                ip = ips.nextElement();
                if (ip instanceof Inet6Address) {
                    map.put(ni.getName(), ip.getHostAddress());
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;
}
 
源代码9 项目: JD-Test   文件: NetworkUtil.java
/**
 * 得到ip地址
 * 
 * @return
 */
public static String getLocalIpAddress() {
    String ret = "";
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    ret = inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        ex.printStackTrace();
    }
    return ret;
}
 
源代码10 项目: sailfish-core   文件: NetworkUtils.java
@Description("Returns the IPv4 for the specified network interface name.<br>" +
        "<b>interfaceName</b> - the network interface name, the IP of which will be returned<br>" +
        "Example:<br/>" +
        "#{currentIpAddress(interfaceName)}")
@UtilityMethod
public String currentIpAddress(String interfaceName) {
    try {
        NetworkInterface networkInterface = NetworkInterface.getByName(interfaceName);
        if (networkInterface == null) {
            throw new EPSCommonException("Unknown interface name: " + interfaceName);
        }
        Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
        InetAddress address;
        while (addresses.hasMoreElements()) {
            address = addresses.nextElement();
            if (address instanceof Inet4Address) {
                return address.getHostAddress();
            }
        }
        throw new EPSCommonException(String.format("Network interface %s has not IPv4", interfaceName));
    } catch (Exception e) {
        throw new EPSCommonException(String.format("Can't get interface [%s]", interfaceName), e);
    }
}
 
源代码11 项目: albert   文件: LocalIpAddressUtil.java
/**
 * 获取本地ip地址,有可能会有多个地址, 若有多个网卡则会搜集多个网卡的ip地址
 */
public static Set<InetAddress> resolveLocalAddresses() {
    Set<InetAddress> addrs = new HashSet<InetAddress>();
    Enumeration<NetworkInterface> ns = null;
    try {
        ns = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        // ignored...
    }
    while (ns != null && ns.hasMoreElements()) {
        NetworkInterface n = ns.nextElement();
        Enumeration<InetAddress> is = n.getInetAddresses();
        while (is.hasMoreElements()) {
            InetAddress i = is.nextElement();
            if (!i.isLoopbackAddress() && !i.isLinkLocalAddress() && !i.isMulticastAddress()
                && !isSpecialIp(i.getHostAddress())) addrs.add(i);
        }
    }
    return addrs;
}
 
源代码12 项目: Rainfall-core   文件: RainfallMaster.java
private boolean isCurrentHostMaster() throws SocketException {
  logger.debug("[Rainfall master] Check if the current host should start the master.");
  InetAddress masterAddress = distributedConfig.getMasterAddress().getAddress();

  Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
  while (networkInterfaces.hasMoreElements()) {
    NetworkInterface networkInterface = networkInterfaces.nextElement();

    logger.debug("[Rainfall naster] Check NIC list.");
    Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
    while (inetAddresses.hasMoreElements()) {
      InetAddress inetAddress = inetAddresses.nextElement();
      logger.debug("[Rainfall master] Check if current NIC ({}) has the IP from rainfall master host ({}).",
          inetAddress, masterAddress);
      if (inetAddress.equals(masterAddress)) {
        logger.debug("[Rainfall master] Current NIC IP is the one from the DistributedConfiguration, attempt to start the master process.");
        return true;
      }
    }
  }
  return false;
}
 
static void testAllNetworkInterfaces() throws Exception {
    System.err.println("\n testAllNetworkInterfaces: \n ");
    for (Enumeration<NetworkInterface> e = NetworkInterface
            .getNetworkInterfaces(); e.hasMoreElements();) {
        NetworkInterface netIF = e.nextElement();
        for (Enumeration<InetAddress> iadrs = netIF.getInetAddresses(); iadrs
                .hasMoreElements();) {
            InetAddress iadr = iadrs.nextElement();
            if (iadr instanceof Inet6Address) {
                System.err.println("Test NetworkInterface:  " + netIF);
                Inet6Address i6adr = (Inet6Address) iadr;
                System.err.println("Testing with " + iadr);
                System.err.println(" scoped iface: "
                        + i6adr.getScopedInterface());
                testInet6AddressSerialization(i6adr, null);
            }
        }
    }
}
 
源代码14 项目: deskcon-android   文件: DesktopHostsActivity.java
public static InetAddress getBroadcast(){
InetAddress found_bcast_address=null;
 System.setProperty("java.net.preferIPv4Stack", "true"); 
    try
    {
      Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces();
      while (niEnum.hasMoreElements())
      {
        NetworkInterface ni = niEnum.nextElement();
        if(!ni.isLoopback()){
            for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses())
            {
              found_bcast_address = interfaceAddress.getBroadcast();               
            }
        }
      }
    }
    catch (SocketException e)
    {
      e.printStackTrace();
    }

    return found_bcast_address;
}
 
源代码15 项目: openjdk-8-source   文件: UniqueMacAddressesTest.java
private boolean testMacAddressesEqual(NetworkInterface netIf1,
        NetworkInterface netIf2) throws Exception {

    byte[] rawMacAddress1 = null;
    byte[] rawMacAddress2 = null;
    boolean macAddressesEqual = false;
    if (!netIf1.getName().equals(netIf2.getName())) {
        System.out.println("compare hardware addresses "
            +  createMacAddressString(netIf1) + " and " + createMacAddressString(netIf2));
        rawMacAddress1 = netIf1.getHardwareAddress();
        rawMacAddress2 = netIf2.getHardwareAddress();
        macAddressesEqual = Arrays.equals(rawMacAddress1, rawMacAddress2);
    } else {
        // same interface
        macAddressesEqual = false;
    }
    return macAddressesEqual;
}
 
源代码16 项目: hadoop   文件: TestDelegationTokenForProxyUser.java
private static void configureSuperUserIPAddresses(Configuration conf,
    String superUserShortName) throws IOException {
  ArrayList<String> ipList = new ArrayList<String>();
  Enumeration<NetworkInterface> netInterfaceList = NetworkInterface
      .getNetworkInterfaces();
  while (netInterfaceList.hasMoreElements()) {
    NetworkInterface inf = netInterfaceList.nextElement();
    Enumeration<InetAddress> addrList = inf.getInetAddresses();
    while (addrList.hasMoreElements()) {
      InetAddress addr = addrList.nextElement();
      ipList.add(addr.getHostAddress());
    }
  }
  StringBuilder builder = new StringBuilder();
  for (String ip : ipList) {
    builder.append(ip);
    builder.append(',');
  }
  builder.append("127.0.1.1,");
  builder.append(InetAddress.getLocalHost().getCanonicalHostName());
  LOG.info("Local Ip addresses: " + builder.toString());
  conf.setStrings(DefaultImpersonationProvider.getTestProvider().
          getProxySuperuserIpConfKey(superUserShortName),
      builder.toString());
}
 
源代码17 项目: jdk8u_jdk   文件: Util.java
/**
 * Returns a list of all the addresses on the system.
 * @param  inclLoopback
 *         if {@code true}, include the loopback addresses
 * @param  ipv4Only
 *         it {@code true}, only IPv4 addresses will be included
 */
static List<InetAddress> getAddresses(boolean inclLoopback,
                                      boolean ipv4Only)
    throws SocketException {
    ArrayList<InetAddress> list = new ArrayList<InetAddress>();
    Enumeration<NetworkInterface> nets =
             NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netInf : Collections.list(nets)) {
        Enumeration<InetAddress> addrs = netInf.getInetAddresses();
        for (InetAddress addr : Collections.list(addrs)) {
            if (!list.contains(addr) &&
                    (inclLoopback ? true : !addr.isLoopbackAddress()) &&
                    (ipv4Only ? (addr instanceof Inet4Address) : true)) {
                list.add(addr);
            }
        }
    }

    return list;
}
 
源代码18 项目: roncoo-education   文件: IdWorker.java
/**
 * <p>
 * 数据标识id部分
 * </p>
 */
protected static long getDatacenterId(long maxDatacenterId) {
	long id = 0L;
	try {
		InetAddress ip = InetAddress.getLocalHost();
		NetworkInterface network = NetworkInterface.getByInetAddress(ip);
		if (network == null) {
			id = 1L;
		} else {
			byte[] mac = network.getHardwareAddress();
			if (null != mac) {
				id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
				id = id % (maxDatacenterId + 1);
			}
		}
	} catch (Exception e) {
		logger.warn(" getDatacenterId: " + e.getMessage());
	}
	return id;
}
 
源代码19 项目: activemq-artemis   文件: NetworkAddressTestBase.java
@Test
public void testConnectorToServerAcceptingAListOfHosts_2() throws Exception {
   Map<NetworkInterface, InetAddress> map = NetworkAddressTestBase.getAddressForEachNetworkInterface();
   if (map.size() <= 2) {
      System.err.println("There must be at least 3 network interfaces: test will not be executed");
      return;
   }

   Set<Entry<NetworkInterface, InetAddress>> set = map.entrySet();
   Iterator<Entry<NetworkInterface, InetAddress>> iterator = set.iterator();
   Entry<NetworkInterface, InetAddress> entry1 = iterator.next();
   Entry<NetworkInterface, InetAddress> entry2 = iterator.next();
   Entry<NetworkInterface, InetAddress> entry3 = iterator.next();

   String listOfHosts = entry1.getValue().getHostAddress() + ", " + entry2.getValue().getHostAddress();

   testConnection(listOfHosts, entry1.getValue().getHostAddress(), true, 0);
   testConnection(listOfHosts, entry2.getValue().getHostAddress(), true, 0);
   testConnection(listOfHosts, entry3.getValue().getHostAddress(), false, 0);
}
 
源代码20 项目: jdk8u-jdk   文件: Inet6AddressSerializationTest.java
static void displayExpectedInet6Address(Inet6Address expectedInet6Address) {

        String expectedHostName = expectedInet6Address.getHostName();
        byte[] expectedAddress = expectedInet6Address.getAddress();
        String expectedHostAddress = expectedInet6Address.getHostAddress();
        int expectedScopeId = expectedInet6Address.getScopeId();
        NetworkInterface expectedNetIf = expectedInet6Address
                .getScopedInterface();

        System.err.println("Excpected HostName: " + expectedHostName);
        System.err.println("Expected Address: "
                + Arrays.toString(expectedAddress));
        System.err.println("Expected HostAddress: " + expectedHostAddress);
        System.err.println("Expected Scope Id " + expectedScopeId);
        System.err.println("Expected NetworkInterface " + expectedNetIf);
        System.err.println("Expected Inet6Address " + expectedInet6Address);
    }
 
源代码21 项目: CameraV   文件: RemoteShareActivity.java
public static String[] getLocalIpAddresses(){
   try {
	   ArrayList<String> alAddresses = new ArrayList<String>();
	   
       for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();  
       en.hasMoreElements();) {
       NetworkInterface intf = en.nextElement();
           for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
           InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()&& InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
                	alAddresses.add(inetAddress.getHostAddress());
                
                }
           }
       }
       
       return alAddresses.toArray(new String[alAddresses.size()]);
       
       } catch (Exception ex) {
          Log.e("IP Address", ex.toString());
      }
      return null;
}
 
源代码22 项目: DroidDLNA   文件: NetworkAddressFactoryImpl.java
protected InetAddress getBindAddressInSubnetOf(InetAddress inetAddress) {
    synchronized (networkInterfaces) {
        for (NetworkInterface iface : networkInterfaces) {
            for (InterfaceAddress ifaceAddress : getInterfaceAddresses(iface)) {

                synchronized (bindAddresses) {
                    if (ifaceAddress == null || !bindAddresses.contains(ifaceAddress.getAddress())) {
                        continue;
                    }
                }

                if (isInSubnet(
                        inetAddress.getAddress(),
                        ifaceAddress.getAddress().getAddress(),
                        ifaceAddress.getNetworkPrefixLength())
                        ) {
                    return ifaceAddress.getAddress();
                }
            }

        }
    }
    return null;
}
 
源代码23 项目: baratine   文件: SocketSystem.java
protected ArrayList<NetworkInterfaceBase> getNetworkInterfaces()
{
  ArrayList<NetworkInterfaceBase> interfaceList = new ArrayList<>();
    
  try {
    Enumeration<NetworkInterface> ifaceEnum
      = NetworkInterface.getNetworkInterfaces();
  
    while (ifaceEnum.hasMoreElements()) {
      NetworkInterface iface = ifaceEnum.nextElement();

      interfaceList.add(new NetworkInterfaceTcp(iface));
    }
  } catch (Exception e) {
    log.log(Level.WARNING, e.toString(), e);
  }
    
  return interfaceList;
}
 
源代码24 项目: swingsane   文件: DiscoveryJob.java
public final InetAddress getLocalAddress() throws SocketException {
  for (final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces
      .hasMoreElements();) {
    final NetworkInterface networkInterface = interfaces.nextElement();
    if (networkInterface.isLoopback()) {
      continue;
    }
    for (final InterfaceAddress interfaceAddr : networkInterface.getInterfaceAddresses()) {
      final InetAddress inetAddr = interfaceAddr.getAddress();
      if (!(inetAddr instanceof Inet4Address)) {
        continue;
      }
      return inetAddr;
    }
  }
  return null;
}
 
源代码25 项目: openjdk-jdk9   文件: NetworkConfigurationProbe.java
public static void main(String... args) throws Exception {
    NetworkConfiguration.printSystemConfiguration(out);

    NetworkConfiguration nc = NetworkConfiguration.probe();
    String list;
    list = nc.ip4MulticastInterfaces()
              .map(NetworkInterface::getName)
              .collect(joining(" "));
    out.println("ip4MulticastInterfaces: " +  list);

    list = nc.ip4Addresses()
              .map(Inet4Address::toString)
              .collect(joining(" "));
    out.println("ip4Addresses: " +  list);

    list = nc.ip6MulticastInterfaces()
              .map(NetworkInterface::getName)
              .collect(joining(" "));
    out.println("ip6MulticastInterfaces: " +  list);

    list = nc.ip6Addresses()
              .map(Inet6Address::toString)
              .collect(joining(" "));
    out.println("ip6Addresses: " +  list);
}
 
源代码26 项目: dubbox-hystrix   文件: PerformanceUtils.java
public static List<String> getEnvironment() {
    List<String> environment = new ArrayList<String>();
    environment.add("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch", ""));
    environment.add("CPU: " + Runtime.getRuntime().availableProcessors() + " cores");
    environment.add("JVM: " + System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version"));
    environment.add("Memory: " + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().totalMemory()) 
                               + " bytes (Max: " + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().maxMemory()) + " bytes)");
    NetworkInterface ni = PerformanceUtils.getNetworkInterface();
    if (ni != null) {
        environment.add("Network: " + ni.getDisplayName());
    }
    return environment;
}
 
static List<Inet6Address> getAllInet6Addresses() throws Exception {
    // System.err.println("\n getAllInet6Addresses: \n ");
    ArrayList<Inet6Address> inet6Addresses = new ArrayList<Inet6Address>();
    for (Enumeration<NetworkInterface> e = NetworkInterface
            .getNetworkInterfaces(); e.hasMoreElements();) {
        NetworkInterface netIF = e.nextElement();
        for (Enumeration<InetAddress> iadrs = netIF.getInetAddresses(); iadrs
                .hasMoreElements();) {
            InetAddress iadr = iadrs.nextElement();
            if (iadr instanceof Inet6Address) {
                System.err.println("Test NetworkInterface:  " + netIF);
                Inet6Address i6adr = (Inet6Address) iadr;
                System.err.println(" address " + iadr);
                System.err.println(" scoped iface: "
                        + i6adr.getScopedInterface());
                // using this to actually set the hostName for an
                // InetAddress
                // created through the NetworkInterface
                // have found that the fabricated instances has a null
                // hostName
                System.err.println(" hostName: " + i6adr.getHostName());
                inet6Addresses.add(i6adr);
            }
        }
    }
    return inet6Addresses;
}
 
源代码28 项目: cache2k   文件: Server.java
/**
* Get non-loopback address.  InetAddress.getLocalHost() does not work on machines without static ip address.
*
* @param ni target network interface
* @param preferIPv4 true iff require IPv4 addresses only
* @param preferIPv6 true iff prefer IPv6 addresses
* @return nonLoopback {@link InetAddress}
* @throws SocketException
*/
private static InetAddress getFirstNonLoopbackAddress(NetworkInterface ni,
                                                      boolean preferIPv4,
                                                      boolean preferIPv6) throws SocketException {
    InetAddress result = null;

    // skip virtual interface name, PTP and non-running interface.
    if (ni.isVirtual() || ni.isPointToPoint() || ! ni.isUp()) {
        return result;
    }
    LOG.info("Interface name is: " + ni.getDisplayName());
    for (Enumeration en2 = ni.getInetAddresses(); en2.hasMoreElements(); ) {
        InetAddress addr = (InetAddress) en2.nextElement();
        if (!addr.isLoopbackAddress()) {
            if (addr instanceof Inet4Address) {
                if (preferIPv6) {
                    continue;
                }
                result = addr;
                break;
            }

            if (addr instanceof Inet6Address) {
                if (preferIPv4) {
                    continue;
                }
                result = addr;
                break;
            }
        }
    }
    return result;
}
 
源代码29 项目: translationstudio8   文件: LinuxSeries.java
public String getSeries() {
//		try {
////			NativeInterfaces.setLibDir(new File("lib"));
//			NativeInterfaces.setLibDir(new File(FileLocator.toFileURL(Platform.getBundle("net.heartsome.cat.ts.help").getEntry("")).getPath() 
//					+ File.separator + System.getProperty("sun.arch.data.model")));
//			EthernetAddress[] macs = NativeInterfaces.getAllInterfaces();
//			String series = "";
//			for (EthernetAddress a : macs) {
//				series += a.toString() + "+";
//			}
//			return "".equals(series) ? null : StringUtils.removeColon(series.substring(0, series.length() - 1));
//		} catch (IOException e) {
//			e.printStackTrace();
//			return null;
//		}	
		
		try {
			String series = "";
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
					.getNetworkInterfaces();
			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface network = networkInterfaces.nextElement();
				if (!network.getName().startsWith("vmnet") && !network.getName().startsWith("vboxnet")) {
					byte[] mac = network.getHardwareAddress();
					if (mac != null && mac.length == 6 && !network.isLoopback() && !network.isVirtual()) {
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < mac.length; i++) {
							sb.append(String.format("%02x", mac[i]));
						}
						sb.append("+");
						series += sb.toString();
					}
				}
			}
			return "".equals(series) ? null : series.substring(0, series.length() - 1);
		} catch (SocketException e) {
			e.printStackTrace();
			return null;
		}
	}
 
源代码30 项目: uavstack   文件: HostNewworkInfo.java
public String getMacAddressAsString(NetworkInterface ni) {

        byte[] mac = null;
        try {
            mac = ni.getHardwareAddress();
        }
        catch (SocketException e) {
            return null;
        }

        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append(":");
            }

            // 字节转换为整数
            int temp = mac[i] & 0xff;
            String str = Integer.toHexString(temp);
            if (str.length() == 1) {
                sb.append("0" + str);
            }
            else {
                sb.append(str);
            }
        }

        return sb.toString().toUpperCase();
    }
 
 类所在包
 同包方法