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:org.n52.iceland.statistics.api.utils.KibanaExporter.java

public static void main(String args[]) throws Exception {
    if (args.length != 2) {
        System.out.printf("Usage: java KibanaExporter.jar %s %s\n", "localhost:9300", "my-cluster-name");
        System.exit(0);/*from w  ww . j  a va2 s.c o m*/
    }
    if (!args[0].contains(":")) {
        throw new IllegalArgumentException(
                String.format("%s not a valid format. Expected <hostname>:<port>.", args[0]));
    }

    // set ES address
    String split[] = args[0].split(":");
    InetSocketTransportAddress address = new InetSocketTransportAddress(InetAddress.getByName(split[0]),
            Integer.parseInt(split[1], 10));

    // set cluster name
    Builder tcSettings = Settings.settingsBuilder();
    tcSettings.put("cluster.name", args[1]);
    System.out.println("Connection to " + args[1]);

    client = TransportClient.builder().settings(tcSettings).build();
    client.addTransportAddress(address);

    // search index pattern for needle
    searchIndexPattern();

    KibanaConfigHolderDto holder = new KibanaConfigHolderDto();
    System.out.println("Reading .kibana index");

    SearchResponse resp = client.prepareSearch(".kibana").setSize(1000).get();
    Arrays.asList(resp.getHits().getHits()).stream().map(KibanaExporter::parseSearchHit).forEach(holder::add);
    System.out.println("Reading finished");

    ObjectMapper mapper = new ObjectMapper();
    // we love pretty things
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    File f = new File("kibana_config.json");

    try (FileOutputStream out = new FileOutputStream(f, false)) {
        mapper.writeValue(out, holder);
    }

    System.out.println("File outputted to: " + f.getAbsolutePath());

    client.close();

}

From source file:fm.last.irccat.IRCCat.java

