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:Main.java

public static void main(String[] argv) throws Exception {
    InetAddress address = InetAddress.getLoopbackAddress();
    System.out.println("Name: " + address.getHostName());
    System.out.println("Addr: " + address.getHostAddress());
    System.out.println(address.isLoopbackAddress());
}

From source file:edu.umass.cs.reconfiguration.reconfigurationpackets.RequestActiveReplicas.java

public static void main(String[] args) {
    String[] addrs = { "128.119.240.21" };
    int[] ports = { 3245 };
    assert (addrs.length == ports.length);
    InetSocketAddress[] isaddrs = new InetSocketAddress[addrs.length];
    try {//from w ww.j av  a 2  s  .c  om
        for (int i = 0; i < addrs.length; i++) {
            isaddrs[i] = new InetSocketAddress(InetAddress.getByName(addrs[i]), ports[i]);
        }
        String name = "name";
        InetSocketAddress sender = new InetSocketAddress(InetAddress.getLoopbackAddress(), 1234);
        RequestActiveReplicas req1 = new RequestActiveReplicas(sender, name, 0);
        System.out.println(req1);
        JSONObject json1;
        json1 = req1.toJSONObject();
        RequestActiveReplicas req2 = new RequestActiveReplicas(json1, null);
        System.out.println(req2);
    } catch (UnknownHostException | JSONException e) {
        e.printStackTrace();
    }
}

From source file:net.sf.jasperreports.phantomjs.InetUtil.java

public static Inet4Address getIPv4Loopback() {
    InetAddress loopbackAddress = InetAddress.getLoopbackAddress();
    //the phantomjs web server module only works with IPv4
    if (loopbackAddress instanceof Inet4Address) {
        return (Inet4Address) loopbackAddress;
    }// w  ww  . j  a  v  a 2s  . com

    try {
        InetAddress[] addresses = InetAddress.getAllByName(loopbackAddress.getHostName());
        for (InetAddress inetAddress : addresses) {
            if (inetAddress instanceof Inet4Address) {
                return (Inet4Address) inetAddress;
            }
        }
    } catch (UnknownHostException e) {
        log.warn("Error while determining loopback addresses for " + loopbackAddress.getHostName(), e);
    }

    try {
        //keep looking for a IPv4 loopback address
        for (Enumeration<NetworkInterface> itfs = NetworkInterface.getNetworkInterfaces(); itfs
                .hasMoreElements();) {
            NetworkInterface itf = itfs.nextElement();
            if (itf.isLoopback()) {
                for (Enumeration<InetAddress> addresses = itf.getInetAddresses(); addresses
                        .hasMoreElements();) {
                    InetAddress address = addresses.nextElement();
                    if (address instanceof Inet4Address) {
                        return (Inet4Address) address;
                    }
                }
            }
        }
    } catch (SocketException e) {
        log.warn("Error while listing network interfaces", e);
    }

    return null;
}

From source file:org.elasticsearch.client.RestClientBuilderIntegTests.java

