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

The following examples show how to use java.net.InetAddress#getHostName() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: metrics-kafka   File: HostUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String getNotLoopbackAddress() {
	String hostName = null;
	Enumeration<NetworkInterface> interfaces;
	try {
		interfaces = NetworkInterface.getNetworkInterfaces();
		while (interfaces.hasMoreElements()) {
			NetworkInterface nic = interfaces.nextElement();
			Enumeration<InetAddress> addresses = nic.getInetAddresses();
			while (hostName == null && addresses.hasMoreElements()) {
				InetAddress address = addresses.nextElement();
				if (!address.isLoopbackAddress()) {
					hostName = address.getHostName();
				}
			}
		}
	} catch (SocketException e) {
		logger.error("getNotLoopbackAddress error!", e);
	}
	return hostName;
}
 
Example 2
Source Project: T0rlib4Android   File: SocksSocket.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Connects to given ip and port using given Proxy server.
 * 
 * @param p
 *            Proxy to use.
 * @param ip
 *            Machine to connect to.
 * @param port
 *            Port to which to connect.
 */
public SocksSocket(SocksProxyBase p, InetAddress ip, int port)
		throws SocksException {
	if (p == null) {
		throw new SocksException(SocksProxyBase.SOCKS_NO_PROXY);
	}
	this.proxy = p.copy();
	this.remoteIP = ip;
	this.remotePort = port;
	this.remoteHost = ip.getHostName();
	if (proxy.isDirect(remoteIP)) {
		doDirect();
	} else {
		processReply(proxy.connect(ip, port));
	}
}
 
Example 3
Source Project: uuid-creator   File: NetworkData.java    License: MIT License 6 votes vote down vote up
private static NetworkData buildNetworkData(NetworkInterface networkInterface, InetAddress inetAddress)
		throws SocketException {
	if (isPhysicalNetworkInterface(networkInterface)) {

		String hostName = inetAddress != null ? inetAddress.getHostName() : null;
		String hostCanonicalName = inetAddress != null ? inetAddress.getCanonicalHostName() : null;
		String interfaceName = networkInterface.getName();
		String interfaceDisplayName = networkInterface.getDisplayName();
		String interfaceHardwareAddress = ByteUtil.toHexadecimal(networkInterface.getHardwareAddress());
		List<String> interfaceAddresses = getInterfaceAddresses(networkInterface);

		NetworkData networkData = new NetworkData();
		networkData.setHostName(hostName);
		networkData.setHostCanonicalName(hostCanonicalName);
		networkData.setInterfaceName(interfaceName);
		networkData.setInterfaceDisplayName(interfaceDisplayName);
		networkData.setInterfaceHardwareAddress(interfaceHardwareAddress);
		networkData.setInterfaceAddresses(interfaceAddresses);

		return networkData;
	}
	return null;
}
 
Example 4
Source Project: sofa-bolt   File: RemotingUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * parse {@link InetSocketAddress} to get address (format [ip:port])
 */
@Test
public void testParseSocketAddressToString() {
    String localhostName;
    String localIP;
    try {
        InetAddress inetAddress = InetAddress.getLocalHost();
        localhostName = inetAddress.getHostName();
        localIP = inetAddress.getHostAddress();
        if (null == localIP || StringUtils.isBlank(localIP)) {
            return;
        }
    } catch (UnknownHostException e) {
        localhostName = "localhost";
        localIP = "127.0.0.1";
    }
    SocketAddress socketAddress = new InetSocketAddress(localhostName, port);
    String res = RemotingUtil.parseSocketAddressToString(socketAddress);
    Assert.assertEquals(localIP + ":" + port, res);
}
 
Example 5
Source Project: flink   File: TaskManagerRunner.java    License: Apache License 2.0 6 votes vote down vote up
private static String determineTaskManagerBindAddressByConnectingToResourceManager(
		final Configuration configuration,
		final HighAvailabilityServices haServices) throws LeaderRetrievalException {

	final Duration lookupTimeout = AkkaUtils.getLookupTimeout(configuration);

	final InetAddress taskManagerAddress = LeaderRetrievalUtils.findConnectingAddress(
		haServices.getResourceManagerLeaderRetriever(),
		lookupTimeout);

	LOG.info("TaskManager will use hostname/address '{}' ({}) for communication.",
		taskManagerAddress.getHostName(), taskManagerAddress.getHostAddress());

	HostBindPolicy bindPolicy = HostBindPolicy.fromString(configuration.getString(TaskManagerOptions.HOST_BIND_POLICY));
	return bindPolicy == HostBindPolicy.IP ? taskManagerAddress.getHostAddress() : taskManagerAddress.getHostName();
}
 
Example 6
public static String getHostName() throws SocketException {
  	Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
    NetworkInterface n = (NetworkInterface) e.nextElement();
    Enumeration<InetAddress> ee = n.getInetAddresses();
    while (ee.hasMoreElements())
    {
        InetAddress i = (InetAddress) ee.nextElement();
        if (!i.isSiteLocalAddress() && !i.isLinkLocalAddress() && !i.isLoopbackAddress() && !i.isAnyLocalAddress() && !i.isMulticastAddress()) {
        	return i.getHostName();
        }
    }
}
throw new SocketException("Failed to get the IP address for the local host");
  }
 
