Java Code Examples for java.net.InetAddress#toString()

The following examples show how to use java.net.InetAddress#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Agent.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
protected void setupStartupCommand(final StartupCommand startup) {
    InetAddress addr;
    try {
        addr = InetAddress.getLocalHost();
    } catch (final UnknownHostException e) {
        s_logger.warn("unknow host? ", e);
        throw new CloudRuntimeException("Cannot get local IP address");
    }

    final Script command = new Script("hostname", 500, s_logger);
    final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
    final String result = command.execute(parser);
    final String hostname = result == null ? parser.getLine() : addr.toString();

    startup.setId(getId());
    if (startup.getName() == null) {
        startup.setName(hostname);
    }
    startup.setDataCenter(getZone());
    startup.setPod(getPod());
    startup.setGuid(getResourceGuid());
    startup.setResourceName(getResourceName());
    startup.setVersion(getVersion());
}
 
Example 2
Source File: INetUtil.java    From blade-tool with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取 服务器 HostIp
 *
 * @return HostIp
 */
public static String getHostIp() {
	String hostAddress;
	try {
		InetAddress address = INetUtil.getLocalHostLANAddress();
		// force a best effort reverse DNS lookup
		hostAddress = address.getHostAddress();
		if (hostAddress == null || "".equals(hostAddress)) {
			hostAddress = address.toString();
		}
	} catch (UnknownHostException ignore) {
		hostAddress = LOCAL_HOST;
	}
	return hostAddress;
}
 
Example 3
Source File: NetworkUtil.java    From common-utils with GNU General Public License v2.0 5 votes vote down vote up
public static String getLocalHostIp() {
    InetAddress address;
    String hostAddress;
    try {
        address = InetAddress.getLocalHost();
        // force a best effort reverse DNS lookup
        hostAddress = address.getHostAddress();
        if (StringUtil.isEmpty(hostAddress)) {
            hostAddress = address.toString();
        }
    } catch (UnknownHostException noIpAddrException) {
        hostAddress = LOCALHOST;
    }
    return hostAddress;
}
 
Example 4
Source File: JdpBroadcaster.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new broadcaster
 *
 * @param address - multicast group address
 * @param srcAddress - address of interface we should use to broadcast.
 * @param port - udp port to use
 * @param ttl - packet ttl
 * @throws IOException
 */
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
        throws IOException, JdpException {
    this.addr = address;
    this.port = port;

    ProtocolFamily family = (address instanceof Inet6Address)
            ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;

    channel = DatagramChannel.open(family);
    channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);

    // with srcAddress equal to null, this constructor do exactly the same as
    // if srcAddress is not passed
    if (srcAddress != null) {
        // User requests particular interface to bind to
        NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);

        if (interf == null) {
            throw new JdpException("Unable to get network interface for " + srcAddress.toString());
        }

        if (!interf.isUp()) {
            throw new JdpException(interf.getName() + " is not up.");
        }

        if (!interf.supportsMulticast()) {
            throw new JdpException(interf.getName() + " does not support multicast.");
        }

        try {
            channel.bind(new InetSocketAddress(srcAddress, 0));
        } catch (UnsupportedAddressTypeException ex) {
            throw new JdpException("Unable to bind to source address");
        }
        channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
    }
}
 
Example 5
Source File: StreamCoordinator.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private HostStreamingData getHostData(InetAddress peer)
{
    HostStreamingData data = peerSessions.get(peer);
    if (data == null)
        throw new IllegalArgumentException("Unknown peer requested: " + peer.toString());
    return data;
}
 
Example 6
Source File: SocketServer.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
final LoggerRepository configureHierarchy(final InetAddress inetAddress) {
   cat.info("Locating configuration file for " + inetAddress);
   // We assume that the toSting method of InetAddress returns is in
   // the format hostname/d1.d2.d3.d4 e.g. torino/192.168.1.1
   final String s = inetAddress.toString();
   final int i = s.indexOf('/');
   if (i == -1) {
      cat.warn("Could not parse the inetAddress [" + inetAddress +
              "]. Using default hierarchy.");
      return genericHierarchy();
   } else {
      final String key = s.substring(0, i);

      final File configFile = new File(dir, key + CONFIG_FILE_EXT);
      if (configFile.exists()) {
         final Hierarchy h = new Hierarchy(new RootLogger(Level.DEBUG));
         hierarchyMap.put(inetAddress, h);

         new PropertyConfigurator().doConfigure(configFile.getAbsolutePath(), h);

         return h;
      } else {
         cat.warn("Could not find config file [" + configFile + "].");
         return genericHierarchy();
      }
   }
}
 
