Example usage for java.net InetAddress getLocalHost

List of usage examples for java.net InetAddress getLocalHost

Introduction

In this page you can find the example usage for java.net InetAddress getLocalHost.

Prototype

public static InetAddress getLocalHost() throws UnknownHostException 

Source Link

Document

Returns the address of the local host.

Usage

From source file:de.thingweb.servient.ServientTestHttp.java

@Test
public void readTD() throws Exception {
    String fromSrv = TestTools.fromUrl("http://localhost:8080/things/SimpleThing/.td");
    String orig = readResource("simplething.jsonld");

    orig = orig.replace("localhost", InetAddress.getLocalHost().getHostName());

    ObjectNode srvJson = (ObjectNode) ContentHelper.readJSON(fromSrv);
    JsonNode origJson = ContentHelper.readJSON(orig);

    Thing td = ThingDescriptionParser.fromBytes(fromSrv.getBytes());
    Thing reference = ThingDescriptionParser.fromBytes(orig.getBytes());

    assertThat("jsonld context should match", srvJson.get("@context"), equalTo(origJson.get("@context")));
    //        assertThat("metadata content should match",srvJson.get("metadata"),equalTo(origJson.get("metadata")));
    //        assertThat("interactions should match",srvJson.get("interactions"),equalTo(origJson.get("interactions")));

    //        assertThat(ContentHelper.getJsonMapper().valueToTree(td),equalTo(ContentHelper.getJsonMapper().valueToTree(reference)));

    // TODO !//from ww  w.ja v a 2 s  . c  o m
}

From source file:org.trpr.platform.core.impl.management.jmx.JMXNotificationDispatcher.java

/** 
 * Helper method to return the local host IP address, enclosed in "[" "]", to be appended to messages.
 * @return the local host's IP address or the String "UnknownHost" in case of errors
 *///  w  w w . j  a va2s  .  c o  m
private String getHostIP() {
    try {
        return "[" + InetAddress.getLocalHost().getHostAddress() + "] ";
    } catch (UnknownHostException uhe) {
        // do nothing.
    }
    return "[UnknownHost]";
}

From source file:jhttpp2.Jhttpp2HTTPSession.java

/** sends a message to the user */
public void sendErrorMSG(int a, String info) throws IOException {
    String statuscode = sendHeader(a);
    String localhost = "localhost";
    try {/*w  w  w. j  a va  2 s .  c  om*/
        localhost = InetAddress.getLocalHost().getHostName() + ":" + server.port;
    } catch (UnknownHostException e_unknown_host) {
    }
    String msg = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"><html>\r"
            + "<!-- jHTTPp2 error message --><HEAD>\r" + "<TITLE>" + statuscode + "</TITLE>\r"
            + "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://" + localhost + "/style.css\"></HEAD>\r" // use css style sheet in htdocs
            + "<BODY BGCOLOR=\"#FFFFFF\" TEXT=\"#000000\" LINK=\"#000080\" VLINK=\"#000080\" ALINK=\"#000080\">\r"
            + "<h2 class=\"headline\">HTTP " + statuscode + " </h2>\r" + "<HR size=\"4\">\r"
            + "<p class=\"i30\">Your request for the following URL failed:</p>"
            + "<p class=\"tiagtext\"><a href=\"" + in.getFullURL() + "\">" + in.getFullURL() + "</A> </p>\r"
            + "<P class=\"i25\">Reason: " + info + "</P>" + "<HR size=\"4\">\r"
            + "<p class=\"i25\"><A HREF=\"http://jhttp2.sourceforge.net/\">jHTTPp2</A> HTTP Proxy, Version "
            + server.getServerVersion() + " at " + localhost
            + "<br>Copyright &copy; 2001-2003 <A HREF=\"mailto:bkohl@users.sourceforge.net\">Benjamin Kohl</A></p>\r"
            + "<p class=\"i25\"><A HREF=\"http://" + localhost
            + "/\">jHTTPp2 local website</A> <A HREF=\"http://" + localhost + "/" + server.WEB_CONFIG_FILE
            + "\">Configuration</A></p>" + "</BODY></HTML>";
    sendLine("Content-Length", String.valueOf(msg.length()));
    sendLine("Content-Type", "text/html; charset=iso-8859-1");
    endHeader();
    write(out, msg);
    out.flush();
}

From source file:in.gov.uidai.auth.aua.httpclient.AuthClient.java

/**
 * Method to perform authentication/*from www  .j  a  va 2s  .c o m*/
 * @param auth Authentication request
 * @return Authentication response
 */
