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

The following are Jave code examples for showing how to use getHostName() of the java.net.InetAddress class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: T0rlib4j   File: SocksSocket.java   Source Code and License Vote up 6 votes
/**
 * 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 2
Project: openrasp   File: SyslogTcpAppender.java   Source Code and License Vote up 6 votes
void connect(InetAddress address, int port) {
   if(this.address == null)
     return;
   try {
     // First, close the previous connection if any.
     cleanUp();
     stw = new SyslogTcpWriter(new Socket(address, port).getOutputStream(), syslogFacility);
   } catch(IOException e) {
     if (e instanceof InterruptedIOException) {
         Thread.currentThread().interrupt();
     }
     String msg = "Could not connect to remote log4j server at ["
+address.getHostName()+"].";
     if(reconnectionDelay > 0) {
       msg += " We will try again later.";
fireConnector(); // fire the connector thread
     } else {
         msg += " We are not retrying.";
         errorHandler.error(msg, e, ErrorCode.GENERIC_FAILURE);
     } 
     LogLog.error(msg);
   }
 }
 
Example 3
Project: ats-framework   File: AtsJunitTestListener.java   Source Code and License Vote up 6 votes
/**
*
* @see org.junit.runner.notification.RunListener#testRunStarted(org.junit.runner.Description)
*/
@Override
public void testRunStarted( Description description ) throws Exception {

    if (log.isDebugEnabled()) { // currently always returns null for Description parameter
        log.debug("testRunStarted(): Called before any test is run. Description of all tests expected: "
                  + description);
    }
    String runNameSysProp = AtsSystemProperties.getPropertyAsString(AtsSystemProperties.TEST_HARNESS__JUNIT_RUN_NAME,
                                                                    "JUnit run(nameless)");

    String hostNameIp = "";
    try {
        InetAddress addr = InetAddress.getLocalHost();
        hostNameIp = addr.getHostName() + "/" + addr.getHostAddress();

    } catch (UnknownHostException uhe) {
        hostNameIp = null;
    }

    logger.startRun(runNameSysProp /* no suite name in JUnit */, CommonConfigurator.getInstance().getOsName(),
                    CommonConfigurator.getInstance().getProductName(),
                    CommonConfigurator.getInstance().getVersionName(),
                    CommonConfigurator.getInstance().getBuildName(), hostNameIp);
    super.testRunStarted(description);
}
 
Example 4
Project: dubbocloud   File: NetUtils.java   Source Code and License Vote up 6 votes
public static String getHostName(String address) {
  	try {
  		int i = address.indexOf(':');
  		if (i > -1) {
  			address = address.substring(0, i);
  		}
  		String hostname = hostNameCache.get(address);
  		if (hostname != null && hostname.length() > 0) {
  			return hostname;
  		}
  		InetAddress inetAddress = InetAddress.getByName(address);
  		if (inetAddress != null) {
  			hostname = inetAddress.getHostName();
  			hostNameCache.put(address, hostname);
  			return hostname;
  		}
} catch (Throwable e) {
	// ignore
}
return address;
  }
 
Example 5
Project: openrasp   File: SyslogTcpAppender.java   Source Code and License Vote up 5 votes
/**
   Connects to remote server at <code>address</code> and <code>port</code>.
*/
public SyslogTcpAppender(InetAddress address, int port, int syslogFacility) {
  this.address = address;
  this.remoteHost = address.getHostName();
  this.port = port;
  this.syslogFacility = syslogFacility;
  this.initSyslogFacilityStr();
  connect(address, port);
}
 
Example 6
Project: T0rlib4Android   File: Socks5Message.java   Source Code and License Vote up 5 votes
/**
 * Construct client request or server response.
 * 
 * @param cmd
 *            - Request/Response code.
 * @param ip
 *            - IP field.
 * @paarm port - port field.
 */
public Socks5Message(int cmd, InetAddress ip, int port) {
	super(cmd, ip, port);

	if (ip == null) {
		this.host = "0.0.0.0";
	} else {
		this.host = ip.getHostName();
	}

	this.version = SOCKS_VERSION;

	byte[] addr;

	if (ip == null) {
		addr = new byte[4];
		addr[0] = addr[1] = addr[2] = addr[3] = 0;
	} else {
		addr = ip.getAddress();
	}

	if (addr.length == 4) {
		addrType = SOCKS_ATYP_IPV4;
	} else {
		addrType = SOCKS_ATYP_IPV6;
	}

	data = new byte[6 + addr.length];
	data[0] = (byte) SOCKS_VERSION; // Version
	data[1] = (byte) command; // Command
	data[2] = (byte) 0; // Reserved byte
	data[3] = (byte) addrType; // Address type

	// Put Address
	System.arraycopy(addr, 0, data, 4, addr.length);
	// Put port
	data[data.length - 2] = (byte) (port >> 8);
	data[data.length - 1] = (byte) (port);
}
 
