List of usage examples for java.net InetAddress getAllByName
public static InetAddress[] getAllByName(String host) throws UnknownHostException
From source file:org.apache.ogt.http.impl.conn.DefaultClientConnectionOperator.java
/** * Resolves the given host name to an array of corresponding IP addresses, based on the * configured name service on the system. * * @param host host name to resolve//from w ww . j a va 2s . c om * @return array of IP addresses * @exception UnknownHostException if no IP address for the host could be determined. * * @since 4.1 */ protected InetAddress[] resolveHostname(final String host) throws UnknownHostException { return InetAddress.getAllByName(host); }
From source file:com.couchbase.cbadmin.client.CouchbaseAdmin.java
private static Inet4Address getIp4Lookup(String host) throws RestApiException { Inet4Address inaddr = null;/* w w w . j av a 2s.c o m*/ InetAddress[] addrList; try { addrList = InetAddress.getAllByName(host); } catch (UnknownHostException ex) { throw new RestApiException(ex); } for (InetAddress addr : addrList) { if (addr instanceof Inet4Address) { inaddr = (Inet4Address) addr; break; } } if (inaddr == null) { throw new RestApiException("Couldn't get IPv4 address"); } return inaddr; }
From source file:org.alfresco.filesys.auth.PassthruServerFactory.java
public void afterPropertiesSet() throws InvalidConfigurationException { // Check if the offline check interval has been specified if (this.offlineCheckInterval != null) { // Range check the value if (this.offlineCheckInterval < MinCheckInterval || this.offlineCheckInterval > MaxCheckInterval) throw new InvalidConfigurationException("Invalid offline check interval, valid range is " + MinCheckInterval + " to " + MaxCheckInterval); // Set the offline check interval for offline passthru servers passthruServers = new PassthruServers(this.offlineCheckInterval); // DEBUG// w w w . j av a 2s . co m if (logger.isDebugEnabled()) logger.debug("Using offline check interval of " + this.offlineCheckInterval + " seconds"); } else { // Create the passthru server list with the default offline check interval passthruServers = new PassthruServers(); } // Propagate the debug setting if (logger.isDebugEnabled()) passthruServers.setDebug(true); // Check if the session timeout has been specified if (this.timeout != null) { // Range check the timeout if (this.timeout < MinSessionTmo || this.timeout > MaxSessionTmo) throw new InvalidConfigurationException( "Invalid session timeout, valid range is " + MinSessionTmo + " to " + MaxSessionTmo); // Set the session timeout for connecting to an authentication server passthruServers.setConnectionTimeout(this.timeout); } passthruServers.setNullDomainUseAnyServer(this.nullDomainUseAnyServer); // Check if a server name has been specified String srvList = null; if (localServer) { try { // Get the list of local network addresses InetAddress[] localAddrs = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName()); // Build the list of local addresses if (localAddrs != null && localAddrs.length > 0) { StringBuilder addrStr = new StringBuilder(); for (InetAddress curAddr : localAddrs) { if (curAddr.isLoopbackAddress() == false) { addrStr.append(curAddr.getHostAddress()); addrStr.append(","); } } if (addrStr.length() > 0) addrStr.setLength(addrStr.length() - 1); // Set the server list using the local address list srvList = addrStr.toString(); } else throw new AlfrescoRuntimeException("No local server address(es)"); } catch (UnknownHostException ex) { throw new AlfrescoRuntimeException("Failed to get local address list"); } } if (this.server != null && this.server.length() > 0) { // Check if the server name was already set if (srvList != null) throw new AlfrescoRuntimeException("Set passthru server via local server or specify name"); // Get the passthru authenticator server name srvList = this.server; } // If the passthru server name has been set initialize the passthru connection if (srvList != null) { // Initialize using a list of server names/addresses passthruServers.setServerList(srvList); } else { // Get the domain/workgroup name String domainName = null; // Check if a domain name has been specified if (this.domain != null && this.domain.length() > 0) { // Check if the authentication server has already been set, ie. server name was also specified if (srvList != null) throw new AlfrescoRuntimeException("Specify server or domain name for passthru authentication"); domainName = this.domain; } // If the domain name has been set initialize the passthru connection if (domainName != null) { try { // Initialize using the domain passthruServers.setDomain(domainName); } catch (IOException ex) { throw new AlfrescoRuntimeException("Error setting passthru domain, " + ex.getMessage()); } } } // Check if we have an authentication server if (passthruServers.getTotalServerCount() == 0) throw new AlfrescoRuntimeException("No valid authentication servers found for passthru"); }
From source file:voldemort.server.VoldemortServer.java
/** * Compare the configured hostname with all the ip addresses and hostnames * for the server node, and log a warning if there is a mismatch. * *//*from w w w .j a va 2 s .c o m*/ // TODO: VoldemortServer should throw exception if cluster xml, node id, and // server's state are not all mutually consistent. // // "I attempted to do this in the past. In practice its hard since the // hostname strings returned may not exactly match what's in cluster.xml // (ela4-app0000.prod vs ela4-app0000.prod.linkedin.com). And for folks // running with multiple interfaces and stuff in the open source world, not // sure how it would fan out.. // // I am in favour of doing this though.. May be implement a server config, // "strict.hostname.check.on.startup" which is false by default and true for // our environments and our SRE makes sure there is an exact match?" -- // VChandar // // "Strict host name doesn't work? We can always trim the rest before the comparison." // -- LGao private void checkHostName() { try { HashSet<String> ipAddrList = new HashSet<String>(); InetAddress localhost = InetAddress.getLocalHost(); InetAddress[] serverAddrs = InetAddress.getAllByName(localhost.getCanonicalHostName()); ipAddrList.add("localhost"); if (serverAddrs != null && serverAddrs.length > 0) { for (InetAddress addr : serverAddrs) { if (addr.getHostName() != null) ipAddrList.add(addr.getHostName()); if (addr.getHostAddress() != null) ipAddrList.add(addr.getHostAddress()); if (addr.getCanonicalHostName() != null) ipAddrList.add(addr.getCanonicalHostName()); } } if (!ipAddrList.contains(this.identityNode.getHost())) { logger.info("List of all IPs & Hostnames for the current node:" + ipAddrList); logger.info("Configured hostname [" + this.identityNode.getHost() + "] does not seem to match current node."); } } catch (UnknownHostException uhe) { logger.warn("Unable to obtain IP information for current node", uhe); } catch (SecurityException se) { logger.warn("Security Manager does not permit obtaining IP Information", se); } }
From source file:org.alfresco.repo.security.authentication.ntlm.NTLMAuthenticationProvider.java
/** * Use the local server as the authentication server * //from w w w .ja va 2 s . c om * @param useLocal String */ public final void setUseLocalServer(String useLocal) { // Check if the local server should be used for authentication if (Boolean.parseBoolean(useLocal) == true) { // Check if the passthru server list is already configured if (m_passthruServers.getTotalServerCount() > 0) throw new AlfrescoRuntimeException("Passthru server list already configured"); try { // Get the list of local network addresses InetAddress[] localAddrs = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName()); // Build the list of local addresses if (localAddrs != null && localAddrs.length > 0) { StringBuilder addrStr = new StringBuilder(); for (InetAddress curAddr : localAddrs) { if (curAddr.isLoopbackAddress() == false) { addrStr.append(curAddr.getHostAddress()); addrStr.append(","); } } if (addrStr.length() > 0) addrStr.setLength(addrStr.length() - 1); // Set the server list using the local address list m_passthruServers.setServerList(addrStr.toString()); } else throw new AlfrescoRuntimeException("No local server address(es)"); } catch (UnknownHostException ex) { throw new AlfrescoRuntimeException("Failed to get local address list"); } } }
From source file:org.apache.james.James.java
/** * @see org.apache.avalon.framework.activity.Initializable#initialize() *///ww w . j ava 2s . c o m public void initialize() throws Exception { getLogger().info("JAMES init..."); // TODO: This should retrieve a more specific named thread pool from // Context that is set up in server.xml try { store = (Store) compMgr.lookup(Store.ROLE); } catch (Exception e) { if (getLogger().isWarnEnabled()) { getLogger().warn("Can't get Store: " + e); } } if (getLogger().isDebugEnabled()) { getLogger().debug("Using Store: " + store.toString()); } try { spool = (SpoolRepository) compMgr.lookup(SpoolRepository.ROLE); } catch (Exception e) { if (getLogger().isWarnEnabled()) { getLogger().warn("Can't get spoolRepository: " + e); } } if (getLogger().isDebugEnabled()) { getLogger().debug("Using SpoolRepository: " + spool.toString()); } try { usersStore = (UsersStore) compMgr.lookup(UsersStore.ROLE); } catch (Exception e) { if (getLogger().isWarnEnabled()) { getLogger().warn("Can't get Store: " + e); } } if (getLogger().isDebugEnabled()) { getLogger().debug("Using UsersStore: " + usersStore.toString()); } String hostName = null; try { hostName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException ue) { hostName = "localhost"; } //a context is a hastable that contain (key,value) attributes //think about it as a shared gloabl configuration context = new DefaultContext(); context.put("HostName", hostName); getLogger().info("Local host is: " + hostName); // Get the domains and hosts served by this instance serverNames = new HashSet(); Configuration serverConf = conf.getChild("servernames"); if (serverConf.getAttributeAsBoolean("autodetect") && (!hostName.equals("localhost"))) { serverNames.add(hostName.toLowerCase(Locale.US)); } final Configuration[] serverNameConfs = conf.getChild("servernames").getChildren("servername"); for (int i = 0; i < serverNameConfs.length; i++) { serverNames.add(serverNameConfs[i].getValue().toLowerCase(Locale.US)); if (serverConf.getAttributeAsBoolean("autodetectIP", true)) { try { /* This adds the IP address(es) for each host to support * support <user@address-literal> - RFC 2821, sec 4.1.3. * It might be proper to use the actual IP addresses * available on this server, but we can't do that * without NetworkInterface from JDK 1.4. Because of * Virtual Hosting considerations, we may need to modify * this to keep hostname and IP associated, rather than * just both in the set. */ InetAddress[] addrs = InetAddress.getAllByName(serverNameConfs[i].getValue()); for (int j = 0; j < addrs.length; j++) { serverNames.add(addrs[j].getHostAddress()); } } catch (Exception genericException) { getLogger().error("Cannot get IP address(es) for " + serverNameConfs[i].getValue()); } } } if (serverNames.isEmpty()) { throw new ConfigurationException("Fatal configuration error: no servernames specified!"); } if (getLogger().isInfoEnabled()) { for (Iterator i = serverNames.iterator(); i.hasNext();) { getLogger().info("Handling mail for: " + i.next()); } } String defaultDomain = (String) serverNames.iterator().next(); context.put(Constants.DEFAULT_DOMAIN, defaultDomain); attributes.put(Constants.DEFAULT_DOMAIN, defaultDomain); // Get postmaster String postMasterAddress = conf.getChild("postmaster").getValue("postmaster").toLowerCase(Locale.US); // if there is no @domain part, then add the first one from the // list of supported domains that isn't localhost. If that // doesn't work, use the hostname, even if it is localhost. if (postMasterAddress.indexOf('@') < 0) { String domainName = null; // the domain to use // loop through candidate domains until we find one or exhaust the list for (int i = 0; domainName == null && i < serverNameConfs.length; i++) { String serverName = serverNameConfs[i].getValue().toLowerCase(Locale.US); if (!("localhost".equals(serverName))) { domainName = serverName; // ok, not localhost, so use it } } // if we found a suitable domain, use it. Otherwise fallback to the host name. postMasterAddress = postMasterAddress + "@" + (domainName != null ? domainName : hostName); } this.postmaster = new MailAddress(postMasterAddress); context.put(Constants.POSTMASTER, postmaster); if (!isLocalServer(postmaster.getHost())) { StringBuffer warnBuffer = new StringBuffer(320).append("The specified postmaster address ( ") .append(postmaster) .append(" ) is not a local address. This is not necessarily a problem, but it does mean that emails addressed to the postmaster will be routed to another server. For some configurations this may cause problems."); getLogger().warn(warnBuffer.toString()); } Configuration userNamesConf = conf.getChild("usernames"); ignoreCase = userNamesConf.getAttributeAsBoolean("ignoreCase", false); boolean enableAliases = userNamesConf.getAttributeAsBoolean("enableAliases", false); boolean enableForwarding = userNamesConf.getAttributeAsBoolean("enableForwarding", false); attributes.put(Constants.DEFAULT_ENABLE_ALIASES, new Boolean(enableAliases)); attributes.put(Constants.DEFAULT_ENABLE_FORWARDING, new Boolean(enableForwarding)); attributes.put(Constants.DEFAULT_IGNORE_USERNAME_CASE, new Boolean(ignoreCase)); //Get localusers try { localusers = (UsersRepository) compMgr.lookup(UsersRepository.ROLE); } catch (Exception e) { getLogger().error("Cannot open private UserRepository"); throw e; } //} compMgr.put(UsersRepository.ROLE, localusers); getLogger().info("Local users repository opened"); Configuration inboxConf = conf.getChild("inboxRepository"); Configuration inboxRepConf = inboxConf.getChild("repository"); // we could delete this block. I didn't remove this because I'm not sure // wether we need the "check" of the inbox repository here, or not. try { store.select(inboxRepConf); } catch (Exception e) { getLogger().error("Cannot open private MailRepository"); throw e; } inboxRootURL = inboxRepConf.getAttribute("destinationURL"); getLogger().info("Private Repository LocalInbox opened"); // Add this to comp compMgr.put(MailServer.ROLE, this); // For mailet engine provide MailetContext //compMgr.put("org.apache.mailet.MailetContext", this); // For AVALON aware mailets and matchers, we put the Component object as // an attribute attributes.put(Constants.AVALON_COMPONENT_MANAGER, compMgr); //Temporary get out to allow complex mailet config files to stop blocking sergei sozonoff's work on bouce processing java.io.File configDir = AvalonContextUtilities.getFile(myContext, "file://conf/"); attributes.put("confDir", configDir.getCanonicalPath()); // We can safely remove this and the localDeliveryField when we // remove the storeMail method from James and from the MailetContext DefaultConfiguration conf = new DefaultConfiguration("mailet", "generated:James.initialize()"); MailetConfigImpl configImpl = new MailetConfigImpl(); configImpl.setMailetName("LocalDelivery"); configImpl.setConfiguration(conf); configImpl.setMailetContext(this); localDeliveryMailet = new LocalDelivery(); localDeliveryMailet.init(configImpl); System.out.println(SOFTWARE_NAME_VERSION); getLogger().info("JAMES ...init end"); }
From source file:org.globus.myproxy.MyProxy.java
private GssSocket getSocket(GSSCredential credential) throws IOException, GSSException { GSSManager manager = ExtendedGSSManager.getInstance(); this.context = manager.createContext(null, GSSConstants.MECH_OID, credential, GSSContext.DEFAULT_LIFETIME); // no delegation this.context.requestCredDeleg(false); // Request confidentiality this.context.requestConf(true); IOException exception = null; Socket socket = null;//w ww .java 2s. co m String goodAddr = ""; int hostIdx = 0; String hosts[] = host.split(","); int socketTimeout = CoGProperties.getDefault().getSocketTimeout(); int currentPort = port; search: while (hostIdx < hosts.length) { String hostPort[] = hosts[hostIdx].split(":"); hosts[hostIdx] = hostPort[0]; if (hostPort.length > 1 && hostPort[1] != null) // port number specified port = Integer.parseInt(hostPort[1].trim()); else port = currentPort; InetAddress addrs[] = null; try { addrs = InetAddress.getAllByName(hosts[hostIdx]); } catch (UnknownHostException e) { if (logger.isDebugEnabled()) { logger.debug("getSocket(): Skipping unknown host " + hosts[hostIdx]); } exception = e; } for (int addrIdx = 0; addrs != null && addrIdx < addrs.length; addrIdx++) { exception = null; try { if (logger.isDebugEnabled()) { logger.debug("getSocket(): Trying " + addrs[addrIdx].toString()); } socket = new Socket(); socket.connect(new InetSocketAddress(addrs[addrIdx], port), socketTimeout); goodAddr = addrs[addrIdx].toString(); if (logger.isDebugEnabled()) { logger.debug(" Succeeded."); } break search; } catch (IOException e) { exception = e; if (logger.isDebugEnabled()) { logger.debug(" Failed."); } } } hostIdx += 1; } if (exception != null) { if (logger.isDebugEnabled()) { logger.debug("getSocket(): " + "Unable to connect to a MyProxy host"); } throw exception; } setHost(hosts[hostIdx]); // host we have successfully connected to GssSocketFactory gssFactory = GssSocketFactory.getDefault(); GssSocket gssSocket = (GssSocket) gssFactory.createSocket(socket, hosts[hostIdx], port, this.context); if (logger.isDebugEnabled()) { logger.debug("getSocket(): Connected to " + goodAddr); } gssSocket.setAuthorization(this.authorization); return gssSocket; }
From source file:org.springframework.integration.ip.util.SocketTestUtils.java
public static void setLocalNicIfPossible(AbstractInternetProtocolReceivingChannelAdapter adapter) throws UnknownHostException { InetAddress[] nics = InetAddress.getAllByName(null); if (nics.length > 0) { // just listen on the loopback interface String loopBack = nics[0].getHostAddress(); adapter.setLocalAddress(loopBack); }//from w ww.j a v a 2 s.co m }
From source file:org.apache.hadoop.yarn.applications.amonly.TestDistributedShell.java
private boolean checkIPs(String hostname, String localIP, String appIP) throws Exception { if (localIP.equals(appIP)) { return true; }// w w w. j ava2 s. com boolean appIPCheck = false; boolean localIPCheck = false; InetAddress[] addresses = InetAddress.getAllByName(hostname); for (InetAddress ia : addresses) { if (ia.getHostAddress().equals(appIP)) { appIPCheck = true; continue; } if (ia.getHostAddress().equals(localIP)) { localIPCheck = true; } } return (appIPCheck && localIPCheck); }
From source file:org.pircbotx.PircBotX.java
/** * Attempt to connect to the specified IRC server using the supplied port * number, password, and socketFactory. On success a {@link ConnectEvent} * will be dispatched/*w w w . j a va2 s .co m*/ * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. */ protected ImmutableMap<InetSocketAddress, Exception> connect() throws IOException, IrcException { synchronized (stateLock) { //Server id Utils.addBotToMDC(this); if (isConnected()) throw new IrcException(IrcException.Reason.AlreadyConnected, "Must disconnect from server before connecting again"); if (getState() == State.CONNECTED) throw new RuntimeException( "Bot is not connected but state is State.CONNECTED. This shouldn't happen"); if (configuration.isIdentServerEnabled() && IdentServer.getServer() == null) throw new RuntimeException("UseIdentServer is enabled but no IdentServer has been started"); //Reset capabilities enabledCapabilities = new ArrayList<String>(); //Pre-insert an initial User representing the bot itself getUserChannelDao().close(); UserHostmask botHostmask = configuration.getBotFactory().createUserHostmask(this, null, configuration.getName(), configuration.getLogin(), null); getUserChannelDao().createUser(botHostmask); //On each server the user gives us, try to connect to all the IP addresses ImmutableMap.Builder<InetSocketAddress, Exception> connectExceptions = ImmutableMap.builder(); int serverEntryCounter = 0; ServerEntryLoop: for (Configuration.ServerEntry curServerEntry : configuration.getServers()) { serverEntryCounter++; serverHostname = curServerEntry.getHostname(); //Hostname and port Utils.addBotToMDC(this); log.info("---Starting Connect attempt {}/{}", connectAttempts, configuration.getAutoReconnectAttempts() + "---"); int serverAddressCounter = 0; InetAddress[] serverAddresses = InetAddress.getAllByName(serverHostname); for (InetAddress curAddress : serverAddresses) { serverAddressCounter++; String debug = Utils.format("[{}/{} address left from {}, {}/{} hostnames left] ", String.valueOf(serverAddresses.length - serverAddressCounter), String.valueOf(serverAddresses.length), serverHostname, String.valueOf(configuration.getServers().size() - serverEntryCounter), String.valueOf(configuration.getServers().size())); log.debug("{}Atempting to connect to {} on port {}", debug, curAddress, curServerEntry.getPort()); try { socket = configuration.getSocketFactory().createSocket(curAddress, curServerEntry.getPort(), configuration.getLocalAddress(), 0); //No exception, assume successful serverPort = curServerEntry.getPort(); break ServerEntryLoop; } catch (Exception e) { connectExceptions.put(new InetSocketAddress(curAddress, curServerEntry.getPort()), e); log.warn("{}Failed to connect to {} on port {}", debug, curAddress, curServerEntry.getPort(), e); } } } //Make sure were connected if (socket == null || (socket != null && !socket.isConnected())) { return connectExceptions.build(); } state = State.CONNECTED; socket.setSoTimeout(configuration.getSocketTimeout()); log.info("Connected to server."); changeSocket(socket); } configuration.getListenerManager().dispatchEvent(new SocketConnectEvent(this)); if (configuration.isIdentServerEnabled()) IdentServer.getServer().addIdentEntry(socket.getInetAddress(), socket.getPort(), socket.getLocalPort(), configuration.getLogin()); if (configuration.isCapEnabled()) // Attempt to initiate a CAP transaction. sendCAP().getSupported(); // Attempt to join the server. if (configuration.isWebIrcEnabled()) sendRaw().rawLineNow("WEBIRC " + configuration.getWebIrcPassword() + " " + configuration.getWebIrcUsername() + " " + configuration.getWebIrcHostname() + " " + configuration.getWebIrcAddress().getHostAddress()); if (StringUtils.isNotBlank(configuration.getServerPassword())) sendRaw().rawLineNow("PASS " + configuration.getServerPassword()); sendRaw().rawLineNow("NICK " + configuration.getName()); sendRaw().rawLineNow("USER " + configuration.getLogin() + " 8 * :" + configuration.getRealName()); //Start input to start accepting lines startLineProcessing(); return ImmutableMap.of(); }