public AuthResponseDetails authenticate(Auth auth) {
    try {
        String signedXML = generateSignedAuthXML(auth);
        System.out.println(signedXML);

        String uriString = authServerURI.toString() + (authServerURI.toString().endsWith("/") ? "" : "/")
                + auth.getAc() + "/" + auth.getUid().charAt(0) + "/" + auth.getUid().charAt(1);

        if (StringUtils.isNotBlank(asaLicenseKey)) {
            uriString = uriString + "/" + asaLicenseKey;
        }

        URI authServiceURI = new URI(uriString);

        WebResource webResource = Client.create(HttpClientHelper.getClientConfig(authServerURI.getScheme()))
                .resource(authServiceURI);

        String responseXML = webResource.header("REMOTE_ADDR", InetAddress.getLocalHost().getHostAddress())
                .post(String.class, signedXML);

        System.out.println(responseXML);

        return new AuthResponseDetails(responseXML, parseAuthResponseXML(responseXML));

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception during authentication " + e.getMessage(), e);
    }
}

From source file:com.zotoh.maedr.device.TcpIO.java

private ServerSocket createSvrSockIt() throws IOException {

    InetAddress ip;/*from  w w w .  j a  v  a 2s .  c o  m*/
    ip = isEmpty(_host) ? InetAddress.getLocalHost() : InetAddress.getByName(_host);

    ServerSocket soc = new ServerSocket(_port, _backlog, ip);
    ServerSocket s = null;
    try {
        soc.setReuseAddress(true);
        s = soc;
        soc = null;
    } finally {
        NetUte.close(soc);
    }

    tlog().debug("TCP: opened server socket: {} on host: {}", _port, _host);
    return s;
}

From source file:com.tc.config.schema.setup.BaseConfigurationSetupManagerTest.java

public void testServerDefaults2() throws IOException, ConfigurationSetupException {
    this.tcConfig = getTempFile("default-config.xml");
    String config = "<tc-config xmlns=\"http://www.terracotta.org/config\">" + "<servers>" + "<server>"
            + "<tsa-port>8513</tsa-port>" + "</server>" + "</servers>" + "</tc-config>";

    writeConfigFile(config);/*from  w  w w  . ja  v a 2s .com*/

    BaseConfigurationSetupManager configSetupMgr = initializeAndGetBaseTVSConfigSetupManager(false);

    Servers servers = configSetupMgr.serversBeanRepository();

    Server server = servers.getServer().get(0);

    Assert.assertEquals(InetAddress.getLocalHost().getHostAddress(), server.getHost());
    Assert.assertEquals("0.0.0.0", server.getBind());
    Assert.assertEquals(InetAddress.getLocalHost().getHostAddress() + ":" + server.getTsaPort().getValue(),
            server.getName());

    int tsaPort = 8513;

    Assert.assertEquals(tsaPort, server.getTsaPort().getValue());
    Assert.assertEquals(server.getBind(), server.getTsaPort().getBind());

    int tempGroupPort = tsaPort + L2ConfigObject.DEFAULT_GROUPPORT_OFFSET_FROM_TSAPORT;
    int defaultGroupPort = ((tempGroupPort <= L2ConfigObject.MAX_PORTNUMBER) ? (tempGroupPort)
            : (tempGroupPort % L2ConfigObject.MAX_PORTNUMBER) + L2ConfigObject.MIN_PORTNUMBER);

    Assert.assertEquals(defaultGroupPort, server.getTsaGroupPort().getValue());
    Assert.assertEquals(server.getBind(), server.getTsaGroupPort().getBind());

}

From source file:net.pms.network.HTTPServer.java