Example 7
Project: sstore-soft   File: ConnectionUtil.java   Source Code and License Vote up 5 votes
public static String getHostnameOrAddress() {
    try {
        final InetAddress addr = InetAddress.getLocalHost();
        return addr.getHostName();
    } catch (UnknownHostException e) {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces == null) {
                return "";
            }
            NetworkInterface intf = interfaces.nextElement();
            Enumeration<InetAddress> addresses = intf.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                if (address instanceof Inet4Address) {
                    return address.getHostAddress();
                }
            }
            interfaces = NetworkInterface.getNetworkInterfaces();
            while (addresses.hasMoreElements()) {
                return addresses.nextElement().getHostAddress();
            }
            return "";
        } catch (SocketException e1) {
            return "";
        }
    }
}
 
Example 8
Project: jdk8u-jdk   File: Utils.java   Source Code and License Vote up 5 votes
/**
 * 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 9
Project: hadoop   File: RpcProgramMountd.java   Source Code and License Vote up 5 votes
@Override
public XDR umnt(XDR xdr, XDR out, int xid, InetAddress client) {
  String path = xdr.readString();
  if (LOG.isDebugEnabled()) {
    LOG.debug("MOUNT UMNT path: " + path + " client: " + client);
  }
  
  String host = client.getHostName();
  mounts.remove(new MountEntry(host, path));
  RpcAcceptedReply.getAcceptInstance(xid, new VerifierNone()).write(out);
  return out;
}
 
Example 10
Project: csap-core   File: Application.java   Source Code and License Vote up 5 votes
public boolean isHostAuthenticatedMember ( String ipAddress ) {
	try {
		InetAddress addr = InetAddress.getByName( ipAddress );
		String remoteServerName = addr.getHostName();

		if ( remoteServerName.equals( "127.0.0.1" ) ) {
			remoteServerName = "localhost";
		}

		if ( remoteServerName.contains( "." ) ) {
			remoteServerName = remoteServerName.substring( 0, remoteServerName.indexOf( "." ) );
		}

		if ( remoteServerName.equals( "rtp-someDeveloper-8811" ) && getCurrentLifeCycle().equals( "dev" ) ) {

			logger.warn( "DEVELOPER TESTING: Resolved: {} to host: {}", ipAddress, remoteServerName );
			return true;
		}
		logger.debug( "Resolved: {} to host: {}", ipAddress, remoteServerName );

		return getAllHostsInAllPackagesInCurrentLifecycle().contains( remoteServerName );

	} catch (Exception e) {
		logger.error( "Failed to get hostname" );
	}

	return false;
}
 
Example 11
Project: VASSAL-src   File: PendingPeerManager.java   Source Code and License Vote up 5 votes
public void addNewPeer(Socket pSocket) {
  IllegalArgument.ifNull("Socket", pSocket);
  InetAddress theirAddress = pSocket.getInetAddress();
  String theirName = theirAddress.getHostName();
  String theirIP = theirAddress.getHostAddress();
  String name = theirIP.equals(theirName) ? null : "(Host: " + theirName + ")";
  zPendingPeers.add(pSocket, new PeerInfo(name, theirIP));
}
 
Example 12
Project: java-android-websocket-client   File: RequestTargetHost.java   Source Code and License Vote up 5 votes
@Override
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    Args.notNull(request, "HTTP request");

    final HttpCoreContext corecontext = HttpCoreContext.adapt(context);

    final ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
    final String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase("CONNECT") && ver.lessEquals(HttpVersion.HTTP_1_0)) {
        return;
    }

    if (!request.containsHeader(HTTP.TARGET_HOST)) {
        HttpHost targethost = corecontext.getTargetHost();
        if (targethost == null) {
            final HttpConnection conn = corecontext.getConnection();
            if (conn instanceof HttpInetConnection) {
                // Populate the context with a default HTTP host based on the
                // inet address of the target host
                final InetAddress address = ((HttpInetConnection) conn).getRemoteAddress();
                final int port = ((HttpInetConnection) conn).getRemotePort();
                if (address != null) {
                    targethost = new HttpHost(address.getHostName(), port);
                }
            }
            if (targethost == null) {
                if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
                    return;
                } else {
                    throw new ProtocolException("Target host missing");
                }
            }
        }
        request.addHeader(HTTP.TARGET_HOST, targethost.toHostString());
    }
}
 
Example 13
Project: s-store   File: ConnectionUtil.java   Source Code and License Vote up 5 votes
public static String getHostnameOrAddress() {
    try {
        final InetAddress addr = InetAddress.getLocalHost();
        return addr.getHostName();
    } catch (UnknownHostException e) {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces == null) {
                return "";
            }
            NetworkInterface intf = interfaces.nextElement();
            Enumeration<InetAddress> addresses = intf.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                if (address instanceof Inet4Address) {
                    return address.getHostAddress();
                }
            }
            interfaces = NetworkInterface.getNetworkInterfaces();
            while (addresses.hasMoreElements()) {
                return addresses.nextElement().getHostAddress();
            }
            return "";
        } catch (SocketException e1) {
            return "";
        }
    }
}
 
Example 14
Project: ibm-cos-sdk-java   File: AwsHostNameUtils.java   Source Code and License Vote up 5 votes
/**
 * Returns the host name for the local host. If the operation is not allowed
 * by the security check, the textual representation of the IP address of
 * the local host is returned instead. If the ip address of the local host
 * cannot be resolved or if there is any other failure, "localhost" is
 * returned as a fallback.
 */
