Example usage for java.net InetAddress getLoopbackAddress

List of usage examples for java.net InetAddress getLoopbackAddress

Introduction

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

Prototype

public static InetAddress getLoopbackAddress() 

Source Link

Document

Returns the loopback address.

Usage

From source file:com.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java

protected void sendTo(int aPort, String anEncodedMessage) {
    SocketChannel socketChannel = null;

    try {/*from   w  ww . jav  a  2 s  .com*/
        socketChannel = SocketChannel.open();
        InetSocketAddress address = new InetSocketAddress(InetAddress.getLoopbackAddress(), aPort);
        socketChannel.connect(address);
        socketChannel.write(ByteBuffer.wrap(anEncodedMessage.getBytes()));
        logger.debug("Sent: {}", anEncodedMessage);

    } catch (IOException e) {
        logger.error("Failed to send because: {}: Continuing...", e.getMessage(), e);
    } finally {
        if (socketChannel != null) {
            try {
                socketChannel.close();
            } catch (IOException e) {
                logger.error("Failed to close client socket because: {}: Continuing...", e.getMessage(), e);
            }
        }
    }
}

From source file:it.mbcraft.command_server.engine.CommandServer.java

/**
 * Starts the server//w  w w .  j  av  a2  s  .  c o m
 *
 */
