List of usage examples for java.net NetworkInterface getInetAddresses
public Enumeration<InetAddress> getInetAddresses()
From source file:de.micromata.mgc.application.webserver.config.JettyConfigTabController.java
private List<String> getListenHosts() { List<String> ret = new ArrayList<>(); try {//w w w .jav a2 s.c om Enumeration e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface n = (NetworkInterface) e.nextElement(); if (n.isUp() == false) { continue; } Enumeration ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); // ret.add(i.getHostName()); ret.add(i.getHostAddress()); // System.out.println(i.getHostAddress()); } } } catch (Exception ex) { ValMessage vm = new ValMessage(ValState.Error, ""); vm.setMessage("Error retriving hosts: " + ex.getMessage()); addToFeedback(vm); } return ret; }
From source file:com.hypersocket.netty.NettyServer.java
protected void bindInterface(Integer port, Set<Channel> channels) throws IOException { Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); Set<String> interfacesToBind = new HashSet<String>( Arrays.asList(configurationService.getValues("listening.interfaces"))); if (interfacesToBind.isEmpty()) { if (log.isInfoEnabled()) { log.info("Binding server to all interfaces on port " + port); }//from ww w . ja va 2 s.c o m Channel ch = serverBootstrap.bind(new InetSocketAddress(port)); channels.add(ch); if (log.isInfoEnabled()) { log.info("Bound to port " + ((InetSocketAddress) ch.getLocalAddress()).getPort()); } } else { while (e.hasMoreElements()) { NetworkInterface i = e.nextElement(); Enumeration<InetAddress> inetAddresses = i.getInetAddresses(); for (InetAddress inetAddress : Collections.list(inetAddresses)) { if (interfacesToBind.contains(inetAddress.getHostAddress())) { try { if (log.isInfoEnabled()) { log.info("Binding server to interface " + i.getDisplayName() + " " + inetAddress.getHostAddress() + ":" + port); } Channel ch = serverBootstrap.bind(new InetSocketAddress(inetAddress, port)); channels.add(ch); if (log.isInfoEnabled()) { log.info("Bound to " + inetAddress.getHostAddress() + ":" + ((InetSocketAddress) ch.getLocalAddress()).getPort()); } } catch (ChannelException ex) { log.error("Failed to bind port", ex); } } } } } }
From source file:edu.ucsb.eucalyptus.ic.WalrusReplyQueue.java
public void handle(ExceptionMessage muleMsg) { try {// w w w . j a v a 2 s .c o m Object requestMsg = muleMsg.getPayload(); String requestString = requestMsg.toString(); EucalyptusMessage msg = (EucalyptusMessage) BindingManager.getBinding("msgs_eucalyptus_ucsb_edu") .fromOM(requestString); Throwable ex = muleMsg.getException().getCause(); EucalyptusMessage errMsg; String ipAddr = "127.0.0.1"; List<NetworkInterface> ifaces = null; try { ifaces = Collections.list(NetworkInterface.getNetworkInterfaces()); } catch (SocketException e1) { } for (NetworkInterface iface : ifaces) { try { if (!iface.isLoopback() && !iface.isVirtual() && iface.isUp()) { for (InetAddress iaddr : Collections.list(iface.getInetAddresses())) { if (!iaddr.isSiteLocalAddress() && !(iaddr instanceof Inet6Address)) { ipAddr = iaddr.getHostAddress(); break; } } } } catch (SocketException e1) { } } if (ex instanceof NoSuchBucketException) { errMsg = new WalrusBucketErrorMessageType(((NoSuchBucketException) ex).getBucketName(), "NoSuchBucket", "The specified bucket was not found", HttpStatus.SC_NOT_FOUND, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof AccessDeniedException) { errMsg = new WalrusBucketErrorMessageType(((AccessDeniedException) ex).getBucketName(), "AccessDenied", "No U", HttpStatus.SC_FORBIDDEN, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof NotAuthorizedException) { errMsg = new WalrusBucketErrorMessageType(((NotAuthorizedException) ex).getValue(), "Unauthorized", "No U", HttpStatus.SC_UNAUTHORIZED, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof BucketAlreadyOwnedByYouException) { errMsg = new WalrusBucketErrorMessageType(((BucketAlreadyOwnedByYouException) ex).getBucketName(), "BucketAlreadyOwnedByYou", "Your previous request to create the named bucket succeeded and you already own it.", HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof BucketAlreadyExistsException) { errMsg = new WalrusBucketErrorMessageType(((BucketAlreadyExistsException) ex).getBucketName(), "BucketAlreadyExists", "The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.", HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof BucketNotEmptyException) { errMsg = new WalrusBucketErrorMessageType(((BucketNotEmptyException) ex).getBucketName(), "BucketNotEmpty", "The bucket you tried to delete is not empty.", HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof PreconditionFailedException) { errMsg = new WalrusBucketErrorMessageType(((PreconditionFailedException) ex).getPrecondition(), "PreconditionFailed", "At least one of the pre-conditions you specified did not hold.", HttpStatus.SC_PRECONDITION_FAILED, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof NotModifiedException) { errMsg = new WalrusBucketErrorMessageType(((NotModifiedException) ex).getPrecondition(), "NotModified", "Object Not Modified", HttpStatus.SC_NOT_MODIFIED, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof TooManyBucketsException) { errMsg = new WalrusBucketErrorMessageType(((TooManyBucketsException) ex).getBucketName(), "TooManyBuckets", "You have attempted to create more buckets than allowed.", HttpStatus.SC_BAD_REQUEST, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof EntityTooLargeException) { errMsg = new WalrusBucketErrorMessageType(((EntityTooLargeException) ex).getEntityName(), "EntityTooLarge", "Your proposed upload exceeds the maximum allowed object size.", HttpStatus.SC_BAD_REQUEST, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof NoSuchEntityException) { errMsg = new WalrusBucketErrorMessageType(((NoSuchEntityException) ex).getBucketName(), "NoSuchEntity", "The specified entity was not found", HttpStatus.SC_NOT_FOUND, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof DecryptionFailedException) { errMsg = new WalrusBucketErrorMessageType(((DecryptionFailedException) ex).getValue(), "Decryption Failed", "Fail", SC_DECRYPTION_FAILED, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof ImageAlreadyExistsException) { errMsg = new WalrusBucketErrorMessageType(((ImageAlreadyExistsException) ex).getValue(), "Image Already Exists", "Fail", HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof NotImplementedException) { errMsg = new WalrusBucketErrorMessageType(((NotImplementedException) ex).getValue(), "Not Implemented", "NA", HttpStatus.SC_NOT_IMPLEMENTED, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else { errMsg = new EucalyptusErrorMessageType(muleMsg.getComponentName(), msg, ex.getMessage()); } replies.putMessage(errMsg); } catch (Exception e) { LOG.error(e, e); } }
From source file:ws.argo.BrowserWeb.BrowserWebController.java
private Properties getPropeGeneratorProps() throws UnknownHostException { if (pgProps != null) return pgProps; InputStream in = getPropertiesFileInputStream(); pgProps = new Properties(); if (in != null) { try {//from ww w .j a va 2s.c o m pgProps.load(in); } catch (IOException e) { // TODO Auto-generated catch block // Should log the props file issue setDefaultProbeGeneratorProperties(pgProps); } } if (pgProps.getProperty("listenerIPAddress", "").equals("")) { // If the listenerIPAddress is blank, then try to get the ip address of the interface String hostIPAddr = null; try { NetworkInterface n = NetworkInterface .getByName(pgProps.getProperty("listenerInterfaceName", "en0")); if (!n.isLoopback()) { Enumeration ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); hostIPAddr = i.getHostName(); System.out.println(hostIPAddr); } } } catch (SocketException e) { System.out.println("A socket exception occurred."); } if (hostIPAddr == null) { hostIPAddr = InetAddress.getLocalHost().getHostName(); System.out.println("Defaulting to local address: " + hostIPAddr); } pgProps.put("listenerIPAddress", hostIPAddr); } return pgProps; }
From source file:io.tilt.minka.domain.NetworkShardIDImpl.java
private InetAddress findSiteAddress(final Config config) { InetAddress fallback = null;/* ww w .j a v a 2s . c o m*/ try { final String niName = config.getFollowerUseNetworkInterfase(); logger.info("{}: Looking for configured network interfase: {}", getClass().getSimpleName(), niName); final Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); while (nis.hasMoreElements()) { final NetworkInterface ni = nis.nextElement(); if (niName.contains(ni.getName())) { logger.info("{}: Interfase found: {}, looking for a Site address..", getClass().getSimpleName(), ni.getName()); final Enumeration<InetAddress> ias = ni.getInetAddresses(); while (ias.hasMoreElements()) { final InetAddress ia = ias.nextElement(); if (ia.isSiteLocalAddress()) { logger.info("{}: Host site address found: {}:{} with HostName {}", getClass().getSimpleName(), ia.getHostAddress(), config.getBrokerServerPort(), ia.getHostName()); return ia; } else { fallback = ia; logger.warn("{}: Specified interfase: {} is not a site address!!, " + "you should specify a non local-only valid interfase !! where's your lan?", getClass().getSimpleName(), ia.getHostAddress()); } } } } } catch (Exception e) { logger.error("{}: Cannot build shard id value with hostname", getClass().getSimpleName(), e); } logger.error("{}: Site network interfase not found !", getClass().getSimpleName()); return fallback; }
From source file:org.apache.spark.simr.Simr.java
/** * @return The IP of the first network interface on this machine as a string, null in the case * of an exception from the underlying network interface. *///from ww w. ja v a 2 s .c o m public String getLocalIP() { String ip; int pickIfaceNum = conf.getInt("simr_interface", 0); int currIface = 0; try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface iface = interfaces.nextElement(); if (iface.isLoopback() || !iface.isUp()) continue; if (currIface++ >= pickIfaceNum) { Enumeration<InetAddress> addresses = iface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); if (addr instanceof Inet4Address) { ip = addr.getHostAddress(); return ip; } } } } } catch (SocketException e) { throw new RuntimeException(e); } return null; }
From source file:org.apache.marmotta.platform.security.services.SecurityServiceImpl.java
/** * Parse host patterns into subnet information. A host pattern has one of the following forms: * <ul>/*from w w w . j a va 2 s. c o m*/ * <li>LOCAL, meaning all local interfaces</li> * <li>x.x.x.x/yy, meaning an IPv4 CIDR address with netmask (number of bits significant for the network, max 32), e.g. 192.168.100.0/24 </li> * <li>xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/yy, meaning an IPv6 CIDR address with netmask (prefix length, max 128)</li> * </ul> * @param hostPatternStrings * @return */ private Set<SubnetInfo> parseHostAddresses(List<String> hostPatternStrings) { HashSet<SubnetInfo> hostPatterns = new HashSet<SubnetInfo>(); for (String host : hostPatternStrings) { try { // reserved name: LOCAL maps to all local addresses if ("LOCAL".equalsIgnoreCase(host)) { try { Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces(); while (ifs.hasMoreElements()) { NetworkInterface iface = ifs.nextElement(); Enumeration<InetAddress> addrs = iface.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr = addrs.nextElement(); try { hostPatterns.add(SubnetInfo.getSubnetInfo(addr)); } catch (UnknownHostException e) { log.warn("could not parse interface address: {}", e.getMessage()); } } } } catch (SocketException ex) { log.warn("could not determine local IP addresses, will use 127.0.0.1/24"); try { hostPatterns.add(SubnetInfo.getSubnetInfo("127.0.0.1/24")); // IPv4 hostPatterns.add(SubnetInfo.getSubnetInfo("::1/128")); // IPv6 } catch (UnknownHostException e) { log.error("could not parse localhost address: {}", e.getMessage()); } } } else if (host.matches("^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+\\./[0-9]+$")) { // CIDR notation try { hostPatterns.add(SubnetInfo.getSubnetInfo(host)); } catch (UnknownHostException e) { log.warn("could not parse host specification '{}': {}", host, e.getMessage()); } } else if (host.matches("^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$")) { // IP address try { hostPatterns.add(SubnetInfo.getSubnetInfo(host + "/32")); } catch (UnknownHostException e) { log.warn("could not parse host specification '{}': {}", host, e.getMessage()); } } else if (IPAddressUtil.isIPv6LiteralAddress(host)) { // IPv6 address try { hostPatterns.add(SubnetInfo.getSubnetInfo(host)); } catch (UnknownHostException e) { log.warn("could not parse host specification '{}': {}", host, e.getMessage()); } } else { log.warn( "invalid host name specification: {}; please use either CIDR u.v.w.x/zz notation or the keyword LOCAL", host); } } catch (IllegalArgumentException ex) { log.warn("illegal host specification for security constraint {}; not in CIDR notation!", host); } } return hostPatterns; }
From source file:org.graphwalker.Util.java
protected static InetAddress getInternetAddr(final String nic) { // Find the real network interface NetworkInterface iface = null; InetAddress ia = null;/* w ww. ja v a 2 s . c o m*/ boolean foundNIC = false; try { for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces .hasMoreElements() && foundNIC == false;) { iface = ifaces.nextElement(); Util.logger.debug("Interface: " + iface.getDisplayName()); for (Enumeration<InetAddress> ips = iface.getInetAddresses(); ips.hasMoreElements() && foundNIC == false;) { ia = ips.nextElement(); Util.logger.debug(ia.getCanonicalHostName() + " " + ia.getHostAddress()); if (!ia.isLoopbackAddress()) { Util.logger.debug(" Not a loopback address..."); if (!ia.getHostAddress().contains(":") && nic.equals(iface.getDisplayName())) { Util.logger.debug(" Host address does not contain ':'"); Util.logger.debug(" Interface: " + iface.getName() + " seems to be InternetInterface. I'll take it..."); foundNIC = true; } } } } } catch (SocketException e) { Util.logger.error(e.getMessage()); } finally { if (!foundNIC && nic != null) { Util.logger.error("Could not bind to network interface: " + nic); throw new RuntimeException("Could not bind to network interface: " + nic); } else if (!foundNIC) { Util.logger.error("Could not bind to any network interface"); throw new RuntimeException("Could not bind to any network interface: "); } } return ia; }
From source file:com.singularityeye.eyetrack.MapsActivity.java
private String getHostAddress() { try {//from w w w . java 2s . c om // iterate over interfaces for (Enumeration<NetworkInterface> networkInterfaces = NetworkInterface .getNetworkInterfaces(); networkInterfaces.hasMoreElements();) { NetworkInterface nextInterface = networkInterfaces.nextElement(); // iterate over ip addresses (note: one interface could have more than one ip address) for (Enumeration<InetAddress> ipAddresses = nextInterface.getInetAddresses(); ipAddresses .hasMoreElements();) { InetAddress nextIpAddress = ipAddresses.nextElement(); // get an IPv4 address if (!nextIpAddress.isLoopbackAddress() && nextIpAddress instanceof Inet4Address) { return nextIpAddress.getHostAddress(); // get first ip address } } } } catch (SocketException e) { Log.e("ERROR", "GetHostAddressException: " + e.getMessage()); } return null; }
From source file:com.adamkruger.myipaddressinfo.NetworkInfoFragment.java
@TargetApi(Build.VERSION_CODES.GINGERBREAD) private static List<NetworkInterfaceInfo> getNetworkInterfaceInfos() { List<NetworkInterfaceInfo> networkInterfaceInfos = new ArrayList<NetworkInterfaceInfo>(); try {/*from w w w . j ava2 s . c o m*/ List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface networkInterface : interfaces) { NetworkInterfaceInfo networkInterfaceInfo = new NetworkInterfaceInfo(); networkInterfaceInfo.name = networkInterface.getDisplayName(); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) { byte[] MAC = networkInterface.getHardwareAddress(); if (MAC != null) { StringBuilder stringBuilder = new StringBuilder(18); for (byte b : MAC) { if (stringBuilder.length() > 0) { stringBuilder.append(':'); } stringBuilder.append(String.format("%02x", b)); } networkInterfaceInfo.MAC = stringBuilder.toString(); } networkInterfaceInfo.MTU = networkInterface.getMTU(); } List<InetAddress> addresses = Collections.list(networkInterface.getInetAddresses()); for (InetAddress address : addresses) { if (!address.isLoopbackAddress()) { networkInterfaceInfo.ipAddresses.add(InetAddressToString(address)); } } if (networkInterfaceInfo.ipAddresses.size() > 0) { networkInterfaceInfos.add(networkInterfaceInfo); } } } catch (SocketException e) { } return networkInterfaceInfos; }