Example usage for java.net NetworkInterface getNetworkInterfaces

List of usage examples for java.net NetworkInterface getNetworkInterfaces

Introduction

In this page you can find the example usage for java.net NetworkInterface getNetworkInterfaces.

Prototype

public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException 

Source Link

Document

Returns an Enumeration of all the interfaces on this machine.

Usage

From source file:org.brandroid.openmanager.fragments.DialogHandler.java

private static String getNetworkInterfaces() {
    String ret = "IP Address:";
    try {// w ww  . java2 s  .com
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface ni = en.nextElement();
            for (Enumeration<InetAddress> enumIP = ni.getInetAddresses(); enumIP.hasMoreElements();) {
                InetAddress ip = enumIP.nextElement();
                if (!ip.isLoopbackAddress())
                    ret += " " + ip.getHostAddress();
            }
        }
    } catch (SocketException e) {
        Logger.LogError("Couldn't get Network Interfaces", e);
    }
    ret += "\n";
    return ret;
}

From source file:com.clustercontrol.agent.Agent.java

public static AgentInfo getAgentInfo() {
    // IP???????agentInfo??????
    if (ReceiveTopic.isReloadFlg()) {
        return agentInfo;
    }// w w  w  .  jav a2  s  .  c o  m

    agentInfo.setFacilityId(AgentProperties.getProperty("facilityId"));
    String instanceId = AgentProperties.getProperty("instanceId");
    if (instanceId == null) {
        instanceId = "";
    }
    agentInfo.setInstanceId(instanceId);

    // OS(?????IP)
    try {
        // ???
        String hostname = System.getProperty("hostname");
        m_log.debug("hostname=[" + hostname + "]");
        agentInfo.setHostname(hostname);

        // IP?
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        ArrayList<String> newIpAddressList = new ArrayList<String>();
        if (null != networkInterfaces) {
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface ni = networkInterfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress in = inetAddresses.nextElement();
                    String hostAddress = in.getHostAddress();
                    if (hostAddress != null && !hostAddress.equals("127.0.0.1")
                            && !hostAddress.startsWith("0:0:0:0:0:0:0:1") && !hostAddress.equals("::1")) {
                        newIpAddressList.add(hostAddress);
                    }
                }
            }
        }
        if (agentInfo.getIpAddress().size() != newIpAddressList.size()) {
            m_log.info("ipAddress change : " + agentInfo.getIpAddress().size() + "," + newIpAddressList.size());
            agentInfo.getIpAddress().clear();
            agentInfo.getIpAddress().addAll(newIpAddressList);
            ReceiveTopic.setReloadFlg(true);
        } else {
            if (!agentInfo.getIpAddress().containsAll(newIpAddressList)) {
                m_log.info("ipAddress change");
                agentInfo.getIpAddress().clear();
                agentInfo.getIpAddress().addAll(newIpAddressList);
                ReceiveTopic.setReloadFlg(true);
            }
        }
    } catch (SocketException e) {
        m_log.error(e, e);
    }
    agentInfo.setInterval(ReceiveTopic.getTopicInterval());

    m_log.debug(getAgentStr());

    return agentInfo;
}

From source file:com.landenlabs.all_devtool.NetFragment.java

public static String getMacAddr() {
    try {//from www .ja  v a 2s. c o  m
        List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface nif : all) {
            if (!nif.getName().equalsIgnoreCase("wlan0"))
                continue;

            byte[] macBytes = nif.getHardwareAddress();
            if (macBytes == null) {
                return "";
            }

            StringBuilder res1 = new StringBuilder();
            for (byte b : macBytes) {
                res1.append(Integer.toHexString(b & 0xFF)).append(":");
            }

            if (res1.length() > 0) {
                res1.deleteCharAt(res1.length() - 1);
            }
            return res1.toString();
        }
    } catch (Exception ex) {
    }
    return "02:00:00:00:00:00";
}

From source file:com.jagornet.dhcp.server.JagornetDhcpServer.java

/**
 * Gets all IPv6 network interfaces on the local host.
 * //  w  w  w  . j  av a2  s  .  co  m
 * @return the list NetworkInterfaces
 */
private List<NetworkInterface> getAllIPv6NetIfs() throws SocketException {
    List<NetworkInterface> netIfs = new ArrayList<NetworkInterface>();
    Enumeration<NetworkInterface> localInterfaces = NetworkInterface.getNetworkInterfaces();
    if (localInterfaces != null) {
        while (localInterfaces.hasMoreElements()) {
            NetworkInterface netIf = localInterfaces.nextElement();
            // for multicast, the loopback interface is excluded
            if (netIf.supportsMulticast() && !netIf.isLoopback()) {
                Enumeration<InetAddress> ifAddrs = netIf.getInetAddresses();
                while (ifAddrs.hasMoreElements()) {
                    InetAddress ip = ifAddrs.nextElement();
                    if (ip instanceof Inet6Address) {
                        netIfs.add(netIf);
                        break; // out to next interface
                    }
                }
            }
        }
    } else {
        log.error("No network interfaces found!");
    }
    return netIfs;
}