Example 7
Source Project: fess   File: AdminMaintenanceAction.java    License: Apache License 2.0 6 votes vote down vote up
protected String getHostInfo() {
    final StringBuilder buf = new StringBuilder();
    try {
        final InetAddress ia = InetAddress.getLocalHost();
        final String hostname = ia.getHostName();
        if (StringUtil.isNotBlank(hostname)) {
            buf.append(hostname);
        }
        final String ip = ia.getHostAddress();
        if (StringUtil.isNotBlank(ip)) {
            if (buf.length() > 0) {
                buf.append(" : ");
            }
            buf.append(ip);
        }
    } catch (final Exception e) {
        // ignore
    }
    return buf.toString();
}
 
Example 8
Source Project: oodt   File: AvroRpcWorkflowManager.java    License: Apache License 2.0 5 votes vote down vote up
private String getHostname() {
    try {
        // Get hostname by textual representation of IP address
        InetAddress addr = InetAddress.getLocalHost();
        // Get the host name
        String hostname = addr.getHostName();
        return hostname;
    } catch (UnknownHostException e) {
    }
    return null;
}
 
Example 9
Source Project: apollo   File: MachineInfo.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return
 * @Description: 获取机器名
 */
public static String getHostName() throws Exception {

    try {
        InetAddress addr = InetAddress.getLocalHost();
        String hostname = addr.getHostName();

        return hostname;

    } catch (UnknownHostException e) {

        throw new Exception();
    }
}
 
Example 10
Source Project: disconf   File: MachineInfo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return
 *
 * @Description: 获取机器名
 */
public static String getHostName() throws Exception {

    try {
        InetAddress addr = InetAddress.getLocalHost();
        String hostname = addr.getHostName();

        return hostname;

    } catch (UnknownHostException e) {

        throw new Exception(e);
    }
}
 
Example 11
Source Project: openjdk-jdk9   File: Utils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the name of the local host.
 *
 * @return The host name
 * @throws UnknownHostException if IP address of a host could not be determined
 */
public static String getHostname() throws UnknownHostException {
    InetAddress inetAddress = InetAddress.getLocalHost();
    String hostName = inetAddress.getHostName();

    assertTrue((hostName != null && !hostName.isEmpty()),
            "Cannot get hostname");

    return hostName;
}
 
Example 12
/**
 * Returns the name of the local host.
 *
 * @return The host name
 * @throws UnknownHostException if IP address of a host could not be determined
 */
public static String getHostname() throws UnknownHostException {
    InetAddress inetAddress = InetAddress.getLocalHost();
    String hostName = inetAddress.getHostName();

    assertTrue((hostName != null && !hostName.isEmpty()),
            "Cannot get hostname");

    return hostName;
}
 
Example 13
Source Project: Openfire   File: NIOConnection.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getHostName() throws UnknownHostException {
    final SocketAddress remoteAddress = ioSession.getRemoteAddress();
    if (remoteAddress == null) throw new UnknownHostException();
    final InetSocketAddress socketAddress = (InetSocketAddress) remoteAddress;
    final InetAddress inetAddress = socketAddress.getAddress();
    return inetAddress.getHostName();
}
 
Example 14
Source Project: cxf   File: HttpServletRequestAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public String getRemoteHost() {
    InetSocketAddress isa = exchange.getRemoteAddress();
    if (isa != null) {
        InetAddress ia = isa.getAddress();
        if (ia != null) {
            return ia.getHostName();
        }
    }
    return null;
}
 
Example 15
Source Project: openjdk-8   File: Utils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the name of the local host.
 *
 * @return The host name
 * @throws UnknownHostException if IP address of a host could not be determined
 */
public static String getHostname() throws UnknownHostException {
    InetAddress inetAddress = InetAddress.getLocalHost();
    String hostName = inetAddress.getHostName();

    assertTrue((hostName != null && !hostName.isEmpty()),
            "Cannot get hostname");

    return hostName;
}
 
Example 16
public static String getLocalHostname() {
    InetAddress address;
    String hostname;
    try {
        address = InetAddress.getLocalHost();
        // force a best effort reverse DNS lookup
        hostname = address.getHostName();
        if (StringUtil.isEmpty(hostname)) {
            hostname = address.toString();
        }
    } catch (UnknownHostException noIpAddrException) {
        hostname = LOCALHOST;
    }
    return hostname;
}
 
Example 17
Source Project: jdk8u_jdk   File: Utils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the name of the local host.
 *
 * @return The host name
 * @throws UnknownHostException if IP address of a host could not be determined
 */
public static String getHostname() throws UnknownHostException {
    InetAddress inetAddress = InetAddress.getLocalHost();
    String hostName = inetAddress.getHostName();

    assertTrue((hostName != null && !hostName.isEmpty()),
            "Cannot get hostname");

    return hostName;
}
 
