Example usage for java.net InetAddress getByName

List of usage examples for java.net InetAddress getByName

Introduction

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

Prototype

public static InetAddress getByName(String host) throws UnknownHostException 

Source Link

Document

Determines the IP address of a host, given the host's name.

Usage

From source file:edu.vt.middleware.gator.server.SocketServerTest.java

/**
 * Tests connecting to the socket server and sending a logging event that
 * should be written to configured appenders.
 *
 * @throws  Exception  On errors.//from  ww w  .ja v  a  2 s . co m
 */
@Test
public void testConnectAndLog() throws Exception {
    final Socket sock = new Socket();
    try {
        final SocketAddress addr = new InetSocketAddress(InetAddress.getByName(server.getBindAddress()),
                server.getPort());
        sock.connect(addr, SOCKET_CONNECT_TIMEOUT);

        // Allow the socket server time to build the hierarchy
        // before sending a test logging event
        Thread.sleep(2000);

        Assert.assertEquals(1, server.getLoggingEventHandlers().size());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending test logging event.");
        }

        final ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
        oos.writeObject(new MockEvent(TEST_MESSAGE));
        oos.flush();
    } finally {
        if (sock.isConnected()) {
            sock.close();
        }
    }

    // Pause to allow time for logging events to be written
    Thread.sleep(2000);

    // Client socket close should trigger cleanup of server handler mapping
    Assert.assertEquals(0, server.getLoggingEventHandlers().size());

    // Ensure test message was written to file
    Assert.assertTrue(readTextFile(LOG_FILE).contains(TEST_MESSAGE));
}

From source file:es.upct.girtel.net2plan.plugins.activepce.pce.PCEMainServer.java