Example 7
Source File: SystemUtil.java    From software-demo with MIT License 5 votes vote down vote up
/**
 * 获取主机地址
 * @return
 */
public static String getLocalHost() {
	InetAddress localHost = null;
	try {
		//获取主机地址
		localHost = InetAddress.getLocalHost();
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
	return localHost != null ? localHost.toString() : "Unknow-Computer/127.0.0.1";
}
 
Example 8
Source File: DnsResponse.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    String ret = "addresses:\n";
    for (InetAddress address: addresses)
        ret += address.toString() + "\n";
    ret += "names:\n";
    for (String name: names)
        ret += name + "\n";
    return ret;
}
 
Example 9
Source File: HelloImpl.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String sayHelloWithInetAddress(InetAddress ipAddr)
        throws RemoteException {
    String response = "Hello with InetAddress " + ipAddr.toString();
    return response;
}
 
Example 10
Source File: HelloImpl.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String sayHelloWithInetAddress(InetAddress ipAddr)
        throws RemoteException {
    String response = "Hello with InetAddress " + ipAddr.toString();
    return response;
}
 
Example 11
Source File: ValueMetaBaseTest.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetDataXML() throws IOException {
  BigDecimal bigDecimal = BigDecimal.ONE;
  ValueMetaBase valueDoubleMetaBase =
    new ValueMetaBase( String.valueOf( bigDecimal ), ValueMetaInterface.TYPE_BIGNUMBER );
  assertEquals(
    "<value-data>" + Encode.forXml( String.valueOf( bigDecimal ) ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    valueDoubleMetaBase.getDataXML( bigDecimal ) );

  boolean valueBoolean = Boolean.TRUE;
  ValueMetaBase valueBooleanMetaBase =
    new ValueMetaBase( String.valueOf( valueBoolean ), ValueMetaInterface.TYPE_BOOLEAN );
  assertEquals(
    "<value-data>" + Encode.forXml( String.valueOf( valueBoolean ) ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    valueBooleanMetaBase.getDataXML( valueBoolean ) );

  Date date = new Date( 0 );
  ValueMetaBase dateMetaBase =
    new ValueMetaBase( date.toString(), ValueMetaInterface.TYPE_DATE );
  SimpleDateFormat formaterData = new SimpleDateFormat( ValueMetaBase.DEFAULT_DATE_FORMAT_MASK );
  assertEquals(
    "<value-data>" + Encode.forXml( formaterData.format( date ) ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    dateMetaBase.getDataXML( date ) );

  InetAddress inetAddress = InetAddress.getByName( "127.0.0.1" );
  ValueMetaBase inetAddressMetaBase =
    new ValueMetaBase( inetAddress.toString(), ValueMetaInterface.TYPE_INET );
  assertEquals( "<value-data>" + Encode.forXml( inetAddress.toString() ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    inetAddressMetaBase.getDataXML( inetAddress ) );

  long value = Long.MAX_VALUE;
  ValueMetaBase integerMetaBase = new ValueMetaBase( String.valueOf( value ), ValueMetaInterface.TYPE_INTEGER );
  assertEquals( "<value-data>" + Encode.forXml( String.valueOf( value ) ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    integerMetaBase.getDataXML( value ) );

  String stringValue = "TEST_STRING";
  ValueMetaBase valueMetaBase = new ValueMetaString( stringValue );
  assertEquals( "<value-data>" + Encode.forXml( stringValue ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    valueMetaBase.getDataXML( stringValue ) );

  Timestamp timestamp = new Timestamp( 0 );
  ValueMetaBase valueMetaBaseTimeStamp = new ValueMetaBase( timestamp.toString(), ValueMetaInterface.TYPE_TIMESTAMP );
  SimpleDateFormat formater = new SimpleDateFormat( ValueMetaBase.DEFAULT_TIMESTAMP_FORMAT_MASK );
  assertEquals(
    "<value-data>" + Encode.forXml( formater.format( timestamp ) ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    valueMetaBaseTimeStamp.getDataXML( timestamp ) );

  byte[] byteTestValues = { 0, 1, 2, 3 };
  ValueMetaBase valueMetaBaseByteArray = new ValueMetaBase( byteTestValues.toString(), ValueMetaInterface.TYPE_STRING );
  valueMetaBaseByteArray.setStorageType( ValueMetaInterface.STORAGE_TYPE_BINARY_STRING );
  assertEquals(
    "<value-data><binary-string>" + Encode.forXml( XMLHandler.encodeBinaryData( byteTestValues ) )
      + "</binary-string>" + Const.CR + "</value-data>",
    valueMetaBaseByteArray.getDataXML( byteTestValues ) );
}
 
Example 12
Source File: TestInetAddressServlet.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
/**
 * Test properties of an instance of InetAddress obtained via getLocalHost()
 * @param localHost
 * @param response
 * @throws IOException
 * @throws AssertionFailedException
 */
private static void testLocalHost(InetAddress localHost, HttpServletResponse response)
    throws IOException, AssertionFailedException {
  assertNotNull("localhost", localHost, response);
  assertTrue("instanceof Inet4Addr", localHost instanceof Inet4Address, response);

  //getAddress
  byte[] bytes = localHost.getAddress();
  assertNotNull("localhost address-bytes", bytes, response);
  assertEquals("localhost address bytes.length", 4, bytes.length, response);
  assertEquals("first byte of localhost address", 127, bytes[0], response);
  assertEquals("last byte of localhost address", 1, bytes[3], response);

  String name = localHost.getCanonicalHostName();
  assertEquals("getCanonicalHostName", "localhost", name, response);

  //getHostAddress should return the loopback address
  String address = localHost.getHostAddress();
  assertEquals("getHostAddress", "127.0.0.1", address, response);

  //getHostName
  name = localHost.getHostName();
  assertEquals("getHostName", "localhost", name, response);

  //Misc Properties
  assertFalse("isAnyLocalAddress", localHost.isAnyLocalAddress(), response);
  assertFalse("isLinkLocalAddress", localHost.isLinkLocalAddress(), response);
  assertTrue("isLoopbackAddress", localHost.isLoopbackAddress(), response);
  assertFalse("isLoopbackAddress", localHost.isMCGlobal(), response);
  assertFalse("isMCLinkLocal", localHost.isMCLinkLocal(), response);
  assertFalse("isMCNodeLocal", localHost.isMCNodeLocal(), response);
  assertFalse("isMCOrgLocal", localHost.isMCOrgLocal(), response);
  assertFalse("isMCSiteLocal", localHost.isMCSiteLocal(), response);
  assertFalse("isMulticastAddress", localHost.isMulticastAddress(), response);
  assertFalse("isSiteLocalAddress", localHost.isSiteLocalAddress(), response);

  //toString
  String s = localHost.toString();
  assertEquals("toString", "localhost/127.0.0.1", s, response);

  //isReachable
  assertFalse("isReachable", localHost.isReachable(1000), response);
  //Can't test version of isReachable() that takes a NetworkInterface
  //because it is not possible to get a network interface without triggering the ptrace sandbox
  //localHost.isReachable(netif,  ttl,  timeout);

}
 
Example 13
Source File: ClientHealthMonitor.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Returns modifiable map (changes do not effect this class) of client
 * membershipID to connection count. This is different from the map contained
 * in this class as here the key is client membershipID & not the the proxyID.
 * It is to be noted that a given client can have multiple proxies.
 * 
 * @param filterProxies
 *          Set identifying the Connection proxies which should be fetched.
 *          These ConnectionProxies may be from same client member or
 *          different. If it is null this would mean to fetch the Connections
 *          of all the ConnectionProxy objects.
 *  
 */
public Map getConnectedClients(Set filterProxies)
{
  Map map = new HashMap(); // KEY=proxyID, VALUE=connectionCount (Integer)
  synchronized (_clientThreadsLock) {
    Iterator connectedClients = this._clientThreads.entrySet().iterator();
    while (connectedClients.hasNext()) {
      Map.Entry entry = (Map.Entry)connectedClients.next();
      ClientProxyMembershipID proxyID = (ClientProxyMembershipID)entry
          .getKey();// proxyID includes FQDN
      if (filterProxies == null || filterProxies.contains(proxyID)) {
        String membershipID = null;
        Set connections = (Set)entry.getValue();
        int socketPort = 0;
        InetAddress socketAddress = null;
        ///*
        Iterator serverConnections = connections.iterator();
        // Get data from one.
        while (serverConnections.hasNext()) {
          ServerConnection sc = (ServerConnection)serverConnections.next();
          socketPort = sc.getSocketPort();
          socketAddress = sc.getSocketAddress();
          membershipID = sc.getMembershipID();
          break;
        }
        //*/
        int connectionCount = connections.size();
        String clientString = null;
        if (socketAddress == null) {
          clientString = "client member id=" + membershipID;
        }
        else {
          clientString = "host name=" + socketAddress.toString()
              + " host ip=" + socketAddress.getHostAddress()
              + " client port=" + socketPort + " client member id="
              + membershipID;
        }
        Object[] data = null;
        data = (Object[])map.get(membershipID);
        if (data == null) {
          map.put(membershipID, new Object[] { clientString,
              Integer.valueOf(connectionCount) });
        }
        else {
          data[1] = Integer.valueOf(((Integer)data[1]).intValue()
              + connectionCount);
        }
        /*
         * Note: all client addresses are same... Iterator serverThreads =
         * ((Set) entry.getValue()).iterator(); while
         * (serverThreads.hasNext()) { ServerConnection connection =
         * (ServerConnection) serverThreads.next(); InetAddress clientAddress =
         * connection.getClientAddress();
         * getLogger().severe("getConnectedClients: proxyID=" + proxyID + "
         * clientAddress=" + clientAddress + " FQDN=" +
         * clientAddress.getCanonicalHostName()); }
         */
      }
    }

  }
  return map;
}
 
Example 14
Source File: ValueMetaBaseTest.java    From hop with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetDataXML() throws IOException {
  BigDecimal bigDecimal = BigDecimal.ONE;
  ValueMetaBase valueDoubleMetaBase =
    new ValueMetaBase( String.valueOf( bigDecimal ), IValueMeta.TYPE_BIGNUMBER );
  assertEquals(
    "<value-data>" + Encode.forXml( String.valueOf( bigDecimal ) ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    valueDoubleMetaBase.getDataXml( bigDecimal ) );

  boolean valueBoolean = Boolean.TRUE;
  ValueMetaBase valueBooleanMetaBase =
    new ValueMetaBase( String.valueOf( valueBoolean ), IValueMeta.TYPE_BOOLEAN );
  assertEquals(
    "<value-data>" + Encode.forXml( String.valueOf( valueBoolean ) ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    valueBooleanMetaBase.getDataXml( valueBoolean ) );

  Date date = new Date( 0 );
  ValueMetaBase dateMetaBase =
    new ValueMetaBase( date.toString(), IValueMeta.TYPE_DATE );
  SimpleDateFormat formaterData = new SimpleDateFormat( ValueMetaBase.DEFAULT_DATE_FORMAT_MASK );
  assertEquals(
    "<value-data>" + Encode.forXml( formaterData.format( date ) ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    dateMetaBase.getDataXml( date ) );

  InetAddress inetAddress = InetAddress.getByName( "127.0.0.1" );
  ValueMetaBase inetAddressMetaBase =
    new ValueMetaBase( inetAddress.toString(), IValueMeta.TYPE_INET );
  assertEquals( "<value-data>" + Encode.forXml( inetAddress.toString() ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    inetAddressMetaBase.getDataXml( inetAddress ) );

  long value = Long.MAX_VALUE;
  ValueMetaBase integerMetaBase = new ValueMetaBase( String.valueOf( value ), IValueMeta.TYPE_INTEGER );
  assertEquals( "<value-data>" + Encode.forXml( String.valueOf( value ) ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    integerMetaBase.getDataXml( value ) );

  String stringValue = "TEST_STRING";
  ValueMetaBase valueMetaBase = new ValueMetaString( stringValue );
  assertEquals( "<value-data>" + Encode.forXml( stringValue ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    valueMetaBase.getDataXml( stringValue ) );

  Timestamp timestamp = new Timestamp( 0 );
  ValueMetaBase valueMetaBaseTimeStamp = new ValueMetaTimestamp( timestamp.toString() );
  SimpleDateFormat formater = new SimpleDateFormat( ValueMetaBase.DEFAULT_TIMESTAMP_FORMAT_MASK );
  assertEquals(
    "<value-data>" + Encode.forXml( formater.format( timestamp ) ) + "</value-data>" + SystemUtils.LINE_SEPARATOR,
    valueMetaBaseTimeStamp.getDataXml( timestamp ) );

  byte[] byteTestValues = { 0, 1, 2, 3 };
  ValueMetaBase valueMetaBaseByteArray = new ValueMetaString( byteTestValues.toString() );
  valueMetaBaseByteArray.setStorageType( IValueMeta.STORAGE_TYPE_BINARY_STRING );
  assertEquals(
    "<value-data><binary-string>" + Encode.forXml( XmlHandler.encodeBinaryData( byteTestValues ) )
      + "</binary-string>" + Const.CR + "</value-data>",
    valueMetaBaseByteArray.getDataXml( byteTestValues ) );
}
 
Example 15
Source File: HelloImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String sayHelloWithInetAddress(InetAddress ipAddr)
        throws RemoteException {
    String response = "Hello with InetAddress " + ipAddr.toString();
    return response;
}
 
Example 16
Source File: HelloImpl.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String sayHelloWithInetAddress(InetAddress ipAddr)
        throws RemoteException {
    String response = "Hello with InetAddress " + ipAddr.toString();
    return response;
}
 
Example 17
Source File: HelloImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String sayHelloWithInetAddress(InetAddress ipAddr)
        throws RemoteException {
    String response = "Hello with InetAddress " + ipAddr.toString();
    return response;
}
 
Example 18
Source File: HelloImpl.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String sayHelloWithInetAddress(InetAddress ipAddr)
        throws RemoteException {
    String response = "Hello with InetAddress " + ipAddr.toString();
    return response;
}
 
Example 19
Source File: HelloImpl.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String sayHelloWithInetAddress(InetAddress ipAddr)
        throws RemoteException {
    String response = "Hello with InetAddress " + ipAddr.toString();
    return response;
}
 
Example 20
Source File: TestInetAddressServlet.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
/**
 * Test the properties of an instance of IPV4 InetAddress obtained via getByAddress()
 * @param The expected host name
 * @param The expected addressString
 * @param The expected addressBytes
 * @param iAddr The instance of InetAddress being tested.
 * @param HttpServletResponse used to return failure message
 * @throws IOException If method being tested throws this.
 * @throws AssertionFailedException If an assertion fails
 */
private static void testNameAndAddress4(
    String name,
    String addressString,
    byte[] addressBytes,
    InetAddress iAddr,
    HttpServletResponse response)
    throws IOException, AssertionFailedException {

  assertNotNull("iAdr", iAddr, response);
  assertTrue("instanceof Inet4Addr", iAddr instanceof Inet4Address, response);

  //getAddress
  byte[] bytes = iAddr.getAddress();
  assertNotNull("iAddr bytes", bytes, response);
  assertEquals("iAddr bytes.length", 4, bytes.length, response);
  for (int i = 0; i < 4; i++) {
    assertEquals("iAddr address byte " + i, addressBytes[i], bytes[i], response);
  }

  //getCanonicalHostName should return addressString because user code
  //doesn't have permission to get an actual host name
  String canonicalName = iAddr.getCanonicalHostName();
  assertEquals("getCanonicalHostName", addressString, canonicalName, response);

  //getHostAddress
  String address = iAddr.getHostAddress();
  assertEquals("getHostAddress", addressString, address, response);

  //getHostName.
  String name2 = iAddr.getHostName();
  String expectedName = (name == null ? addressString : name);
  assertEquals("getHostName", expectedName, name2, response);

  //Misc Properties
  assertFalse("isAnyLocalAddress", iAddr.isAnyLocalAddress(), response);
  assertFalse("isLinkLocalAddress", iAddr.isLinkLocalAddress(), response);
  assertFalse("isLoopbackAddress", iAddr.isLoopbackAddress(), response);
  assertFalse("isMCGlobal", iAddr.isMCGlobal(), response);
  assertFalse("isMCLinkLoca", iAddr.isMCLinkLocal(), response);
  assertFalse("isMCNodeLocal", iAddr.isMCNodeLocal(), response);
  assertFalse("isMCOrgLocal", iAddr.isMCOrgLocal(), response);
  assertFalse("isMCSiteLoca", iAddr.isMCSiteLocal(), response);
  assertFalse("isMulticastAddress", iAddr.isMulticastAddress(), response);
  assertFalse("isSiteLocalAddress", iAddr.isSiteLocalAddress(), response);

  //toString
  String s = iAddr.toString();
  String prefix = (name == null ? addressString : name);
  assertEquals("toString", prefix + "/" + addressString, s, response);

  //isReachable
  assertFalse("isReachable", iAddr.isReachable(1000), response);
}