public static String localHostName() {
    try {
        InetAddress localhost = InetAddress.getLocalHost();
        return localhost.getHostName();
    } catch (Exception e) {
        InternalLogFactory.getLog(AwsHostNameUtils.class)
            .debug(
                "Failed to determine the local hostname; fall back to "
                        + "use \"localhost\".", e);
        return "localhost";
    }
}
 
Example 15
Project: csap-core   File: Application.java   Source Code and License Vote up 5 votes
private void updateApplicationVariables ()
		throws UnknownHostException {

	httpdIntegration.updateConstants();

	WAR_DIR = STAGING + CSAP_SERVICE_PACKAGES;
	BUILD_DIR = STAGING + "/build/";
	// Use relative paths to handle all use cases
	CSAP_DEFINITION_FOLDER_FOR_JUNITs = getDefinitionFile()
		.getParentFile()
		.getAbsolutePath();
	InetAddress addr = InetAddress.getLocalHost();

	// Get hostname
	HOST_NAME = addr.getHostName();
	if ( HOST_NAME.indexOf( "." ) != -1 ) {
		// in case of host.somecompany.com, strip off domain
		HOST_NAME = HOST_NAME.substring( 0, HOST_NAME.indexOf( "." ) );
	}

	// hook for testing on eclipse
	logger.info( "Host name is: {}", HOST_NAME );
	if ( isRunningOnDesktop() ) {
		HOST_NAME = "localhost";
		//
		logger.info( "\n\n Did not find STAGING env var,  forcing test mode - setting host to localhost \n\n" );
	}

	if ( isJvmInManagerMode() ) {
		refreshConfigHandleOnlyOnMgrs = refreshConfigPool.scheduleWithFixedDelay(
			new Runnable() {

				@Override
				public void run () {
					updateCache( false );
				}
			}, 10, 10, TimeUnit.SECONDS );
	}
}
 
Example 16
Project: openjdk-jdk10   File: ChangeHostName.java   Source Code and License Vote up 5 votes
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 17
Project: openjdk-jdk10   File: TCPEndpoint.java   Source Code and License Vote up 5 votes
/**
 * Do our best to obtain a fully qualified hostname for the local
 * host.  Perform the following steps to get a localhostname:
 *
 * 1. InetAddress.getLocalHost().getHostName() - if contains
 *    '.' use as FQDN
 * 2. if no '.' query name service for FQDN in a thread
 *    Note: We query the name service for an FQDN by creating
 *    an InetAddress via a stringified copy of the local ip
 *    address; this creates an InetAddress with a null hostname.
 *    Asking for the hostname of this InetAddress causes a name
 *    service lookup.
 *
 * 3. if name service takes too long to return, use ip address
 * 4. if name service returns but response contains no '.'
 *    default to ipaddress.
 */
static String attemptFQDN(InetAddress localAddr)
    throws java.net.UnknownHostException
{

    String hostName = localAddr.getHostName();

    if (hostName.indexOf('.') < 0 ) {

        String hostAddress = localAddr.getHostAddress();
        FQDN f = new FQDN(hostAddress);

        int nameServiceTimeOut =
            TCPEndpoint.getInt("sun.rmi.transport.tcp.localHostNameTimeOut",
                               10000);

        try {
            synchronized(f) {
                f.getFQDN();

                /* wait to obtain an FQDN */
                f.wait(nameServiceTimeOut);
            }
        } catch (InterruptedException e) {
            /* propagate the exception to the caller */
            Thread.currentThread().interrupt();
        }
        hostName = f.getHost();

        if ((hostName == null) || (hostName.equals(""))
            || (hostName.indexOf('.') < 0 )) {

            hostName = hostAddress;
        }
    }
    return hostName;
}
 
Example 18
Project: hadoop-oss   File: LoadGenerator.java   Source Code and License Vote up 4 votes
/** Constructor */
public LoadGenerator() throws IOException, UnknownHostException {
  InetAddress addr = InetAddress.getLocalHost();
  hostname = addr.getHostName();
  Arrays.fill(WRITE_CONTENTS, (byte) 'a');
}
 
Example 19
Project: shabdiz   File: AbstractHost.java   Source Code and License Vote up 4 votes
protected AbstractHost(final InetAddress address) {

        this.address = address;
        local = NetworkUtil.isValidLocalAddress(address);
        name = address.getHostName();
    }
 
Example 20
Project: lighthouse   File: HttpHost.java   Source Code and License Vote up 2 votes
/**
 * Creates {@code HttpHost} instance with the given scheme, inet address and port.
 *
 * @param address   the inet address.
 * @param port      the port number.
 *                  {@code -1} indicates the scheme default port.
 * @param scheme    the name of the scheme.
 *                  {@code null} indicates the
 *                  {@link #DEFAULT_SCHEME_NAME default scheme}
 *
 * @since 4.3
 */
public HttpHost(final InetAddress address, final int port, final String scheme) {
    this(Args.notNull(address,"Inet address"), address.getHostName(), port, scheme);
}