@Override
public void executeFromCommandLine(String[] args) throws ParseException {
    System.out.println("PCE MAIN SERVER");
    System.out.println("==============================");

    Scanner scanner = new Scanner(System.in);

    System.out.println("Starting PCEP & BGP-LS servers...");

    PCEPServer serverPCEP;/*from w w w  .ja v  a2 s  . co m*/
    BGPServer serverBGP;

    try {
        serverPCEP = new PCEPServer();
        serverBGP = new BGPServer();
    } catch (Net2PlanException e) {
        throw (e);
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

    /* Create and start PCE Server */
    serverPCEP.acceptConnections();

    /* Create and start BGP server */
    serverBGP.acceptConnections();

    System.out.println("PCE successfully started");

    while (true) {
        String option;

        System.out.println("============================");
        System.out.println("|    MULTILAYER AS-PCE     |");
        System.out.println("============================");
        System.out.println("| Options:                 |");
        System.out.println("| 1. View current sessions |");
        System.out.println("| 2. Print TEDB and LSPDB  |");
        System.out.println("| 3. Exit                  |");
        System.out.println("============================");
        System.out.println("");
        System.out.print("Choose an option (1-3): ");

        option = scanner.nextLine();

        Set<InetAddress> activeSessions = PCEMasterController.getInstance().getActiveSessions();
        switch (option) {
        case "1":
            if (activeSessions.isEmpty())
                System.out.println("No active session");
            else
                System.out.println("Active sessions: " + activeSessions);
            break;

        case "2":
            switch (activeSessions.size()) {
            case 0:
                System.out.println("No active session");
                break;

            case 1:
                System.out.println("Network state: " + PCEMasterController.getInstance()
                        .getPCEEntity(activeSessions.iterator().next()).getNetworkState());
                break;

            default:
                System.out.println(">> Active sessions: " + activeSessions);
                System.out.print(">> Choose a session: ");
                try {
                    String session = scanner.nextLine();
                    IPCEEntity pceEntity = PCEMasterController.getInstance()
                            .getPCEEntity(InetAddress.getByName(session));
                    System.out.println("Network state: " + pceEntity.getNetworkState());
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                break;
            }
            break;

        case "3":
            System.exit(0);

        default:
            System.out.println("Wrong option");
        }
    }
}

From source file:com.netflix.spinnaker.halyard.deploy.provider.v1.kubernetes.KubernetesOperationFactory.java

private KubernetesLoadBalancerDescription baseLoadBalancerDescription(String accountName,
        SpinnakerService service) {/* w w  w .  j a  v a 2 s . c o m*/
    String address = service.getAddress();
    int port = service.getPort();
    KubernetesLoadBalancerDescription description = new KubernetesLoadBalancerDescription();

    String namespace = KubernetesProviderInterface.getNamespaceFromAddress(address);
    String name = KubernetesProviderInterface.getServiceFromAddress(address);
    Names parsedName = Names.parseName(name);
    description.setApp(parsedName.getApp());
    description.setStack(parsedName.getStack());
    description.setDetail(parsedName.getDetail());

    description.setName(name);
    description.setNamespace(namespace);
    description.setAccount(accountName);

    KubernetesNamedServicePort servicePort = new KubernetesNamedServicePort();
    servicePort.setPort(port);
    servicePort.setTargetPort(port);
    servicePort.setName("http");
    servicePort.setProtocol("TCP");

    if (service instanceof SpinnakerPublicService) {
        SpinnakerPublicService publicService = (SpinnakerPublicService) service;
        String publicAddress = publicService.getPublicAddress();
        InetAddress addr;
        try {
            addr = InetAddress.getByName(publicAddress);
        } catch (UnknownHostException e) {
            throw new HalException(new ProblemBuilder(Problem.Severity.FATAL,
                    "Failed to parse supplied public address: " + e.getMessage()).build());
        }

        if (!(addr.isAnyLocalAddress() || addr.isLoopbackAddress())) {
            description.setLoadBalancerIp(publicService.getPublicAddress());
            description.setServiceType("LoadBalancer");
        }
    }

    List<KubernetesNamedServicePort> servicePorts = new ArrayList<>();
    servicePorts.add(servicePort);
    description.setPorts(servicePorts);

    return description;
}

From source file:com.floragunn.searchguard.config.EvaluatorTest.java

@Test
public void testEval3() throws IOException, MalformedConfigurationException {
    final TokenEvaluator te = new TokenEvaluator(new BytesArray(loadFile("ac_rules_4.json")));

    Evaluator eval = te.getEvaluator(Lists.<String>newArrayList("public"), Lists.<String>newArrayList(),
            Lists.<String>newArrayList(), InetAddress.getLocalHost(), new User("test"));
    Assert.assertTrue(eval.getBypassAll());
    Assert.assertFalse(eval.getExecuteAll());
    Assert.assertEquals(FilterAction.BYPASS, eval.evaluateFilter("XX", "XX"));

    eval = te.getEvaluator(Lists.<String>newArrayList("eight"), Lists.<String>newArrayList(),
            Lists.<String>newArrayList(), InetAddress.getByName("8.8.8.8"), new User("test"));
    Assert.assertTrue(eval.getBypassAll());
    Assert.assertFalse(eval.getExecuteAll());
    Assert.assertEquals(FilterAction.BYPASS, eval.evaluateFilter("XX", "XX"));

    eval = te.getEvaluator(Lists.<String>newArrayList(), Lists.<String>newArrayList("internal"),
            Lists.<String>newArrayList(), InetAddress.getByName("127.0.0.1"), new User("test"));
    Assert.assertTrue(eval.getBypassAll());
    Assert.assertFalse(eval.getExecuteAll());
    Assert.assertEquals(FilterAction.BYPASS, eval.evaluateFilter("XX", "XX"));

    eval = te.getEvaluator(Lists.<String>newArrayList(), Lists.<String>newArrayList("internal"),
            Lists.<String>newArrayList("xxx"), InetAddress.getByName("8.8.8.8"), new User("test"));
    Assert.assertTrue(eval.getBypassAll());
    Assert.assertFalse(eval.getExecuteAll());
    Assert.assertEquals(FilterAction.BYPASS, eval.evaluateFilter("check", "1"));
    Assert.assertEquals(FilterAction.BYPASS, eval.evaluateFilter("XX", "XX"));
    Assert.assertEquals(FilterAction.BYPASS, eval.evaluateFilter("read", "only"));

    final User user = new User("jacksonm");
    user.addRole("ceo");

    eval = te.getEvaluator(Lists.<String>newArrayList(), Lists.<String>newArrayList("internal"),
            Lists.<String>newArrayList("xxx"), InetAddress.getByName("8.8.8.8"), user);
    Assert.assertTrue(eval.getBypassAll());
    Assert.assertFalse(eval.getExecuteAll());
    Assert.assertEquals(FilterAction.BYPASS, eval.evaluateFilter("check", "1"));
    Assert.assertEquals(FilterAction.BYPASS, eval.evaluateFilter("XX", "XX"));
    Assert.assertEquals(FilterAction.BYPASS, eval.evaluateFilter("read", "only"));
}

From source file:com.basho.riak.pbc.RiakClient.java

public RiakClient(String host, int port, int bufferSizeKb) throws IOException {
    this.pool = new RiakConnectionPool(0, RiakConnectionPool.LIMITLESS, InetAddress.getByName(host), port, 1000,
            bufferSizeKb, 1000, 0);//from  w w  w .  j  a  v  a 2  s . c  o m
    this.pool.start();
}

From source file:com.netflix.metacat.main.configs.ElasticSearchConfig.java

/**
 * The ElasticSearch client./*from ww  w . j  a va2s  .  c o  m*/
 *
 * @param config System config
 * @return Configured client or error
 */
@Bean
@ConditionalOnMissingBean(Client.class)
public Client elasticSearchClient(final Config config) {
    final String clusterName = config.getElasticSearchClusterName();
    if (StringUtils.isBlank(clusterName)) {
        throw new IllegalStateException("No cluster name set. Unable to continue");
    }
    final Settings settings = Settings.builder().put("cluster.name", clusterName)
            .put("client.transport.sniff", true) //to dynamically add new hosts and remove old ones
            .put("transport.tcp.connect_timeout", "60s").build();
    final TransportClient client = new PreBuiltTransportClient(settings);
    // Add the transport address if exists
    final String clusterNodesStr = config.getElasticSearchClusterNodes();
    if (StringUtils.isNotBlank(clusterNodesStr)) {
        final int port = config.getElasticSearchClusterPort();
        final Iterable<String> clusterNodes = Splitter.on(',').split(clusterNodesStr);
        clusterNodes.forEach(clusterNode -> {
            try {
                client.addTransportAddress(
                        new InetSocketTransportAddress(InetAddress.getByName(clusterNode), port));
            } catch (UnknownHostException exception) {
                log.error("Skipping unknown host {}", clusterNode);
            }
        });
    }

    if (client.transportAddresses().isEmpty()) {
        throw new IllegalStateException("No Elasticsearch cluster nodes added. Unable to create client.");
    }
    return client;
}

From source file:osh.busdriver.MieleGatewayBusDriver.java

/**
 * CONSTRUCTOR//from   w ww .  j  a  va 2 s .  co m
 * @param controllerbox
 * @param deviceID
 * @param driverConfig
 * @throws UnknownHostException 
 */
public MieleGatewayBusDriver(IOSH controllerbox, UUID deviceID, OSHParameterCollection driverConfig)
        throws UnknownHostException {
    super(controllerbox, deviceID, driverConfig);

    this.mieleGatewayHost = driverConfig.getParameter("mielegatewayhost");
    this.mieleGatewayAddr = InetAddress.getByName(mieleGatewayHost);

    this.mieleGatewayUsername = driverConfig.getParameter("mielegatewayusername");
    this.mieleGatewayPassword = driverConfig.getParameter("mielegatewaypassword");

    deviceProperties = new HashMap<UUID, Map<String, String>>();
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java

private static Set<UpnpIgdDevice> findIpv4Devices() throws IOException, InterruptedException {
    InetSocketAddress multicastSocketAddress;
    try {/*from  w  ww .  j ava  2  s  .  c o m*/
        multicastSocketAddress = new InetSocketAddress(InetAddress.getByName("239.255.255.250"), 1900); // NOPMD
    } catch (UnknownHostException uhe) {
        throw new IllegalStateException(uhe);
    }

    Set<InetAddress> localIpv4Addresses = NetworkUtils.getAllLocalIpv4Addresses();
    return scanForDevices(multicastSocketAddress, localIpv4Addresses, IPV4_SEARCH_QUERY);
}

From source file:com.edmunds.etm.agent.impl.TcpHealthCheck.java

private InetAddress getHostAddress() {
    if (hostAddress == null) {
        try {/*from  w  ww . ja v a  2  s  .  com*/
            if (StringUtils.isEmpty(hostName)) {
                hostAddress = InetAddress.getLocalHost();
            } else {
                hostAddress = InetAddress.getByName(hostName);
            }
        } catch (UnknownHostException e) {
            String message = String.format("Could not get IP address for host %s", hostName);
            logger.error(message, e);
            throw new RuntimeException(message, e);
        }
    }
    return hostAddress;
}

From source file:be.tutul.naheulcraft.launcher.auth.Auth.java

public void logIn() {
    new Thread() {
        private Socket ss;
        private BufferedReader in;
        private PrintWriter out;

        public void run() {
            try {
                InetAddress adresse = InetAddress.getByName("naheulcraft.be"); // Rcupre l'adresse IP
                String IP = adresse.toString().split("/")[1];
                Auth.this.logger.info("Connexion  " + IP + ":" + Variables.PORT);
                this.ss = new Socket(IP, Variables.PORT);

                this.in = new BufferedReader(new InputStreamReader(this.ss.getInputStream()));
                this.out = new PrintWriter(this.ss.getOutputStream());

                // On signale au serveur qu'on demande une authentification
                this.out.println("<start>");
                this.out.flush();
                String ok = this.in.readLine();
                if (!ok.contains("<ok>")) {
                    Auth.this.launcher.getPanel().getLogInPopup().setText("Rponse innatendu du serveur");
                    Auth.this.launcher.getPanel().getLogInPopup().setCanLogIn(true);
                    Auth.this.launcher.getPanel().showLoginPrompt();
                    return;
                }//from   w w  w .j  a v a  2 s. co  m

                Auth.this.logger.info("Connexion au service de login tablie");

                String key = ok.split("<ok>")[1]; // On rcure la cl
                String msg = Auth.this.launcher.getUser().getPseudo() + ":"
                        + Auth.this.launcher.getUser().getPass() + ":" + Variables.version + "<end>";
                System.err.println("A : " + msg);//TODO
                msg = crypt(msg, key); // On crypt en base 64

                // On lui envoit la requte
                Auth.this.logger.info("Vrification du login en cours...");
                System.err.println("B : " + msg);//TODO
                this.out.println(msg);
                this.out.flush();

                String login = this.in.readLine();
                login = decrypt(login, key); // On dcrypt en string
                System.err.println("C : " + login);//TODO

                // On ferme le socket
                this.in.close();
                this.out.close();
                this.ss.close();

                String ret;
                if (login != null) {
                    if (login.contains("pass")) {
                        ret = "Mauvais mot de passe";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.warning(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("user")) {
                        ret = "Mauvais pseudo";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.warning(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("statut")) {
                        ret = "Compte n'ont autoris";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.warning(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("encodage")) {
                        ret = "Problme dans la demande de login";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.error(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("serveur")) {
                        ret = "Erreur du service de login";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.error(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("<ok>")) {
                        String id = login.split("<end>")[0].split("<ok>")[1];
                        Auth.this.launcher.getUser().setID(id);
                        Auth.this.launcher.getUser().setLogin(true);
                        Auth.this.logger.info("Login vrifier avec succs");
                        Auth.this.logger.info("ID de connexion : " + id);
                        Auth.this.lastLogin.writeUsername();
                        Auth.this.launcher.getPanel().showPanel();
                        return;
                    } else {
                        Auth.this.logger.error(login);
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.launcher.getPanel().getLogInPopup().setText("Erreur inconnue");
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    }
                }
                Auth.this.logger.error("Pas de rponse du serveur");
                Auth.this.launcher.getUser().setLogin(false);
                Auth.this.launcher.getPanel().getLogInPopup().setText("Pas de rponse");
                Auth.this.launcher.getPanel().showLoginPrompt();
            } catch (Exception e) {
                Auth.this.logger.fatal("Impossible de communiquer avec le service de login", e);
                Auth.this.launcher.getUser().setLogin(false);
                Auth.this.launcher.getPanel().getLogInPopup().setText("Problme de communication");
                Auth.this.launcher.getPanel().showLoginPrompt();
                try { // On tente quand mme de couper le socket
                    this.in.close();
                    this.out.close();
                    this.ss.close();
                } catch (Exception ingnored) {
                }
            }
        }
    }.start();
}