From source file:com.taobao.diamond.client.impl.DefaultDiamondPublisher.java

private String getHostAddress() {
    String address = "127.0.0.1";
    try {//from  w w  w  .  ja  v  a2s.  c  o  m
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface ni = en.nextElement();
            Enumeration<InetAddress> ads = ni.getInetAddresses();
            while (ads.hasMoreElements()) {
                InetAddress ip = ads.nextElement();
                if (!ip.isLoopbackAddress() && ip.isSiteLocalAddress()) {
                    return ip.getHostAddress();
                }
            }
        }
    } catch (Exception e) {
        log.error("", e);
    }
    return address;
}

From source file:org.opendaylight.netvirt.openstack.netvirt.impl.BridgeConfigurationManagerImpl.java

private String getLocalControllerHostIpAddress() {
    String ipaddress = null;//w ww  . j a va 2  s.c o  m
    try {
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
                .hasMoreElements();) {
            NetworkInterface iface = ifaces.nextElement();

            for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                InetAddress inetAddr = inetAddrs.nextElement();
                if (!inetAddr.isLoopbackAddress() && inetAddr.isSiteLocalAddress()) {
                    ipaddress = inetAddr.getHostAddress();
                    break;
                }
            }
        }
    } catch (Exception e) {
        LOG.warn("Exception while fetching local host ip address ", e);
    }
    return ipaddress;
}

From source file:org.opendaylight.ovsdb.southbound.transactions.md.OvsdbBridgeUpdateCommandTest.java

@SuppressWarnings("unchecked")
@Test/*from   w  ww. j ava  2 s  .  c o  m*/
public void testSetOpenFlowNodeRef() throws Exception {
    PowerMockito.mockStatic(SouthboundMapper.class);

    when(ovsdbBridgeUpdateCommand.getUpdates()).thenReturn(mock(TableUpdates.class));
    when(ovsdbBridgeUpdateCommand.getDbSchema()).thenReturn(mock(DatabaseSchema.class));
    PowerMockito.mockStatic(TyperUtils.class);
    Map<UUID, Controller> updatedControllerRows = new HashMap<>();
    when(TyperUtils.extractRowsUpdated(eq(Controller.class), any(TableUpdates.class),
            any(DatabaseSchema.class))).thenReturn(updatedControllerRows);

    List<ControllerEntry> controllerEntryList = new ArrayList<>();
    ControllerEntry controllerEntry = mock(ControllerEntry.class);
    controllerEntryList.add(controllerEntry);
    when(SouthboundMapper.createControllerEntries(any(Bridge.class), any(Map.class)))
            .thenReturn(controllerEntryList);
    when(controllerEntry.isIsConnected()).thenReturn(true);
    Uri uri = mock(Uri.class);
    when(controllerEntry.getTarget()).thenReturn(uri);
    when(uri.getValue()).thenReturn("tcp:192.168.12.56:6633");

    IpAddress bridgeControllerIpAddress = mock(IpAddress.class);
    PowerMockito.mockStatic(InetAddresses.class);
    when(InetAddresses.isInetAddress("192.168.12.56")).thenReturn(true);
    PowerMockito.whenNew(IpAddress.class).withAnyArguments().thenReturn(bridgeControllerIpAddress);

    PowerMockito.mockStatic(NumberUtils.class);
    when(NumberUtils.isNumber("6633")).thenReturn(true);
    PortNumber bridgeControllerPortNumber = mock(PortNumber.class);
    PowerMockito.whenNew(PortNumber.class).withAnyArguments().thenReturn(bridgeControllerPortNumber);

    PowerMockito.mockStatic(NetworkInterface.class);
    Enumeration<NetworkInterface> networkInterfaces = mock(Enumeration.class);
    when(NetworkInterface.getNetworkInterfaces()).thenReturn(networkInterfaces);

    when(networkInterfaces.hasMoreElements()).thenReturn(true, false);
    NetworkInterface networkInterface = PowerMockito.mock(NetworkInterface.class);
    when(networkInterfaces.nextElement()).thenReturn(networkInterface);

    Enumeration<InetAddress> networkInterfaceAddresses = mock(Enumeration.class);
    when(networkInterface.getInetAddresses()).thenReturn(networkInterfaceAddresses);
    when(networkInterfaceAddresses.hasMoreElements()).thenReturn(true, false);
    InetAddress networkInterfaceAddress = PowerMockito.mock(InetAddress.class);
    when(networkInterfaceAddresses.nextElement()).thenReturn(networkInterfaceAddress);

    Ipv4Address ipv4Address = mock(Ipv4Address.class);
    when(bridgeControllerIpAddress.getIpv4Address()).thenReturn(ipv4Address);
    when(ipv4Address.getValue()).thenReturn("127.0.0.1");
    when(networkInterfaceAddress.getHostAddress()).thenReturn("127.0.0.1");
    assertEquals(bridgeControllerIpAddress.getIpv4Address().getValue(),
            networkInterfaceAddress.getHostAddress());
    OvsdbConnectionInstance ovsdbConnectionInstance = mock(OvsdbConnectionInstance.class);
    when(ovsdbBridgeUpdateCommand.getOvsdbConnectionInstance()).thenReturn(ovsdbConnectionInstance);
    when(ovsdbConnectionInstance.getInstanceIdentifier()).thenReturn(mock(InstanceIdentifier.class));
    OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder = mock(OvsdbBridgeAugmentationBuilder.class);
    Bridge bridge = mock(Bridge.class);
    when(ovsdbBridgeAugmentationBuilder.setBridgeOpenflowNodeRef(any(InstanceIdentifier.class)))
            .thenReturn(ovsdbBridgeAugmentationBuilder);

    Whitebox.invokeMethod(ovsdbBridgeUpdateCommand, "setOpenFlowNodeRef", ovsdbBridgeAugmentationBuilder,
            bridge);
    verify(controllerEntry, times(2)).isIsConnected();
    verify(ovsdbBridgeAugmentationBuilder).setBridgeOpenflowNodeRef(any(InstanceIdentifier.class));
}