public static void main(String[] args) throws Exception {
    try {//  w w w . j  ava  2  s .  c om
        if (args.length == 0) {
            System.out.println("first param should be config file");
            System.exit(-1);
        }
        XMLConfiguration c = null;
        try {
            c = new XMLConfiguration(args[0]);
        } catch (ConfigurationException cex) {
            System.err.println("Configuration error, check config file");
            cex.printStackTrace();
            System.exit(1);
        }

        IRCCat bot = new IRCCat(c);

        // listen for stuff and send it to irc:
        ServerSocket serverSocket = null;
        InetAddress inet = null;
        try {
            if (bot.getCatIP() != null)
                inet = InetAddress.getByName(bot.getCatIP());
        } catch (UnknownHostException ex) {
            System.out.println("Could not resolve config cat.ip, fix your config");
            ex.printStackTrace();
            System.exit(2);
        }

        try {
            serverSocket = new ServerSocket(bot.getCatPort(), 0, inet);
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + bot.getCatPort());
            System.exit(1);
        }

        System.out.println("Listening on " + bot.getCatIP() + " : " + bot.getCatPort());

        while (true) {
            try {
                Socket clientSocket = serverSocket.accept();
                // System.out.println("Connection on catport from: "
                // + clientSocket.getInetAddress().toString());
                CatHandler handler = new CatHandler(clientSocket, bot);
                handler.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.logic.test.FTPSLogic.java

public static void main(String[] args) {
    String serverAdress = "62.2.176.167";
    String username = "RLSFTPRead";
    String password = "ftp4rls";
    int port = 990;
    FTPSClient ftpsClient = new FTPSClient("TLS", true);
    String remoteFile = "REM - Persons Extract.csv";
    File localFile = new File("Persons Extract.csv");

    try {//  w  w w. j  av  a2  s. c  o m
        TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        ftpsClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

        //ftpsClient.setTrustManager(trustManager[0]);
        //KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        //kmf.init(null, null);
        //KeyManager km = kmf.getKeyManagers()[0];

        //ftpsClient.setKeyManager(km);
        ftpsClient.setBufferSize(1024 * 1024);
        ftpsClient.setConnectTimeout(100000);
        ftpsClient.connect(InetAddress.getByName(serverAdress), port);
        ftpsClient.setSoTimeout(100000);

        if (ftpsClient.login(username, password)) {
            ftpsClient.execPBSZ(0);
            ftpsClient.execPROT("P");
            ftpsClient.changeWorkingDirectory("/");
            ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpsClient.enterLocalPassiveMode();

            //ftpsClient.retrieveFile(remoteFile, new FileOutputStream(localFile));
            for (FTPFile file : ftpsClient.listFiles()) {
                System.out.println("Nom " + file.getName());
            }

        }
    } catch (SocketException e) {
        ;
    } catch (UnknownHostException e) {
        ;
    } catch (IOException e) {
        ;
    } catch (Exception e) {
        ;
    } finally {
        try {
            ftpsClient.logout();
        } catch (Exception e2) {
        }

        try {
            ftpsClient.disconnect();
        } catch (Exception e2) {
        }
    }
}

From source file:com.ok2c.lightmtp.examples.LocalMailServerTransportExample.java

public static void main(final String[] args) throws Exception {
    File workingDir = new File(".");
    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).build();

    final MailServerTransport mta = new LocalMailServerTransport(workingDir, config);

    InetSocketAddress sockaddress = new InetSocketAddress("localhost", 2525);

    InetAddressRange iprange = new InetAddressRange(InetAddress.getByName("127.0.0.0"), 8);

    mta.start(new DefaultIdGenerator(), new MyRemoteAddressValidator(iprange), new MyEnvelopValidator(),
            new MyDeliveryHandler());
    mta.listen(sockaddress);/*from www .j a va 2s.c o m*/

    System.out.println("LMTP server listening on " + sockaddress);

    Runtime runtime = Runtime.getRuntime();
    runtime.addShutdownHook(new Thread() {

        @Override
        public void run() {
            try {
                mta.shutdown();
            } catch (IOException ex) {
                mta.forceShutdown();
            }
        }

    });
}

From source file:MulticastClient.java

 public static void main(String[] args) throws IOException {

   MulticastSocket socket = new MulticastSocket(4446);
   InetAddress address = InetAddress.getByName("230.0.0.1");
   socket.joinGroup(address);/*from   w w  w  .j  av a2  s .  c o m*/

   DatagramPacket packet;

   // get a few quotes
   for (int i = 0; i < 5; i++) {

      byte[] buf = new byte[256];
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);

      String received = new String(packet.getData());
      System.out.println("Quote of the Moment: " + received);
   }

   socket.leaveGroup(address);
   socket.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    InetAddress serverIPAddress = InetAddress.getByName("localhost");
    int port = 19000;
    InetSocketAddress serverAddress = new InetSocketAddress(serverIPAddress, port);
    Selector selector = Selector.open();
    SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(false);/*w w  w .  j  av  a2 s .  c o m*/
    channel.connect(serverAddress);
    int operations = SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE;
    channel.register(selector, operations);

    userInputReader = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        if (selector.select() > 0) {
            boolean doneStatus = processReadySet(selector.selectedKeys());
            if (doneStatus) {
                break;
            }
        }
    }
    channel.close();
}

From source file:UDPSend.java

public static void main(String args[]) {
    try {/*from   ww  w . j  a  va2s  . c o m*/
        // Check the number of arguments
        if (args.length < 3)
            throw new IllegalArgumentException("Wrong number of args");

        // Parse the arguments
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        // Figure out the message to send.
        // If the third argument is -f, then send the contents of the file
        // specified as the fourth argument. Otherwise, concatenate the
        // third and all remaining arguments and send that.
        byte[] message;
        if (args[2].equals("-f")) {
            File f = new File(args[3]);
            int len = (int) f.length(); // figure out how big the file is
            message = new byte[len]; // create a buffer big enough
            FileInputStream in = new FileInputStream(f);
            int bytes_read = 0, n;
            do { // loop until we've read it all
                n = in.read(message, bytes_read, len - bytes_read);
                bytes_read += n;
            } while ((bytes_read < len) && (n != -1));
        } else { // Otherwise, just combine all the remaining arguments.
            String msg = args[2];
            for (int i = 3; i < args.length; i++)
                msg += " " + args[i];
            // Convert the message to bytes using UTF-8 encoding
            message = msg.getBytes("UTF-8");
        }

        // Get the internet address of the specified host
        InetAddress address = InetAddress.getByName(host);

        // Initialize a datagram packet with data and address
        DatagramPacket packet = new DatagramPacket(message, message.length, address, port);

        // Create a datagram socket, send the packet through it, close it.
        DatagramSocket dsocket = new DatagramSocket();
        dsocket.send(packet);
        dsocket.close();
    } catch (Exception e) {
        System.err.println(e);
        System.err.println(usage);
    }
}