@Override
public void start() {

    try {
        System.out.print("Starting command server ...");

        SocketConfig config = SocketConfig.custom().setSoTimeout(15000).setTcpNoDelay(true).setBacklogSize(2)
                .setSoKeepAlive(false).build();

        server = ServerBootstrap.bootstrap().setListenerPort(listenPort)
                .setLocalAddress(InetAddress.getLoopbackAddress()).setServerInfo("Java:CommandServer/1.1")
                .setSocketConfig(config).setExceptionLogger(ExceptionLogger.NO_OP)
                .registerHandler("*", new HttpCommandHandler()).create();

        server.start();

        System.out.println("done!");
    } catch (IOException ex) {
        Logger.getLogger(CommandServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.opendaylight.infrautils.diagstatus.internal.ClusterMemberInfoImpl.java

@Override
public boolean isLocalAddress(InetAddress ipAddress) {
    return ipAddress.equals(InetAddress.getLoopbackAddress()) || ipAddress.equals(getSelfAddress());
}

From source file:org.sonar.application.config.JdbcSettings.java

private static String buildH2JdbcUrl(int embeddedDatabasePort) {
    InetAddress ip = InetAddress.getLoopbackAddress();
    String host;/*from  w w  w. ja  v a 2  s  .c om*/
    if (ip instanceof Inet6Address) {
        host = "[" + ip.getHostAddress() + "]";
    } else {
        host = ip.getHostAddress();
    }
    return format("jdbc:h2:tcp://%s:%d/sonar", host, embeddedDatabasePort);
}

From source file:org.opennms.gizmo.k8s.portforward.KubeCtlPortForwardingStrategy.java

@Override
public ForwardedPort portForward(String namespace, String pod, int remotePort) {
    CommandLine cmdLine = new CommandLine("kubectl");
    cmdLine.addArgument("--namespace=${namespace}");
    cmdLine.addArgument("port-forward");
    cmdLine.addArgument("${pod}");
    cmdLine.addArgument(":${remotePort}");

    HashMap<String, String> map = new HashMap<>();
    map.put("namespace", namespace);
    map.put("pod", pod);
    map.put("remotePort", Integer.toString(remotePort));
    cmdLine.setSubstitutionMap(map);//from  ww  w. jav  a  2s.com

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(out, err);

    DefaultExecutor executor = new DefaultExecutor();
    final ExecuteWatchdog wd = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(wd);
    executor.setStreamHandler(psh);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    final int localPort = waitForLocalPort(wd, out, err);
    return new ForwardedPort() {
        @Override
        public InetSocketAddress getAddress() {
            return new InetSocketAddress(InetAddress.getLoopbackAddress(), localPort);
        }

        @Override
        public void close() throws IOException {
            wd.destroyProcess();
        }

        @Override
        public String toString() {
            return String.format("ForwardedPort[localPort=%d]", localPort);
        }
    };
}

From source file:org.apache.hyracks.server.test.NCServiceIT.java

@Test
public void IsNodelistCorrect() throws Exception {
    // Ping the nodelist HTTP API
    String localhost = InetAddress.getLoopbackAddress().getHostAddress();
    String response = getHttp("http://" + localhost + ":12345/rest/nodes");
    JSONObject result = new JSONObject(response);
    JSONArray nodes = result.getJSONArray("result");
    int numNodes = nodes.length();
    Assert.assertEquals("Wrong number of nodes!", 2, numNodes);
    for (int i = 0; i < nodes.length(); i++) {
        JSONObject node = nodes.getJSONObject(i);
        String id = node.getString("node-id");
        if (id.equals("red") || id.equals("blue")) {
            continue;
        }//from   w w  w  .j  a v  a 2 s.com
        Assert.fail("Unexpected node ID '" + id + "'!");
    }
}

From source file:com.sittinglittleduck.DirBuster.EasySSLProtocolSocketFactoryUnitTest.java

@Test(expected = IllegalArgumentException.class)
public void shouldFailCreatingSocketForMissingParameters() throws Exception {
    // Given//from w  ww  .j a v a 2 s .  c o  m
    HttpConnectionParams nullParams = null;
    // When
    socketFactory.createSocket("localhost", 18080, InetAddress.getLoopbackAddress(), 12345, nullParams);
    // Then = IllegalArgumentException
}

From source file:com.machinepublishers.jbrowserdriver.diagnostics.HttpServer.java

public static void launch(int port) {
    if (loop.compareAndSet(false, true)) {
        new Thread(new Runnable() {
            @Override//from  w  w  w.j a va2  s.c  o  m
            public void run() {
                try (ServerSocket serverSocket = new ServerSocket(port, 50, InetAddress.getLoopbackAddress())) {
                    listener.set(serverSocket);
                    while (loop.get()) {
                        try (Socket socket = serverSocket.accept();
                                DataOutputStream output = new DataOutputStream(socket.getOutputStream());
                                BufferedReader reader = new BufferedReader(
                                        new InputStreamReader(socket.getInputStream()))) {
                            List<String> request = new ArrayList<String>();
                            for (String line; (line = reader.readLine()) != null;) {
                                request.add(line);
                                if (line.startsWith("GET / ")) {
                                    output.write(indexContent, 0, indexContent.length);
                                    output.write(indexBody, 0, indexBody.length);
                                } else if (line.startsWith("POST / ")) {
                                    output.write(postContent, 0, postContent.length);
                                    output.write(postBody, 0, postBody.length);
                                } else if (line.startsWith("GET /iframe.htm")) {
                                    output.write(iframeContent, 0, iframeContent.length);
                                    output.write(iframeBody, 0, iframeBody.length);
                                } else if (line.startsWith("GET /redirect/site1 ")) {
                                    output.write(redirectContent);
                                } else if (line.startsWith("GET /redirect/site2 ")) {
                                    output.write(iframeContent, 0, iframeContent.length);
                                    output.write(iframeBody, 0, iframeBody.length);
                                } else if (line.startsWith("GET /wait-forever ")) {
                                    synchronized (HttpServer.class) {
                                        HttpServer.class.wait();
                                    }
                                } else if (line.startsWith("GET /image.png")) {
                                    output.write(imageContent, 0, imageContent.length);
                                    output.write(imageBody, 0, imageBody.length);
                                }
                            }
                            previousRequest.set(request);
                            previousRequestId.incrementAndGet();
                        }
                    }
                } catch (Throwable t) {
                }
            }
        }).start();
    }
}

From source file:com.sittinglittleduck.DirBuster.EasySSLProtocolSocketFactoryUnitTest.java

@Test
public void shouldCreateSocketWithGivenLocalAddressAndPort() throws Exception {
    // Given//from   w  w  w  .j a va 2s .  c  o  m
    InetAddress localAddress = InetAddress.getLoopbackAddress();
    int localPort = 28080;
    // When
    Socket sslSocket = socketFactory.createSocket("localhost", 18080, localAddress, localPort,
            new HttpConnectionParams());
    // Then
    assertThat(sslSocket.getLocalAddress(), is(equalTo(localAddress)));
    assertThat(sslSocket.getLocalPort(), is(equalTo(localPort)));
}