From source file:com.jagornet.dhcp.server.JagornetDhcpServer.java

public static List<InetAddress> getAllIPv6Addrs() {
    if (allIPv6Addrs == null) {
        allIPv6Addrs = new ArrayList<InetAddress>();
        try {//from  w  w w. ja  va2  s  .co m
            Enumeration<NetworkInterface> localInterfaces = NetworkInterface.getNetworkInterfaces();
            if (localInterfaces != null) {
                while (localInterfaces.hasMoreElements()) {
                    NetworkInterface netIf = localInterfaces.nextElement();
                    Enumeration<InetAddress> ifAddrs = netIf.getInetAddresses();
                    while (ifAddrs.hasMoreElements()) {
                        InetAddress ip = ifAddrs.nextElement();
                        if (ip instanceof Inet6Address) {
                            allIPv6Addrs.add(ip);
                        }
                    }
                }
            } else {
                log.error("No network interfaces found!");
            }
        } catch (IOException ex) {
            log.error("Failed to get IPv6 addresses: " + ex);
        }
    }
    return allIPv6Addrs;
}

From source file:org.jivesoftware.openfire.clearspace.ClearspaceManager.java

private List<String> getServerInterfaces() {

    List<String> bindInterfaces = new ArrayList<String>();

    String interfaceName = JiveGlobals.getXMLProperty("network.interface");
    String bindInterface = null;/*from   www .j  a va2 s  .  c o  m*/
    if (interfaceName != null) {
        if (interfaceName.trim().length() > 0) {
            bindInterface = interfaceName;
        }
    }

    int adminPort = JiveGlobals.getXMLProperty("adminConsole.port", 9090);
    int adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091);

    if (bindInterface == null) {
        try {
            Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netInterface : Collections.list(nets)) {
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                for (InetAddress address : Collections.list(addresses)) {
                    if ("127.0.0.1".equals(address.getHostAddress())) {
                        continue;
                    }
                    if (address.getHostAddress().startsWith("0.")) {
                        continue;
                    }
                    Socket socket = new Socket();
                    InetSocketAddress remoteAddress = new InetSocketAddress(address,
                            adminPort > 0 ? adminPort : adminSecurePort);
                    try {
                        socket.connect(remoteAddress);
                        bindInterfaces.add(address.getHostAddress());
                        break;
                    } catch (IOException e) {
                        // Ignore this address. Let's hope there is more addresses to validate
                    }
                }
            }
        } catch (SocketException e) {
            // We failed to discover a valid IP address where the admin console is running
            return null;
        }
    } else {
        bindInterfaces.add(bindInterface);
    }

    return bindInterfaces;
}

From source file:de.mangelow.throughput.NotificationService.java

private String getIPAddress() {

    try {/*w  ww  .  j  a  v a 2 s.  c  om*/
        String ipv4;
        List<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
        if (nilist.size() > 0) {
            for (NetworkInterface ni : nilist) {
                List<InetAddress> ialist = Collections.list(ni.getInetAddresses());
                if (ialist.size() > 0) {
                    for (InetAddress address : ialist) {
                        if (!address.isLoopbackAddress()
                                && InetAddressUtils.isIPv4Address(ipv4 = address.getHostAddress())) {
                            return ipv4;
                        }
                    }
                }

            }
        }

    } catch (SocketException ex) {
        if (D)
            ex.printStackTrace();
    }

    return "";

}