static InetAddress getLocalInetAddress(String byConnecting, int port) { InetAddress addr = getAddressWithSocket(byConnecting, port); if (addr == null) { addr = getAddressWithSocket("www.baidu.com", 80); } if (addr == null) { try { addr = getFirstNonLoopbackAddress(true, false); } catch (SocketException e2) { addr = null; } } return addr; }
/** * Get the local host address, try to get actual IP. * * @return ip form of host address */ public static String getLocalHostAddress() { InetAddress localHost = null; try { localHost = InetAddress.getLocalHost(); } catch (Exception e) { LOGGER.error("Error while get localhost address", e); } if (localHost != null && !localHost.isLoopbackAddress()) { return localHost.getHostAddress(); } return getLocalHostAddress("www.google.com", 80); }
/** * Get local host name. On some platform, InetAddress.getLocalHost().getHostName() will return * "localhost". If the /etc/hosts file is not set properly, it will return "localhost" or throw * exception. So, at this circumstance, we will get the address by connecting a network address. * * @return local host name */ public static String getLocalHostName() { String hostName = null; try { hostName = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { LOGGER.error("Error while get localhost name", e); } if (hostName != null && !"localhost".equals(hostName)) { return hostName; } return getLocalHostName("www.google.com", 80); }
@Test public void testLocalHostName() throws Exception { String localHostAddress = NetworkUtils.getLocalHostName(); assertThat(localHostAddress, notNullValue()); final InetAddress firstNonLoopbackAddress = NetworkUtils.getFirstNonLoopbackAddress(true, false); assertThat(firstNonLoopbackAddress.isLoopbackAddress(), is(false)); assertThat(firstNonLoopbackAddress, instanceOf(Inet4Address.class)); }
StringBuilder addDnsIP(StringBuilder jvmArguments) { try { List<?> dnsServers = NetworkUtils.getDnsServers(); if (!dnsServers.isEmpty()) { return jvmArguments.append(" -Dngrinder.dns.ip=").append(StringUtils.join(dnsServers, ",")).append(" "); } } catch (Exception e) { LOGGER.error("Error while adding DNS IPs for the security mode. This might be occurred by not using " + "Oracle JDK : {}", e.getMessage()); } return jvmArguments; }
/** * Get a available port greater than the given port. * * @param scanStartPort port scan from * @return min port available from scanStartPort */ public static int checkPortAvailability(InetAddress inetAddress, int scanStartPort, int limit) { while (true) { if (checkExactPortAvailability(inetAddress, scanStartPort)) { return scanStartPort; } if (scanStartPort++ > limit) { throw processException("no port is available"); } } }
/** * Get the available ports. * * @param size port size * @param from port number starting from * @return port list */ public static List<Integer> getAvailablePorts(String ip, int size, int from, int limit) { List<Integer> ports = new ArrayList<Integer>(size); int freeSocket; InetAddress inetAddress = null; if (StringUtils.isNotBlank(ip)) { try { inetAddress = InetAddress.getByName(ip); } catch (Exception e) { noOp(); } } for (int i = 0; i < size; i++) { freeSocket = checkPortAvailability(inetAddress, from, limit); ports.add(freeSocket); from = freeSocket + 1; } return ports; }
/** * Initialize the monitor server. * * @param agentConfig agentConfig * @throws IOException IO error */ public void init(AgentConfig agentConfig) throws IOException { this.agentConfig = agentConfig; Set<String> systemDataCollector = new HashSet<String>(); systemDataCollector.add(SYSTEM); MonitorContext.getInstance().setDataCollectors(systemDataCollector); int port = agentConfig.getMonitorProperties().getPropertyInt(PROP_MONITOR_BINDING_PORT); this.rmiRegistry = LocateRegistry.createRegistry(port); MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); String hostname = agentConfig.getMonitorBindingIP(); if (StringUtils.isBlank(hostname)) { hostname = NetworkUtils.getAllPBindingAddress(); } final String jmxUrlString = String.format("service:jmx:rmi://%s:%d/jndi/rmi://%s:%d/jmxrmi", hostname, port, hostname, port); JMXServiceURL jmxUrl = new JMXServiceURL(jmxUrlString); this.jmxServer = JMXConnectorServerFactory.newJMXConnectorServer(jmxUrl, null, mBeanServer); RegisterMXBean.getInstance().addDefaultMXBean(mBeanServer); LOG.info("Service URL:{} is initiated.", jmxUrl); }
@Test public void testAvailableSocket() throws IOException { ServerSocket serverSocket = null; try { // When port is already used serverSocket = new ServerSocket(20111); int localPort = serverSocket.getLocalPort(); // It should be excluded in available ports List<Integer> availablePorts = NetworkUtils.getAvailablePorts("", 20, 20111, 40000); assertThat(availablePorts.contains(localPort), not(true)); assertThat(availablePorts.size(), is(20)); } finally { if (serverSocket != null) { serverSocket.close(); } } } }
@Test public void testIPAndPortPair() { NetworkUtils.IPPortPair ipAndPortPair = NetworkUtils.convertIPAndPortPair ("2001:0:9d38:90d7:469:1f94:f5bf:cf5d", 0); assertThat(ipAndPortPair.getIP(), is("2001:0:9d38:90d7:469:1f94:f5bf:cf5d")); assertThat(ipAndPortPair.getPort(), is(0)); ipAndPortPair = NetworkUtils.convertIPAndPortPair("[2001:0:9d38:90d7:469:1f94:f5bf:cf5d]:20", 0); assertThat(ipAndPortPair.getIP(), is("2001:0:9d38:90d7:469:1f94:f5bf:cf5d")); assertThat(ipAndPortPair.getPort(), is(20)); ipAndPortPair = NetworkUtils.convertIPAndPortPair ("2001:0:9d38:90d7:469:1f94:f5bf:cf5d", 0); assertThat(ipAndPortPair.getIP(), is("2001:0:9d38:90d7:469:1f94:f5bf:cf5d")); assertThat(ipAndPortPair.getPort(), is(0)); ipAndPortPair = NetworkUtils.convertIPAndPortPair("127.0.0.1:20", 0); assertThat(ipAndPortPair.getIP(), is("127.0.0.1")); assertThat(ipAndPortPair.getPort(), is(20)); ipAndPortPair = NetworkUtils.convertIPAndPortPair("127.0.0.1", 20); assertThat(ipAndPortPair.getIP(), is("127.0.0.1")); assertThat(ipAndPortPair.getPort(), is(20)); ipAndPortPair = NetworkUtils.convertIPAndPortPair("127.2.0.1:40:40", 20); assertThat(ipAndPortPair.getIP(), is("127.0.0.1")); assertThat(ipAndPortPair.getPort(), is(40)); }
/** * Constructor. * * @param logger Logger. * @param agentConfig which contains basic agent configuration * @param proceedWithoutConsole <code>true</code> => proceed if a console connection could not be made. */ public AgentImplementationEx(Logger logger, AgentConfig agentConfig, boolean proceedWithoutConsole) { m_logger = logger; m_agentConfig = agentConfig; m_proceedWithoutConsole = proceedWithoutConsole; m_consoleListener = new ConsoleListener(m_eventSynchronisation, m_logger); m_agentIdentity = new AgentIdentityImplementation(NetworkUtils.getLocalHostName()); }
@Test public void testLocalHostAddressByConnecting() { String localHostAddress = NetworkUtils.getLocalHostAddress("www.baidu.com", 80); assertThat(localHostAddress, notNullValue()); assertThat(localHostAddress, not("127.0.0.1")); localHostAddress = NetworkUtils.getLocalHostAddress("www.invalidaddresssss", 80); assertThat(localHostAddress, notNullValue()); assertThat(localHostAddress, not("127.0.0.1")); }
@Test public void testLocalHostNameByConnecting() { String localHostAddress = NetworkUtils.getLocalHostName("www.baidu.com", 80); assertThat(localHostAddress, notNullValue()); }
@Test public void testLocalHostAddress() throws UnknownHostException { String localHostAddress = NetworkUtils.getLocalHostAddress(); assertThat(localHostAddress, notNullValue()); assertThat(localHostAddress, not("127.0.0.1")); localHostAddress = NetworkUtils.getLocalHostAddress(); assertThat(localHostAddress, notNullValue()); assertThat(localHostAddress, not("127.0.0.1")); }
public PropertyBuilder createPropertyBuilder(String hostString) throws DirectoryException { Directory directory = new Directory(new File(".")); GrinderProperties property = new GrinderProperties(); return new PropertyBuilder(property, directory, true, GRINDER_SECURITY_LEVEL_NORMAL, hostString, NetworkUtils.getLocalHostName()); } }
@Test public void testStartAgent() { // Start Console console1 = new SingleConsole(getFreePort()); console1.start(); console1.setReportPath(new File("./tmp/console-home")); // Check there is no agents are attached. assertThat(console1.getAllAttachedAgentsCount(), is(0)); // Make one agent connect to console1 GrinderProperties grinderProperties = new GrinderProperties(); grinderProperties.setInt(GrinderProperties.CONSOLE_PORT, console1.getConsolePort()); String localHostAddress = NetworkUtils.getLocalHostAddress(); grinderProperties.setProperty(GrinderProperties.CONSOLE_HOST, localHostAddress); AgentIdentity next = getAgentIdentity(allAvailableAgents, 0); agentControllerServerDaemon.startAgent(grinderProperties, next); waitAndAssertUntilAgentAttachedTo(console1, 1, 2); // Shutdown agent controller and see agent is detached as well agentControllerServerDaemon.shutdown(); waitAndAssertUntilAgentAttachedTo(console1, 0, 5); }
GrinderProperties properties = new GrinderProperties(); PropertyBuilder builder = new ValidationPropertyBuilder(properties, new Directory(base), securityEnabled, securityLevel, hostString, NetworkUtils.getLocalHostName()); properties.setInt("grinder.agents", 1); properties.setInt("grinder.processes", 1);
private String buildTestRunProperties(ScriptLocation script, AbstractLanguageHandler handler, Properties systemProperty, GrinderProperties properties) { PropertyBuilder builder = new PropertyBuilder(properties, script.getDirectory(), isSecurityEnabled(properties), properties.getProperty(GRINDER_PROP_SECURITY_LEVEL, GRINDER_SECURITY_LEVEL_NORMAL), properties.getProperty(GRINDER_PROP_ETC_HOSTS), NetworkUtils.getLocalHostName(), m_agentConfig.getAgentProperties().getPropertyBoolean(PROP_AGENT_SERVER_MODE), m_agentConfig.getAgentProperties().getPropertyBoolean(PROP_AGENT_LIMIT_XMX), m_agentConfig.getAgentProperties().getPropertyBoolean(PROP_AGENT_ENABLE_LOCAL_DNS), m_agentConfig.getAgentProperties().getProperty(PROP_AGENT_JAVA_OPT)); String jvmArguments = builder.buildJVMArgument(); String rebaseCustomClassPath = getForeMostClassPath(systemProperty, handler, m_logger) + File.pathSeparator + builder.rebaseCustomClassPath(properties.getProperty("grinder.jvm.classpath", "")); properties.setProperty("grinder.jvm.classpath", rebaseCustomClassPath); m_logger.info("grinder properties {}", properties); m_logger.info("jvm arguments {}", jvmArguments); // To be safe... if (properties.containsKey("grinder.duration") && !properties.containsKey("grinder.runs")) { properties.setInt("grinder.runs", 0); } return jvmArguments; }