From source file:com.ls.zencat.ZenCat.java

public static void main(String[] args) throws Exception {
    try {/*w  w  w . j  a  v a 2s.c  o  m*/
        if (args.length == 0) {
            System.out.println("first param should be config file");
            System.exit(-1);
        }
        XMLConfiguration c = null;
        try {
            c = new XMLConfiguration(args[0]);
        } catch (ConfigurationException cex) {
            System.err.println("Configuration error, check config file");
            cex.printStackTrace();
            System.exit(1);
        }

        ZenCat bot = new ZenCat(c);

        // listen for stuff and send it to irc:
        ServerSocket serverSocket = null;
        InetAddress inet = null;
        try {
            if (bot.getCatIP() != null)
                inet = InetAddress.getByName(bot.getCatIP());
        } catch (UnknownHostException ex) {
            System.out.println("Could not resolve config cat.ip, fix your config");
            ex.printStackTrace();
            System.exit(2);
        }

        try {
            serverSocket = new ServerSocket(bot.getCatPort(), 0, inet);
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + bot.getCatPort());
            System.exit(1);
        }

        System.out.println("Listening on " + bot.getCatIP() + " : " + bot.getCatPort());

        while (true) {
            try {
                Socket clientSocket = serverSocket.accept();
                // System.out.println("Connection on catport from: "
                // + clientSocket.getInetAddress().toString());
                CatHandler handler = new CatHandler(clientSocket, bot);
                handler.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:SDRecord.java

public static void main(String[] args) {

    boolean recordToInf = false;
    long recordTo = 0, txsize = 0, wr = 0, max = 0;
    int sourcePort = 0, destPort = 0;
    String val;
    OutputStream writer = null;/*from  w ww.  j ava  2  s  . co  m*/
    InetAddress rhost = null, lhost = null;
    DatagramSocket socket = null;

    //Default values
    int buffSize = 1500;
    try {
        lhost = InetAddress.getByName("0.0.0.0");
    } catch (UnknownHostException e1) {
        System.err.println("ERROR!: Host not reconized");
        System.exit(3);
    }
    recordToInf = true;
    sourcePort = 7355;

    Options options = new Options();

    options.addOption("m", true, "Minutes to record, default is no limit");
    options.addOption("l", true, "Bind to a specific local address, default is 0.0.0.0");
    options.addOption("p", true, "Local port to use, default is 7355");
    options.addOption("r", true, "Remote address where to send data");
    options.addOption("d", true, "Remote port, to use with -r option");
    options.addOption("f", true, "Output file where to save the recording");
    options.addOption("s", true, "Stop recording when reaching specified MBs");
    options.addOption("h", false, "Help");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e1) {
        System.err.println("ERROR!: Error while parsing the command line");
        System.exit(1);
    }

    if (cmd.hasOption("m")) {
        val = cmd.getOptionValue("m");
        try {
            if (Long.parseLong(val) < 0) {
                System.err.println("ERROR!: -m argument value cannot be negative");
                System.exit(3);
            }
            recordTo = System.currentTimeMillis() + (Long.parseLong(val) * 60000);
            recordToInf = false;
        } catch (NumberFormatException e) {
            System.err.println("ERROR!: -m argument not an integer");
            System.exit(3);
        }
    }

    if (cmd.hasOption("l")) {
        val = cmd.getOptionValue("l");
        try {
            lhost = InetAddress.getByName(val);
        } catch (UnknownHostException e) {
            System.err.println("ERROR!: Host not reconized");
            System.exit(3);
        }
    }

    if (cmd.hasOption("p")) {
        val = cmd.getOptionValue("p");
        try {
            sourcePort = Integer.parseInt(val);
        } catch (NumberFormatException e) {
            System.err.println("ERROR!: -p argument not an integer");
            System.exit(3);
        }
    }

    if (cmd.hasOption("r")) {
        val = cmd.getOptionValue("r");
        try {
            rhost = InetAddress.getByName(val);
        } catch (UnknownHostException e) {
            System.err.println("ERROR!: Host not reconized");
            System.exit(3);
        }
    }

    if (cmd.hasOption("d")) {
        val = cmd.getOptionValue("d");
        try {
            destPort = Integer.parseInt(val);
        } catch (NumberFormatException e) {
            System.err.println("-ERROR!: -d argument not an integer");
            System.exit(3);
        }
    }

    if (cmd.hasOption("f")) {
        val = cmd.getOptionValue("f");
        try {
            writer = new FileOutputStream(val);
        } catch (FileNotFoundException e) {
            System.err.println("ERROR!: File not found");
            System.exit(3);
        }
    }

    if (cmd.hasOption("s")) {
        val = cmd.getOptionValue("s");

        try {
            max = (long) (Double.parseDouble(val) * 1000000);
        } catch (NumberFormatException e) {
            System.err.println("ERROR!: -s argument not valid");
            System.exit(3);
        }

        if (Double.parseDouble(val) < 0) {
            System.err.println("ERROR!: -s argument value cannot be negative");
            System.exit(3);
        }

    }

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SDRecord", options);
        System.exit(0);
    }

    try {
        socket = new DatagramSocket(sourcePort, lhost);
        //socket options
        socket.setReuseAddress(true);
    } catch (SocketException e) {
        e.printStackTrace();
        System.exit(3);
    }

    byte[] buffer = new byte[buffSize];
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

    System.err.println("Listening " + lhost.toString() + " on port " + sourcePort);

    while (recordToInf == true || System.currentTimeMillis() <= recordTo) {
        //Stop recording when reaching max bytes
        if (max != 0 && txsize >= max)
            break;

        packet.setData(buffer);
        try {
            socket.receive(packet);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(4);
        }

        //Ignoring packets with no data
        if (basicFilter(packet) == null)
            continue;

        if (writer == null && rhost == null)
            wr = recordToStdout(packet);
        if (writer != null)
            wr = recordToFile(packet, writer);
        if (rhost != null)
            wr = recordToSocket(packet, socket, rhost, destPort);

        txsize += wr;
        System.err
                .print("\r" + formatSize(txsize) + " transferred" + "\033[K" + "\t Press Ctrl+c to terminate");
    }
    //closing socket and exit
    System.err.print("\r" + formatSize(txsize) + " transferred" + "\033[K");
    socket.close();
    System.out.println();
    System.exit(0);
}

From source file:org.unidle.test.LocationGenerator.java

public static void main(final String... args) throws Exception {

    final ConcurrentMap<String, Boolean> locations = locations();

    scheduledExecutorService.scheduleAtFixedRate(new ShutdownWatcher(locations), 15L, 15L, SECONDS);

    final DatabaseReader databaseReader = databaseReader();

    for (int i = 0; i < 256; i++) {
        for (int j = 0; j < 256; j++) {
            for (int k = 0; k < 256; k++) {

                final InetAddress address = InetAddress.getByName(format("%d.%d.%d.0", i, j, k));

                if (executorService.isShutdown() || executorService.isTerminated()) {
                    return;
                }/*w  ww  . j  a v a 2s . co  m*/

                executorService.execute(new AddressChecker(databaseReader, address, locations));
            }
        }
    }
}