Example 18
public static void main(String[] args) throws Exception {

        InetAddress localAddress = InetAddress.getLocalHost();
        String[] hostlist = new String[] {
            localAddress.getHostAddress(), localAddress.getHostName() };

        for (int i = 0; i < hostlist.length; i++) {

            System.setProperty("java.rmi.server.hostname", hostlist[i]);
            Remote impl = new ChangeHostName();
            System.err.println("\ncreated impl extending URO: " + impl);

            Receiver stub = (Receiver) RemoteObject.toStub(impl);
            System.err.println("stub for impl: " + stub);

            System.err.println("invoking method on stub");
            stub.receive(stub);

            UnicastRemoteObject.unexportObject(impl, true);
            System.err.println("unexported impl");

            if (stub.toString().indexOf(hostlist[i]) >= 0) {
                System.err.println("stub's ref contains hostname: " +
                                   hostlist[i]);
            } else {
                throw new RuntimeException(
                    "TEST FAILED: stub's ref doesn't contain hostname: " +
                    hostlist[i]);
            }
        }
        System.err.println("TEST PASSED");
    }
 
Example 19
Source Project: DeviceConnect-Android   File: HostInfo.java    License: MIT License 4 votes vote down vote up
/**
 * @param address
 *            IP address to bind
 * @param dns
 *            JmDNS instance
 * @param jmdnsName
 *            JmDNS name
 * @return new HostInfo
 */
public static HostInfo newHostInfo(InetAddress address, JmDNSImpl dns, String jmdnsName) {
	Log.i("mDNS","newHostInfo");
    HostInfo localhost = null;
    String aName = "";
    InetAddress addr = address;
    Log.i("mDNS","addr:"+addr);

    try {
        if (addr == null) {
        	
            String ip = System.getProperty("net.mdns.interface");
            Log.i("mDNS","ip"+ip);
            if (ip != null) {
                addr = InetAddress.getByName(ip);
            } else {
                addr = InetAddress.getLocalHost();
                Log.i("mDNS","addr:"+addr);
                if (addr.isLoopbackAddress()) {
                    // Find local address that isn't a loopback address
                    InetAddress[] addresses = NetworkTopologyDiscovery.Factory.getInstance().getInetAddresses();
                    if (addresses.length > 0) {
                        addr = addresses[0];
                    }
                }
            }
            
            aName = addr.getHostName();
            if (addr.isLoopbackAddress()) {
                logger.warning("Could not find any address beside the loopback.");
            }
        } else {
        	
            aName = addr.getHostName();
            
        }
        if (aName.contains("in-addr.arpa") || (aName.equals(addr.getHostAddress()))) {
            aName = ((jmdnsName != null) && (jmdnsName.length() > 0) ? jmdnsName : addr.getHostAddress());
        }
    } catch (final IOException e) {
    	
        logger.log(Level.WARNING, "Could not intialize the host network interface on " + address + "because of an error: " + e.getMessage(), e);
        // This is only used for running unit test on Debian / Ubuntu
        addr = loopbackAddress();
        aName = ((jmdnsName != null) && (jmdnsName.length() > 0) ? jmdnsName : "computer");
    }
    // A host name with "." is illegal. so strip off everything and append .local.
    aName = aName.replace('.', '-');
    aName += ".local.";
    localhost = new HostInfo(addr, aName, dns);
    return localhost;
}
 
Example 20
Source Project: AndroidNetworkTools   File: PingNative.java    License: Apache License 2.0 4 votes vote down vote up
public static PingResult ping(InetAddress host, PingOptions pingOptions) throws IOException, InterruptedException {
    PingResult pingResult = new PingResult(host);

    if (host == null) {
        pingResult.isReachable = false;
        return pingResult;
    }

    StringBuilder echo = new StringBuilder();
    Runtime runtime = Runtime.getRuntime();

    int timeoutSeconds = Math.max(pingOptions.getTimeoutMillis() / 1000, 1);
    int ttl = Math.max(pingOptions.getTimeToLive(), 1);

    String address = host.getHostAddress();
    String pingCommand = "ping";

    if (address != null) {
        if (IPTools.isIPv6Address(address)) {
            // If we detect this is a ipv6 address, change the to the ping6 binary
            pingCommand = "ping6";
        } else if (!IPTools.isIPv4Address(address)) {
            // Address doesn't look to be ipv4 or ipv6, but we could be mistaken

        }
    } else {
        // Not sure if getHostAddress ever returns null, but if it does, use the hostname as a fallback
        address = host.getHostName();
    }

    Process proc = runtime.exec(pingCommand + " -c 1 -W " + timeoutSeconds + " -t " + ttl + " " + address);
    proc.waitFor();
    int exit = proc.exitValue();
    String pingError;
    switch (exit) {
        case 0:
            InputStreamReader reader = new InputStreamReader(proc.getInputStream());
            BufferedReader buffer = new BufferedReader(reader);
            String line;
            while ((line = buffer.readLine()) != null) {
                echo.append(line).append("\n");
            }
            return getPingStats(pingResult, echo.toString());
        case 1:
            pingError = "failed, exit = 1";
            break;
        default:
            pingError = "error, exit = 2";
            break;
    }
    pingResult.error = pingError;
    proc.destroy();
    return pingResult;
}