List of usage examples for java.net NetworkInterface getInetAddresses
public Enumeration<InetAddress> getInetAddresses()
From source file:com.oneops.inductor.Config.java
/** * Retruns the inductor IP address (IPV4 address). If there are multiple * NICs/IfAddresses, it selects the first one. Openstack VMs normally has * only one network interface (eth0).//w ww . jav a2 s . c o m * * @return IPV4 address of inductor with interface name. Returns * <code>null</code> if it couldn't find anything. */ private String getInductorIPv4Addr() { try { Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); while (nics.hasMoreElements()) { NetworkInterface nic = nics.nextElement(); if (nic.isUp() && !nic.isLoopback()) { Enumeration<InetAddress> addrs = nic.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress add = addrs.nextElement(); // Print only IPV4 address if (add instanceof Inet4Address && !add.isLoopbackAddress()) { // Log the first one. String ip = add.getHostAddress() + " (" + nic.getDisplayName() + ")"; logger.info("Inductor IP : " + ip); return ip; } } } } } catch (Exception e) { logger.warn("Error getting inductor IP address", e); // Skip any errors } return null; }
From source file:org.springframework.cloud.commons.util.InetUtils.java
public InetAddress findFirstNonLoopbackAddress() { InetAddress result = null;/*from ww w .j a v a 2 s . c o m*/ try { int lowest = Integer.MAX_VALUE; for (Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); nics .hasMoreElements();) { NetworkInterface ifc = nics.nextElement(); if (ifc.isUp()) { log.trace("Testing interface: " + ifc.getDisplayName()); if (ifc.getIndex() < lowest || result == null) { lowest = ifc.getIndex(); } else if (result != null) { continue; } // @formatter:off if (!ignoreInterface(ifc.getDisplayName())) { for (Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements();) { InetAddress address = addrs.nextElement(); if (address instanceof Inet4Address && !address.isLoopbackAddress() && !ignoreAddress(address)) { log.trace("Found non-loopback interface: " + ifc.getDisplayName()); result = address; } } } // @formatter:on } } } catch (IOException ex) { log.error("Cannot get first non-loopback address", ex); } if (result != null) { return result; } try { return InetAddress.getLocalHost(); } catch (UnknownHostException e) { log.warn("Unable to retrieve localhost"); } return null; }
From source file:org.opendaylight.ovsdb.southbound.transactions.md.OvsdbBridgeUpdateCommandTest.java
@SuppressWarnings("unchecked") @Test/*from ww w . jav a 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:org.opendaylight.netvirt.openstack.netvirt.impl.BridgeConfigurationManagerImpl.java
private String getLocalControllerHostIpAddress() { String ipaddress = null;//from w ww. j a v a2 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:sce.RESTAppMetricJob.java
public void sendEmail(JobExecutionContext context, String email) throws JobExecutionException { try {/*from w w w .j a va2s .co m*/ Date d = new Date(); String message = "Job was executed at: " + d.toString() + "\n"; SchedulerMetaData schedulerMetadata = context.getScheduler().getMetaData(); //Get the scheduler instance id message += "Scheduler Instance Id: " + schedulerMetadata.getSchedulerInstanceId() + "\n"; //Get the scheduler name message += "Scheduler Name: " + schedulerMetadata.getSchedulerName() + "\n"; try { //Get the scheduler ip Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces(); message += "Scheduler IP: "; for (; n.hasMoreElements();) { NetworkInterface e = n.nextElement(); //System.out.println("Interface: " + e.getName()); Enumeration<InetAddress> a = e.getInetAddresses(); for (; a.hasMoreElements();) { InetAddress addr = a.nextElement(); message += !addr.getHostAddress().equals("127.0.0.1") ? addr.getHostAddress() + " " : ""; } } message += "\n"; } catch (SocketException e) { throw new JobExecutionException(e); } //Returns the result (if any) that the Job set before its execution completed (the type of object set as the result is entirely up to the particular job). //The result itself is meaningless to Quartz, but may be informative to JobListeners or TriggerListeners that are watching the job's execution. message += "Result: " + (context.getResult() != null ? context.getResult() : "") + "\n"; //Get the unique Id that identifies this particular firing instance of the trigger that triggered this job execution. It is unique to this JobExecutionContext instance as well. message += "Fire Instance Id: " + (context.getFireInstanceId() != null ? context.getFireInstanceId() : "") + "\n"; //Get a handle to the Calendar referenced by the Trigger instance that fired the Job. message += "Calendar: " + (context.getCalendar() != null ? context.getCalendar().getDescription() : "") + "\n"; //The actual time the trigger fired. For instance the scheduled time may have been 10:00:00 but the actual fire time may have been 10:00:03 if the scheduler was too busy. message += "Fire Time: " + (context.getFireTime() != null ? context.getFireTime() : "") + "\n"; //the job name message += "Job Name: " + (context.getJobDetail().getKey() != null ? context.getJobDetail().getKey().getName() : "") + "\n"; //the job group message += "Job Group: " + (context.getJobDetail().getKey() != null ? context.getJobDetail().getKey().getGroup() : "") + "\n"; //The amount of time the job ran for (in milliseconds). The returned value will be -1 until the job has actually completed (or thrown an exception), and is therefore generally only useful to JobListeners and TriggerListeners. //message += "RunTime: " + context.getJobRunTime() + "\n"; //the next fire time message += "Next Fire Time: " + (context.getNextFireTime() != null && context.getNextFireTime().toString() != null ? context.getNextFireTime().toString() : "") + "\n"; //the previous fire time message += "Previous Fire Time: " + (context.getPreviousFireTime() != null && context.getPreviousFireTime().toString() != null ? context.getPreviousFireTime().toString() : "") + "\n"; //refire count message += "Refire Count: " + context.getRefireCount() + "\n"; //job data map message += "\nJob data map: \n"; JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); for (Map.Entry<String, Object> entry : jobDataMap.entrySet()) { message += entry.getKey() + " = " + entry.getValue() + "\n"; } Mail.sendMail("SCE notification", message, email, null, null); } catch (SchedulerException e) { throw new JobExecutionException(e); } }
From source file:org.apache.geode.internal.net.SocketCreator.java
/** * returns a set of the non-loopback InetAddresses for this machine *//*w w w . j a va 2 s. c om*/ public static Set<InetAddress> getMyAddresses() { Set<InetAddress> result = new HashSet<InetAddress>(); Set<InetAddress> locals = new HashSet<InetAddress>(); Enumeration<NetworkInterface> interfaces; try { interfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { throw new IllegalArgumentException( LocalizedStrings.StartupMessage_UNABLE_TO_EXAMINE_NETWORK_INTERFACES.toLocalizedString(), e); } while (interfaces.hasMoreElements()) { NetworkInterface face = interfaces.nextElement(); boolean faceIsUp = false; try { faceIsUp = face.isUp(); } catch (SocketException e) { InternalDistributedSystem ids = InternalDistributedSystem.getAnyInstance(); if (ids != null) { logger.info("Failed to check if network interface is up. Skipping {}", face, e); } } if (faceIsUp) { Enumeration<InetAddress> addrs = face.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr = addrs.nextElement(); if (addr.isLoopbackAddress() || addr.isAnyLocalAddress() || (!useLinkLocalAddresses && addr.isLinkLocalAddress())) { locals.add(addr); } else { result.add(addr); } } // while } } // while // fix for bug #42427 - allow product to run on a standalone box by using // local addresses if there are no non-local addresses available if (result.size() == 0) { return locals; } else { return result; } }
From source file:cn.apputest.ctria.section2.Lucha2Activity.java
public String getLocalIpAddressGPRS() { try {/*from www .j av a2 s .c o m*/ 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("WifiPreferenceIpAddress", "ex.toString()"); } return null; }
From source file:com.cloud.utils.net.NetUtils.java
public static InetAddress[] getAllLocalInetAddresses() { final List<InetAddress> addrList = new ArrayList<InetAddress>(); try {//from ww w. j a v a 2 s. co m for (final NetworkInterface ifc : IteratorUtil .enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) { if (ifc.isUp() && !ifc.isVirtual()) { for (final InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) { addrList.add(addr); } } } } catch (final SocketException e) { s_logger.warn("SocketException in getAllLocalInetAddresses().", e); } final InetAddress[] addrs = new InetAddress[addrList.size()]; if (addrList.size() > 0) { System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size()); } return addrs; }
From source file:com.att.android.arodatacollector.utils.AROCollectorUtils.java
/** * Returns the IP Address of the device during the trace cycle when it is * connected to the network./* ww w.j a v a2 s . co m*/ * * @return The IP Address of the device. * * @throws java.net.SocketException */ public String getLocalIpAddress() throws SocketException { for (final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { final NetworkInterface intf = en.nextElement(); for (final Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { final InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress(); } } } return null; }
From source file:info.pancancer.arch3.worker.WorkerRunnable.java
/** * Get the IP address of this machine, preference is given to returning an IPv4 address, if there is one. * * @return An InetAddress object./*from w ww. j a v a2s . c o m*/ * @throws SocketException */ public InetAddress getFirstNonLoopbackAddress() throws SocketException { final String dockerInterfaceName = "docker"; for (NetworkInterface i : Collections.list(NetworkInterface.getNetworkInterfaces())) { if (i.getName().contains(dockerInterfaceName)) { // the virtual ip address for the docker mount is useless but is not a loopback address continue; } log.info("Examining " + i.getName()); for (InetAddress addr : Collections.list(i.getInetAddresses())) { if (!addr.isLoopbackAddress()) { // Prefer IP v4 if (addr instanceof Inet4Address) { return addr; } } } } Log.info("Could not find an ipv4 address"); for (NetworkInterface i : Collections.list(NetworkInterface.getNetworkInterfaces())) { log.info("Examining " + i.getName()); if (i.getName().contains(dockerInterfaceName)) { // the virtual ip address for the docker mount is useless but is not a loopback address continue; } // If we got here it means we never found an IP v4 address, so we'll have to return the IPv6 address. for (InetAddress addr : Collections.list(i.getInetAddresses())) { // InetAddress addr = (InetAddress) en2.nextElement(); if (!addr.isLoopbackAddress()) { return addr; } } } return null; }