@BeforeClass
public static void startHttpServer() throws Exception {
    httpsServer = MockHttpServer.createHttps(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
    httpsServer.setHttpsConfigurator(new HttpsConfigurator(getSslContext()));
    httpsServer.createContext("/", new ResponseHandler());
    httpsServer.start();//from   www.j  ava 2 s .com
}

From source file:com.bytelightning.opensource.pokerface.ProxySpecificTest.java

/**
 * Configure both servers//from w ww. j  a v  a2  s .c  o  m
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {
    RemoteTarget = new SunHttpServer(new InetSocketAddress(InetAddress.getLoopbackAddress(), 8088), null);
    RemoteTarget.start(new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            OnRemoteTargetRequest(exchange);
        }
    });
    proxy = new PokerFace();
    XMLConfiguration conf = new XMLConfiguration();
    conf.load(ProxySpecificTest.class.getResource("/ProxySpecificTestConfig.xml"));
    proxy.config(conf);
    boolean started = proxy.start();
    Assert.assertTrue("Successful proxy start", started);

}

From source file:org.sonar.ce.cluster.HazelcastClientWrapperImplTest.java

@BeforeClass
public static void setupHazelcastClusterAndHazelcastClient() {
    int port = NetworkUtils.getNextAvailablePort(InetAddress.getLoopbackAddress());
    hzCluster = HazelcastTestHelper.createHazelcastCluster("cluster_with_client", port);

    Settings settings = createClusterSettings("cluster_with_client", "localhost:" + port);
    hzClient = new HazelcastClientWrapperImpl(settings);
}

From source file:org.apache.cassandra.utils.JMXServerUtils.java

/**
 * Creates a server programmatically. This allows us to set parameters which normally are
 * inaccessable./*from w  w w .  j a  v a2 s .co  m*/
 */
public static JMXConnectorServer createJMXServer(int port, boolean local) throws IOException {
    Map<String, Object> env = new HashMap<>();

    String urlTemplate = "service:jmx:rmi://%1$s/jndi/rmi://%1$s:%2$d/jmxrmi";
    InetAddress serverAddress = null;
    if (local) {
        serverAddress = InetAddress.getLoopbackAddress();
        System.setProperty("java.rmi.server.hostname", serverAddress.getHostAddress());
    }

    // Configure the RMI client & server socket factories, including SSL config.
    env.putAll(configureJmxSocketFactories(serverAddress, local));

    // Configure authn, using a JMXAuthenticator which either wraps a set log LoginModules configured
    // via a JAAS configuration entry, or one which delegates to the standard file based authenticator.
    // Authn is disabled if com.sun.management.jmxremote.authenticate=false
    env.putAll(configureJmxAuthentication());

    // Configure authz - if a custom proxy class is specified an instance will be returned.
    // If not, but a location for the standard access file is set in system properties, the
    // return value is null, and an entry is added to the env map detailing that location
    // If neither method is specified, no access control is applied
    MBeanServerForwarder authzProxy = configureJmxAuthorization(env);

    // Make sure we use our custom exporter so a full GC doesn't get scheduled every
    // sun.rmi.dgc.server.gcInterval millis (default is 3600000ms/1 hour)
    env.put(RMIExporter.EXPORTER_ATTRIBUTE, new Exporter());

    String url = String.format(urlTemplate,
            (serverAddress != null ? serverAddress.getHostAddress() : "0.0.0.0"), port);

    int rmiPort = Integer.getInteger("com.sun.management.jmxremote.rmi.port", 0);
    JMXConnectorServer jmxServer = JMXConnectorServerFactory.newJMXConnectorServer(
            new JMXServiceURL("rmi", null, rmiPort), env, ManagementFactory.getPlatformMBeanServer());

    // If a custom authz proxy was created, attach it to the server now.
    if (authzProxy != null)
        jmxServer.setMBeanServerForwarder(authzProxy);

    jmxServer.start();

    // use a custom Registry to avoid having to interact with it internally using the remoting interface
    configureRMIRegistry(port, env);

    logger.info("Configured JMX server at: {}", url);
    return jmxServer;
}

From source file:org.sonar.server.app.EmbeddedTomcatTest.java

@Test
public void start() throws Exception {
    Props props = new Props(new Properties());

    // prepare file system
    File home = temp.newFolder();
    File data = temp.newFolder();
    File webDir = new File(home, "web");
    FileUtils.write(new File(home, "web/WEB-INF/web.xml"), "<web-app/>");
    props.set("sonar.path.home", home.getAbsolutePath());
    props.set("sonar.path.data", data.getAbsolutePath());
    props.set("sonar.path.web", webDir.getAbsolutePath());
    props.set("sonar.path.logs", temp.newFolder().getAbsolutePath());

    // start server on a random port
    InetAddress address = InetAddress.getLoopbackAddress();
    int httpPort = NetworkUtils.getNextAvailablePort(address);
    props.set("sonar.web.host", address.getHostAddress());
    props.set("sonar.web.port", String.valueOf(httpPort));
    EmbeddedTomcat tomcat = new EmbeddedTomcat(props);
    assertThat(tomcat.getStatus()).isEqualTo(EmbeddedTomcat.Status.DOWN);
    tomcat.start();/*from ww  w  . j a v  a 2s .  c  o m*/
    assertThat(tomcat.getStatus()).isEqualTo(EmbeddedTomcat.Status.UP);

    // check that http connector accepts requests
    URL url = new URL("http://" + address.getHostAddress() + ":" + httpPort);
    url.openConnection().connect();

    // stop server
    tomcat.terminate();
    // tomcat.isUp() must not be called. It is used to wait for server startup, not shutdown.
    try {
        url.openConnection().connect();
        fail();
    } catch (ConnectException e) {
        // expected
    }
}

From source file:org.elasticsearch.client.RestClientIntegTests.java

@BeforeClass
public static void startHttpServer() throws Exception {
    httpServer = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
    httpServer.start();//from  w w  w.jav  a 2s.  c  om
    //returns a different status code depending on the path
    for (int statusCode : getAllStatusCodes()) {
        createStatusCodeContext(httpServer, statusCode);
    }
    int numHeaders = randomIntBetween(0, 5);
    defaultHeaders = generateHeaders("Header-default", "Header-array", numHeaders);
    restClient = RestClient
            .builder(new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort()))
            .setDefaultHeaders(defaultHeaders).build();
}

From source file:io.jmnarloch.spring.cloud.zuul.store.CassandraZuulRouteStoreTest.java

@Before
public void setUp() throws Exception {

    final Cluster cluster = Cluster.builder().addContactPoints(InetAddress.getLoopbackAddress()).withPort(9142)
            .build();//from ww w .  ja  v  a2 s  .c o  m
    cassandraTemplate = new CassandraTemplate(cluster.connect("zuul"));

    instance = new CassandraZuulRouteStore(cassandraTemplate);
}