List of usage examples for java.net NetworkInterface getNetworkInterfaces
public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException
From source file:org.magnum.dataup.VideoController.java
private static InetAddress getLocalHostLANAddress() throws UnknownHostException { try {//from ww w .jav a2 s. c o m InetAddress candidateAddress = null; // Iterate all NICs (network interface cards)... for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) { NetworkInterface iface = (NetworkInterface) ifaces.nextElement(); // Iterate all IP addresses assigned to each card... for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) { InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); if (!inetAddr.isLoopbackAddress()) { if (inetAddr.isSiteLocalAddress()) { // Found non-loopback site-local address. Return it immediately... return inetAddr; } else if (candidateAddress == null) { // Found non-loopback address, but not necessarily site-local. // Store it as a candidate to be returned if site-local address is not subsequently found... candidateAddress = inetAddr; // Note that we don't repeatedly assign non-loopback non-site-local addresses as candidates, // only the first. For subsequent iterations, candidate will be non-null. } } } } if (candidateAddress != null) { // We did not find a site-local address, but we found some other non-loopback address. // Server might have a non-site-local address assigned to its NIC (or it might be running // IPv6 which deprecates the "site-local" concept). // Return this non-loopback candidate address... return candidateAddress; } // At this point, we did not find a non-loopback address. // Fall back to returning whatever InetAddress.getLocalHost() returns... InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); if (jdkSuppliedAddress == null) { throw new UnknownHostException( "The JDK InetAddress.getLocalHost() method unexpectedly returned null."); } return jdkSuppliedAddress; } catch (Exception e) { UnknownHostException unknownHostException = new UnknownHostException( "Failed to determine LAN address: " + e); unknownHostException.initCause(e); throw unknownHostException; } }
From source file:org.peercast.core.PeerCastServiceController.java
private String getIpAddress() { Enumeration<NetworkInterface> netIFs; try {/*w w w. j a v a 2 s .c o m*/ netIFs = NetworkInterface.getNetworkInterfaces(); while (netIFs.hasMoreElements()) { NetworkInterface netIF = netIFs.nextElement(); Enumeration<InetAddress> ipAddrs = netIF.getInetAddresses(); while (ipAddrs.hasMoreElements()) { InetAddress ip = ipAddrs.nextElement(); if (!ip.isLoopbackAddress() && !ip.isLinkLocalAddress() && ip.isSiteLocalAddress()) { String ipStr = ip.getHostAddress().toString(); Log.d(TAG, "IP: " + ipStr); return ipStr; } } } } catch (SocketException e) { e.printStackTrace(); } return null; }
From source file:com.ghgande.j2mod.modbus.utils.TestUtils.java
/** * Returns the last adapter it finds that is not a loopback * * @return Adapter to use//w ww . j av a 2 s.com */ public static List<NetworkInterface> getNetworkAdapters() { List<NetworkInterface> returnValue = new ArrayList<NetworkInterface>(); try { // Loop round all the adapters Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { // Get the MAC address if it exists NetworkInterface network = networkInterfaces.nextElement(); byte[] mac = network.getHardwareAddress(); if (mac != null && mac.length > 0 && network.getInterfaceAddresses() != null) { returnValue.add(network); logger.debug("Current MAC address : {} ({})", returnValue, network.getDisplayName()); } } } catch (Exception e) { logger.error("Cannot determine the local MAC address - {}", e.getMessage()); } return returnValue; }
From source file:com.sixt.service.framework.registry.consul.RegistrationManager.java
private void updateIpAddress() { try {/*from www . j a v a2s. c o m*/ Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces(); ipAddress = null; while (b.hasMoreElements()) { NetworkInterface iface = b.nextElement(); if (iface.getName().startsWith("dock")) { continue; } for (InterfaceAddress f : iface.getInterfaceAddresses()) { if (f.getAddress().isSiteLocalAddress()) { ipAddress = f.getAddress().getHostAddress(); } } } } catch (SocketException e) { e.printStackTrace(); } }
From source file:org.speechforge.zanzibar.sip.SipServer.java
public static InetAddress getLocalHost() throws SocketException, UnknownHostException { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); if (!networkInterface.isLoopback()) { Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); if (inetAddresses.hasMoreElements()) return inetAddresses.nextElement(); }/*from www . j a v a 2s.co m*/ } return InetAddress.getLocalHost(); }
From source file:org.gluu.oxtrust.ldap.cache.service.CacheRefreshTimer.java
private boolean isStartCacheRefresh(CacheRefreshConfiguration cacheRefreshConfiguration, GluuAppliance currentAppliance) { if (!GluuBoolean.ENABLED.equals(currentAppliance.getVdsCacheRefreshEnabled())) { return false; }//from w w w. ja v a2 s . co m long poolingInterval = StringHelper.toInteger(currentAppliance.getVdsCacheRefreshPollingInterval()) * 60 * 1000; if (poolingInterval < 0) { return false; } String cacheRefreshServerIpAddress = currentAppliance.getCacheRefreshServerIpAddress(); if (StringHelper.isEmpty(cacheRefreshServerIpAddress)) { log.debug("There is no master Cache Refresh server"); return false; } // Compare server IP address with cacheRefreshServerIp boolean cacheRefreshServer = false; try { Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface networkInterface : Collections.list(nets)) { Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); for (InetAddress inetAddress : Collections.list(inetAddresses)) { if (StringHelper.equals(cacheRefreshServerIpAddress, inetAddress.getHostAddress())) { cacheRefreshServer = true; break; } } if (cacheRefreshServer) { break; } } } catch (SocketException ex) { log.error("Failed to enumerate server IP addresses", ex); } if (!cacheRefreshServer) { log.debug("This server isn't master Cache Refresh server"); return false; } // Check if cache refresh specific configuration was loaded if (cacheRefreshConfiguration == null) { log.info( "Failed to start cache refresh. Can't loading configuration from oxTrustCacheRefresh.properties"); return false; } long timeDiffrence = System.currentTimeMillis() - this.lastFinishedTime; return timeDiffrence >= poolingInterval; }
From source file:net.pms.newgui.NetworkTab.java
public JComponent build() { FormLayout layout = new FormLayout("left:pref, 2dlu, p, 2dlu , p, 2dlu, p, 2dlu, pref:grow", "p, 0dlu, p, 0dlu, p, 3dlu, p, 3dlu, p, 3dlu,p, 3dlu, p, 15dlu, p, 3dlu,p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p,3dlu, p, 3dlu, p, 15dlu, p,3dlu, p, 3dlu, p, 15dlu, p, 3dlu, p"); PanelBuilder builder = new PanelBuilder(layout); builder.setBorder(Borders.DLU4_BORDER); builder.setOpaque(true);//from w ww.j a v a2s . co m CellConstraints cc = new CellConstraints(); smcheckBox = new JCheckBox(Messages.getString("NetworkTab.3")); smcheckBox.setContentAreaFilled(false); smcheckBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { PMS.getConfiguration().setMinimized((e.getStateChange() == ItemEvent.SELECTED)); } }); if (PMS.getConfiguration().isMinimized()) { smcheckBox.setSelected(true); } JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), cc.xyw(1, 1, 9)); cmp = (JComponent) cmp.getComponent(0); cmp.setFont(cmp.getFont().deriveFont(Font.BOLD)); builder.addLabel(Messages.getString("NetworkTab.0"), cc.xy(1, 7)); final KeyedComboBoxModel kcbm = new KeyedComboBoxModel( new Object[] { "bg", "ca", "zhs", "zht", "cz", "da", "nl", "en", "fi", "fr", "de", "el", "is", "it", "ja", "no", "pl", "pt", "br", "ro", "ru", "sl", "es", "sv" }, new Object[] { "Bulgarian", "Catalan", "Chinese (Simplified)", "Chinese (Traditional)", "Czech", "Danish", "Dutch", "English", "Finnish", "French", "German", "Greek", "Icelandic", "Italian", "Japanese", "Norwegian", "Polish", "Portuguese", "Portuguese (Brazilian)", "Romanian", "Russian", "Slovenian", "Spanish", "Swedish" }); langs = new JComboBox(kcbm); langs.setEditable(false); //langs.setSelectedIndex(0); String defaultLang = null; if (configuration.getLanguage() != null && configuration.getLanguage().length() > 0) { defaultLang = configuration.getLanguage(); } else { defaultLang = Locale.getDefault().getLanguage(); } if (defaultLang == null) { defaultLang = "en"; } kcbm.setSelectedKey(defaultLang); if (langs.getSelectedIndex() == -1) { langs.setSelectedIndex(0); } langs.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { configuration.setLanguage((String) kcbm.getSelectedKey()); } } }); builder.add(langs, cc.xyw(3, 7, 7)); builder.add(smcheckBox, cc.xyw(1, 9, 9)); JButton service = new JButton(Messages.getString("NetworkTab.4")); service.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (PMS.get().installWin32Service()) { JOptionPane.showMessageDialog( (JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())), Messages.getString("NetworkTab.11") + Messages.getString("NetworkTab.12"), "Information", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog( (JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())), Messages.getString("NetworkTab.14"), "Error", JOptionPane.ERROR_MESSAGE); } } }); builder.add(service, cc.xy(1, 11)); if (System.getProperty(LooksFrame.START_SERVICE) != null || !Platform.isWindows()) { service.setEnabled(false); } host = new JTextField(PMS.getConfiguration().getServerHostname()); host.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { configuration.setHostname(host.getText()); PMS.get().getFrame().setReloadable(true); } }); // host.setEnabled( StringUtils.isBlank(configuration.getNetworkInterface())) ; port = new JTextField(configuration.getServerPort() != 5001 ? "" + configuration.getServerPort() : ""); port.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { try { String p = port.getText(); if (StringUtils.isEmpty(p)) { p = "5001"; } int ab = Integer.parseInt(p); configuration.setServerPort(ab); PMS.get().getFrame().setReloadable(true); } catch (NumberFormatException nfe) { } } }); cmp = builder.addSeparator(Messages.getString("NetworkTab.22"), cc.xyw(1, 21, 9)); cmp = (JComponent) cmp.getComponent(0); cmp.setFont(cmp.getFont().deriveFont(Font.BOLD)); ArrayList<String> names = new ArrayList<String>(); names.add(""); ArrayList<String> interfaces = new ArrayList<String>(); interfaces.add(""); Enumeration<NetworkInterface> enm; try { enm = NetworkInterface.getNetworkInterfaces(); while (enm.hasMoreElements()) { NetworkInterface ni = enm.nextElement(); // check for interface has at least one ip address. if (ni.getInetAddresses().hasMoreElements()) { names.add(ni.getName()); String displayName = ni.getDisplayName(); if (displayName == null) { displayName = ni.getName(); } interfaces.add(displayName.trim()); } } } catch (SocketException e1) { logger.error(null, e1); } final KeyedComboBoxModel networkInterfaces = new KeyedComboBoxModel(names.toArray(), interfaces.toArray()); networkinterfacesCBX = new JComboBox(networkInterfaces); networkInterfaces.setSelectedKey(configuration.getNetworkInterface()); networkinterfacesCBX.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { configuration.setNetworkInterface((String) networkInterfaces.getSelectedKey()); //host.setEnabled( StringUtils.isBlank(configuration.getNetworkInterface())) ; PMS.get().getFrame().setReloadable(true); } } }); ip_filter = new JTextField(PMS.getConfiguration().getIpFilter()); ip_filter.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { configuration.setIpFilter(ip_filter.getText()); PMS.get().getFrame().setReloadable(true); } }); builder.addLabel(Messages.getString("NetworkTab.20"), cc.xy(1, 23)); builder.add(networkinterfacesCBX, cc.xyw(3, 23, 7)); builder.addLabel(Messages.getString("NetworkTab.23"), cc.xy(1, 25)); builder.add(host, cc.xyw(3, 25, 7)); builder.addLabel(Messages.getString("NetworkTab.24"), cc.xy(1, 27)); builder.add(port, cc.xyw(3, 27, 7)); builder.addLabel(Messages.getString("NetworkTab.30"), cc.xy(1, 29)); builder.add(ip_filter, cc.xyw(3, 29, 7)); cmp = builder.addSeparator(Messages.getString("NetworkTab.31"), cc.xyw(1, 31, 9)); cmp = (JComponent) cmp.getComponent(0); cmp.setFont(cmp.getFont().deriveFont(Font.BOLD)); newHTTPEngine = new JCheckBox(Messages.getString("NetworkTab.32")); newHTTPEngine.setSelected(PMS.getConfiguration().isHTTPEngineV2()); newHTTPEngine.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { PMS.getConfiguration().setHTTPEngineV2((e.getStateChange() == ItemEvent.SELECTED)); } }); builder.add(newHTTPEngine, cc.xyw(1, 33, 9)); preventSleep = new JCheckBox(Messages.getString("NetworkTab.33")); preventSleep.setSelected(PMS.getConfiguration().isPreventsSleep()); preventSleep.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { PMS.getConfiguration().setPreventsSleep((e.getStateChange() == ItemEvent.SELECTED)); } }); builder.add(preventSleep, cc.xyw(1, 35, 9)); cmp = builder.addSeparator(Messages.getString("NetworkTab.34"), cc.xyw(1, 37, 9)); cmp = (JComponent) cmp.getComponent(0); cmp.setFont(cmp.getFont().deriveFont(Font.BOLD)); JPanel panel = builder.getPanel(); JScrollPane scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); return scrollPane; }
From source file:org.basdroid.common.NetworkUtils.java
/** * Returns MAC address of the given interface name. * @param interfaceName eth0, wlan0 or NULL=use first interface * @return mac address or empty string/* w w w . j av a 2s. co m*/ */ public static String getMACAddress(String interfaceName) { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { if (interfaceName != null) { Log.d(TAG, "intf.getName() = " + intf.getName()); if (!intf.getName().equalsIgnoreCase(interfaceName)) continue; } byte[] mac = intf.getHardwareAddress(); if (mac == null) return ""; StringBuilder buf = new StringBuilder(); for (int idx = 0; idx < mac.length; idx++) { buf.append(String.format("%02X:", mac[idx])); } if (buf.length() > 0) buf.deleteCharAt(buf.length() - 1); return buf.toString(); } } catch (Exception ex) { } // for now eat exceptions return ""; }
From source file:net.sbbi.upnp.Discovery.java
private static UPNPRootDevice[] discoverDevices(int timeOut, int ttl, int mx, String searchTarget, NetworkInterface ni) throws IOException { if (searchTarget == null || searchTarget.trim().length() == 0) { throw new IllegalArgumentException("Illegal searchTarget"); }// www. jav a 2 s .c o m final Map devices = new HashMap(); DiscoveryResultsHandler handler = new DiscoveryResultsHandler() { public void discoveredDevice(String usn, String udn, String nt, String maxAge, URL location, String firmware) { synchronized (devices) { if (!devices.containsKey(usn)) { try { UPNPRootDevice device = new UPNPRootDevice(location, maxAge, firmware, usn, udn); devices.put(usn, device); } catch (Exception ex) { log.error("Error occured during upnp root device object creation from location " + location, ex); } } } } }; DiscoveryListener.getInstance().registerResultsHandler(handler, searchTarget); if (ni == null) { for (Enumeration e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) { NetworkInterface intf = (NetworkInterface) e.nextElement(); for (Enumeration adrs = intf.getInetAddresses(); adrs.hasMoreElements();) { InetAddress adr = (InetAddress) adrs.nextElement(); if (adr instanceof Inet4Address && !adr.isLoopbackAddress()) { sendSearchMessage(adr, ttl, mx, searchTarget); } } } } else { for (Enumeration adrs = ni.getInetAddresses(); adrs.hasMoreElements();) { InetAddress adr = (InetAddress) adrs.nextElement(); if (adr instanceof Inet4Address && !adr.isLoopbackAddress()) { sendSearchMessage(adr, ttl, mx, searchTarget); } } } try { Thread.sleep(timeOut); } catch (InterruptedException ex) { // don't care } DiscoveryListener.getInstance().unRegisterResultsHandler(handler, searchTarget); if (devices.size() == 0) { return null; } int j = 0; UPNPRootDevice[] rootDevices = new UPNPRootDevice[devices.size()]; for (Iterator i = devices.values().iterator(); i.hasNext();) { rootDevices[j++] = (UPNPRootDevice) i.next(); } return rootDevices; }
From source file:com.cellbots.httpserver.HttpCommandServer.java
public String getLocalIpAddress() { try {/*from w w w. j av a2s . c om*/ 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()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { Log.e("", ex.toString()); } return null; }