java.net.InetAddress#getHostName ( )源码实例Demo

下面列出了java.net.InetAddress#getHostName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: metrics-kafka   文件: HostUtil.java
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;
}
 
源代码2 项目: T0rlib4Android   文件: SocksSocket.java
/**
 * 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));
	}
}
 
源代码3 项目: uuid-creator   文件: NetworkData.java
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;
}
 
源代码4 项目: sofa-bolt   文件: RemotingUtilTest.java
/**
 * 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);
}
 
源代码5 项目: flink   文件: TaskManagerRunner.java
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();
}
 
源代码6 项目: codewind-eclipse   文件: PlatformUtil.java
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");
  }
 
源代码7 项目: fess   文件: AdminMaintenanceAction.java
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();
}
 
源代码8 项目: oodt   文件: AvroRpcWorkflowManager.java
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;
}
 
源代码9 项目: apollo   文件: MachineInfo.java
/**
 * @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();
    }
}
 
源代码10 项目: disconf   文件: MachineInfo.java
/**
 * @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);
    }
}
 
源代码11 项目: openjdk-jdk9   文件: Utils.java
/**
 * 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;
}
 
源代码12 项目: TencentKona-8   文件: Utils.java
/**
 * 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;
}
 
源代码13 项目: Openfire   文件: NIOConnection.java
@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();
}
 
源代码14 项目: cxf   文件: HttpServletRequestAdapter.java
public String getRemoteHost() {
    InetSocketAddress isa = exchange.getRemoteAddress();
    if (isa != null) {
        InetAddress ia = isa.getAddress();
        if (ia != null) {
            return ia.getHostName();
        }
    }
    return null;
}
 
源代码15 项目: openjdk-8   文件: Utils.java
/**
 * 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;
}
 
源代码16 项目: common-utils   文件: NetworkUtil.java
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;
}
 
源代码17 项目: jdk8u_jdk   文件: Utils.java
/**
 * 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;
}
 
源代码18 项目: openjdk-jdk9   文件: ChangeHostName.java
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");
    }
 
源代码19 项目: DeviceConnect-Android   文件: HostInfo.java
/**
 * @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;
}
 
源代码20 项目: AndroidNetworkTools   文件: PingNative.java
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;
}