public boolean start() throws IOException {
    hostname = configuration.getServerHostname();
    InetSocketAddress address;//w  w  w .  j ava2  s . c o  m

    if (StringUtils.isNotBlank(hostname)) {
        logger.info("Using forced address " + hostname);
        InetAddress tempIA = InetAddress.getByName(hostname);

        if (tempIA != null && networkInterface != null
                && networkInterface.equals(NetworkInterface.getByInetAddress(tempIA))) {
            address = new InetSocketAddress(tempIA, port);
        } else {
            address = new InetSocketAddress(hostname, port);
        }
    } else if (isAddressFromInterfaceFound(configuration.getNetworkInterface())) { // XXX sets iafinal and networkInterface
        logger.info("Using address {} found on network interface: {}", iafinal,
                networkInterface.toString().trim().replace('\n', ' '));
        address = new InetSocketAddress(iafinal, port);
    } else {
        logger.info("Using localhost address");
        address = new InetSocketAddress(port);
    }

    logger.info("Created socket: " + address);

    if (configuration.isHTTPEngineV2()) { // HTTP Engine V2
        group = new DefaultChannelGroup("myServer");
        factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());

        ServerBootstrap bootstrap = new ServerBootstrap(factory);
        HttpServerPipelineFactory pipeline = new HttpServerPipelineFactory(group);
        bootstrap.setPipelineFactory(pipeline);
        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);
        bootstrap.setOption("reuseAddress", true);
        bootstrap.setOption("child.reuseAddress", true);
        bootstrap.setOption("child.sendBufferSize", 65536);
        bootstrap.setOption("child.receiveBufferSize", 65536);
        channel = bootstrap.bind(address);
        group.add(channel);

        if (hostname == null && iafinal != null) {
            hostname = iafinal.getHostAddress();
        } else if (hostname == null) {
            hostname = InetAddress.getLocalHost().getHostAddress();
        }
    } else { // HTTP Engine V1
        serverSocketChannel = ServerSocketChannel.open();

        serverSocket = serverSocketChannel.socket();
        serverSocket.setReuseAddress(true);
        serverSocket.bind(address);

        if (hostname == null && iafinal != null) {
            hostname = iafinal.getHostAddress();
        } else if (hostname == null) {
            hostname = InetAddress.getLocalHost().getHostAddress();
        }

        runnable = new Thread(this, "HTTP Server");
        runnable.setDaemon(false);
        runnable.start();
    }

    return true;
}

From source file:dk.netarkivet.viewerproxy.WebProxyTester.java

/**
 * Test the general integration of the WebProxy access through the running Jetty true:
 *//* w  w w .jav  a  2 s .  co  m*/
@Test
public void testJettyIntegration() throws Exception {
    TestURIResolver uriResolver = new TestURIResolver();
    proxy = new WebProxy(uriResolver);

    try {
        new Socket(InetAddress.getLocalHost(), httpPort);
    } catch (IOException e) {
        fail("Port not in use after starting server");
    }

    // GET request
    HttpClient client = new HttpClient();
    HostConfiguration hc = new HostConfiguration();
    String hostName = SystemUtils.getLocalHostName();
    hc.setProxy(hostName, httpPort);
    client.setHostConfiguration(hc);
    GetMethod get = new GetMethod("http://foo.bar/");
    client.executeMethod(get);

    assertEquals("Status code should be what URI resolver gives", 242, get.getStatusCode());
    assertEquals("Body should contain what URI resolver wrote", "Test", get.getResponseBodyAsString());
    get.releaseConnection();

    // POST request
    PostMethod post = new PostMethod("http://foo2.bar/");
    post.addParameter("a", "x");
    post.addParameter("a", "y");
    client.executeMethod(post);

    // Check request received by URIResolver
    assertEquals("URI resolver lookup should be called.", 2, uriResolver.lookupCount);
    assertEquals("URI resolver lookup should be called with right URI.", new URI("http://foo2.bar/"),
            uriResolver.lookupRequestArgument);
    assertEquals("Posted parameter should be received.", 1, uriResolver.lookupRequestParameteres.size());
    assertNotNull("Posted parameter should be received.", uriResolver.lookupRequestParameteres.get("a"));
    assertEquals("Posted parameter should be received.", 2,
            uriResolver.lookupRequestParameteres.get("a").length);
    assertEquals("Posted parameter should be received.", "x", uriResolver.lookupRequestParameteres.get("a")[0]);
    assertEquals("Posted parameter should be received.", "y", uriResolver.lookupRequestParameteres.get("a")[1]);
    assertEquals("Status code should be what URI resolver gives", 242, post.getStatusCode());
    assertEquals("Body should contain what URI resolver wrote", "Test", post.getResponseBodyAsString());
    post.releaseConnection();

    // Request with parameter and portno
    get = new GetMethod("http://foo2.bar:8090/?baz=boo");
    client.executeMethod(get);

    // Check request received by URIResolver
    assertEquals("URI resolver lookup should be called.", 3, uriResolver.lookupCount);
    assertEquals("URI resolver 2 lookup should be called with right URI.",
            new URI("http://foo2.bar:8090/?baz=boo"), uriResolver.lookupRequestArgument);
    assertEquals("Status code should be what URI resolver gives", 242, get.getStatusCode());
    assertEquals("Body should contain what URI resolver wrote", "Test", get.getResponseBodyAsString());
    get.releaseConnection();
}

From source file:net.grinder.util.NetworkUtil.java

/**
 * 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.
 * /*from  w  ww  .  j  a v a 2s. co m*/
 * @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);

}