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:examples.finger.java

public static final void main(String[] args) {
    boolean longOutput = false;
    int arg = 0, index;
    String handle, host;/*from w ww . ja  va  2  s. co  m*/
    FingerClient finger;
    InetAddress address = null;

    // Get flags.  If an invalid flag is present, exit with usage message.
    while (arg < args.length && args[arg].startsWith("-")) {
        if (args[arg].equals("-l"))
            longOutput = true;
        else {
            System.err.println("usage: finger [-l] [[[handle][@<server>]] ...]");
            System.exit(1);
        }
        ++arg;
    }

    finger = new FingerClient();
    // We want to timeout if a response takes longer than 60 seconds
    finger.setDefaultTimeout(60000);

    if (arg >= args.length) {
        // Finger local host

        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            System.err.println("Error unknown host: " + e.getMessage());
            System.exit(1);
        }

        try {
            finger.connect(address);
            System.out.print(finger.query(longOutput));
            finger.disconnect();
        } catch (IOException e) {
            System.err.println("Error I/O exception: " + e.getMessage());
            System.exit(1);
        }

        return;
    }

    // Finger each argument
    while (arg < args.length) {

        index = args[arg].lastIndexOf("@");

        if (index == -1) {
            handle = args[arg];
            try {
                address = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                System.err.println("Error unknown host: " + e.getMessage());
                System.exit(1);
            }
        } else {
            handle = args[arg].substring(0, index);
            host = args[arg].substring(index + 1);

            try {
                address = InetAddress.getByName(host);
            } catch (UnknownHostException e) {
                System.err.println("Error unknown host: " + e.getMessage());
                System.exit(1);
            }
        }

        System.out.println("[" + address.getHostName() + "]");

        try {
            finger.connect(address);
            System.out.print(finger.query(longOutput, handle));
            finger.disconnect();
        } catch (IOException e) {
            System.err.println("Error I/O exception: " + e.getMessage());
            System.exit(1);
        }

        ++arg;
        if (arg != args.length)
            System.out.print("\n");
    }
}

From source file:examples.unix.finger.java

public static void main(String[] args) {
    boolean longOutput = false;
    int arg = 0, index;
    String handle, host;//from w w  w  . j av  a  2  s.  com
    FingerClient finger;
    InetAddress address = null;

    // Get flags.  If an invalid flag is present, exit with usage message.
    while (arg < args.length && args[arg].startsWith("-")) {
        if (args[arg].equals("-l")) {
            longOutput = true;
        } else {
            System.err.println("usage: finger [-l] [[[handle][@<server>]] ...]");
            System.exit(1);
        }
        ++arg;
    }

    finger = new FingerClient();
    // We want to timeout if a response takes longer than 60 seconds
    finger.setDefaultTimeout(60000);

    if (arg >= args.length) {
        // Finger local host

        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            System.err.println("Error unknown host: " + e.getMessage());
            System.exit(1);
        }

        try {
            finger.connect(address);
            System.out.print(finger.query(longOutput));
            finger.disconnect();
        } catch (IOException e) {
            System.err.println("Error I/O exception: " + e.getMessage());
            System.exit(1);
        }

        return;
    }

    // Finger each argument
    while (arg < args.length) {

        index = args[arg].lastIndexOf("@");

        if (index == -1) {
            handle = args[arg];
            try {
                address = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                System.err.println("Error unknown host: " + e.getMessage());
                System.exit(1);
            }
        } else {
            handle = args[arg].substring(0, index);
            host = args[arg].substring(index + 1);

            try {
                address = InetAddress.getByName(host);
                System.out.println("[" + address.getHostName() + "]");
            } catch (UnknownHostException e) {
                System.err.println("Error unknown host: " + e.getMessage());
                System.exit(1);
            }
        }

        try {
            finger.connect(address);
            System.out.print(finger.query(longOutput, handle));
            finger.disconnect();
        } catch (IOException e) {
            System.err.println("Error I/O exception: " + e.getMessage());
            System.exit(1);
        }

        ++arg;
        if (arg != args.length) {
            System.out.print("\n");
        }
    }
}

From source file:cnxchecker.Client.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("H", "host", true, "Remote IP address");
    options.addOption("p", "port", true, "Remote TCP port");
    options.addOption("s", "size", true, "Packet size in bytes (1 KiB)");
    options.addOption("f", "freq", true, "Packets per seconds  (1 Hz)");
    options.addOption("w", "workers", true, "Number of Workers (1)");
    options.addOption("d", "duration", true, "Duration of the test in seconds (60 s)");
    options.addOption("h", "help", false, "Print help");
    CommandLineParser parser = new GnuParser();
    try {//from  w ww . ja  v a 2s .  c om
        CommandLine cmd = parser.parse(options, args);

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

        // host
        InetAddress ia = null;
        if (cmd.hasOption("H")) {
            String host = cmd.getOptionValue("H");

            try {
                ia = InetAddress.getByName(host);
            } catch (UnknownHostException e) {
                printAndExit("Unknown host: " + host);
            }
        } else {
            printAndExit("Host option is mandatory");
        }

        // port
        int port = 0;
        if (cmd.hasOption("p")) {
            try {
                port = Integer.parseInt(cmd.getOptionValue("p"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid port number " + cmd.getOptionValue("p"));
            }

            if (port < 0 || port > 65535) {
                printAndExit("Invalid port number " + port);
            }
        }

        // size
        int size = 1024;
        if (cmd.hasOption("s")) {
            try {
                size = Integer.parseInt(cmd.getOptionValue("s"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid packet size " + cmd.getOptionValue("s"));
            }

            if (size < 0) {
                printAndExit("Invalid packet size: " + port);
            }
        }

        // freq
        double freq = 1;
        if (cmd.hasOption("f")) {
            try {
                freq = Double.parseDouble(cmd.getOptionValue("f"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid frequency: " + cmd.getOptionValue("f"));
            }

            if (freq <= 0) {
                printAndExit("Invalid frequency: " + freq);
            }
        }

        // workers
        int workers = 1;
        if (cmd.hasOption("w")) {
            try {
                workers = Integer.parseInt(cmd.getOptionValue("w"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid number of workers: " + cmd.getOptionValue("w"));
            }

            if (workers < 0) {
                printAndExit("Invalid number of workers: " + workers);
            }
        }

        // duration
        int duration = 60000;
        if (cmd.hasOption("d")) {
            try {
                duration = Integer.parseInt(cmd.getOptionValue("d")) * 1000;
            } catch (NumberFormatException e) {
                printAndExit("Invalid duration: " + cmd.getOptionValue("d"));
            }

            if (duration < 0) {
                printAndExit("Invalid duration: " + duration);
            }
        }

        Client client = new Client(ia, port, size, freq, workers, duration);
        client.doit();
    } catch (ParseException e) {
        printAndExit("Failed to parse options: " + e.getMessage());
    }

    System.exit(0);
}

From source file:com.knowbout.epg.EPG.java

public static void main(String[] args) {
    String configFile = "/etc/flip.tv/epg.xml";
    boolean sitemaponly = false;
    if (args.length > 0) {
        if (args.length == 2 && args[0].equals("-config")) {
            configFile = args[1];/*from  w w  w  .jav  a 2  s.  c om*/
        } else if (args.length == 1 && args[0].equals("-sitemaponly")) {
            sitemaponly = true;
        } else {
            System.err.println("Usage: java " + EPG.class.getName() + " [-config <xmlfile>]");
            System.exit(1);
        }
    }

    try {
        XMLConfiguration config = new XMLConfiguration(configFile);

        HashMap<String, String> hibernateProperties = new HashMap<String, String>();
        Configuration database = config.subset("database");
        hibernateProperties.put(Environment.DRIVER, database.getString("driver"));
        hibernateProperties.put(Environment.URL, database.getString("url"));
        hibernateProperties.put(Environment.USER, database.getString("user"));
        hibernateProperties.put(Environment.PASS, database.getString("password"));
        hibernateProperties.put(Environment.DATASOURCE, null);

        HibernateUtil.setProperties(hibernateProperties);

        if (!sitemaponly) {
            //test(config);
            // Get the server configuration to download the content
            Configuration provider = config.subset("provider");
            InetAddress server = InetAddress.getByName(provider.getString("server"));
            File destinationFolder = new File(provider.getString("destinationFolder"));
            String username = provider.getString("username");
            String password = provider.getString("password");
            String remoteDirectory = provider.getString("remoteWorkingDirectory");
            boolean forceDownload = provider.getBoolean("forceDownload");
            Downloader downloader = new Downloader(server, username, password, destinationFolder,
                    remoteDirectory, forceDownload);
            int count = downloader.downloadFiles();
            log.info("Downloaded " + count + " files");
            //         int count = 14;
            if (count > 0) {
                log.info("Processing downloads now.");
                //Get the name of the files to process
                Configuration files = config.subset("files");
                File headend = new File(destinationFolder, files.getString("headend"));
                File lineup = new File(destinationFolder, files.getString("lineup"));
                File stations = new File(destinationFolder, files.getString("stations"));
                File programs = new File(destinationFolder, files.getString("programs"));
                File schedules = new File(destinationFolder, files.getString("schedules"));

                Parser parser = new Parser(config, headend, lineup, stations, programs, schedules);
                parser.parse();
                log.info("Finished parsing EPG Data. Invoking AlertQueue service now.");
                String alertUrl = config.getString("alertUrl");
                HessianProxyFactory factory = new HessianProxyFactory();
                AlertQueue alerts = (AlertQueue) factory.create(AlertQueue.class, alertUrl);
                alerts.checkAlerts();
                log.info("Updating sitemap");
                updateSitemap(config.getString("sitemap", "/usr/local/webapps/search/sitemap.xml.gz"));
                log.info("Exiting EPG now.");
            } else {
                log.info("No files were downloaded, so don't process the old files.");
            }
        } else {
            log.info("Updating sitemap");
            updateSitemap(config.getString("sitemap", "/usr/local/webapps/search/sitemap.xml.gz"));
            log.info("Done updating sitemap");
        }
    } catch (ConfigurationException e) {
        log.fatal("Configuration error in file " + configFile, e);
        e.printStackTrace();
    } catch (UnknownHostException e) {
        log.fatal("Unable to connect to host", e);
        e.printStackTrace();
    } catch (IOException e) {
        log.fatal("Error downloading or processing EPG information", e);
        e.printStackTrace();
    } catch (Throwable e) {
        log.fatal("Unexpected Error", e);
        e.printStackTrace();
    }

}

From source file:proxy.ElementalHttpGet.java

public static void main(String[] args) throws Exception {
    //      String localIp = args[0];
    //      System.out.println("localIp: " + localIp);
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent())
            .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1"))
            .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("api.weibo.com", 443, "https");
    coreContext.setTargetHost(host);/* ww w.  j  a  v a 2  s .c  om*/
    //      for (InetAddress localinetAddress : getAllIp("eth0")) {
    //         System.out.println(localinetAddress.getHostAddress());
    request(httpproc, httpexecutor, coreContext, host, InetAddress.getByName("60.169.74.152"));
    //      }

}

From source file:examples.server2serverFTP.java

public static final void main(String[] args) {
    String server1, username1, password1, file1;
    String server2, username2, password2, file2;
    FTPClient ftp1, ftp2;/*from w  w  w. j  a  v  a 2s .co m*/
    ProtocolCommandListener listener;

    if (args.length < 8) {
        System.err.println("Usage: ftp <host1> <user1> <pass1> <file1> <host2> <user2> <pass2> <file2>");
        System.exit(1);
    }

    server1 = args[0];
    username1 = args[1];
    password1 = args[2];
    file1 = args[3];
    server2 = args[4];
    username2 = args[5];
    password2 = args[6];
    file2 = args[7];

    listener = new PrintCommandListener(new PrintWriter(System.out));
    ftp1 = new FTPClient();
    ftp1.addProtocolCommandListener(listener);
    ftp2 = new FTPClient();
    ftp2.addProtocolCommandListener(listener);

    try {
        int reply;
        ftp1.connect(server1);
        System.out.println("Connected to " + server1 + ".");

        reply = ftp1.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp1.disconnect();
            System.err.println("FTP server1 refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp1.isConnected()) {
            try {
                ftp1.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server1.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        int reply;
        ftp2.connect(server2);
        System.out.println("Connected to " + server2 + ".");

        reply = ftp2.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp2.disconnect();
            System.err.println("FTP server2 refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp2.isConnected()) {
            try {
                ftp2.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server2.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp1.login(username1, password1)) {
            System.err.println("Could not login to " + server1);
            break __main;
        }

        if (!ftp2.login(username2, password2)) {
            System.err.println("Could not login to " + server2);
            break __main;
        }

        // Let's just assume success for now.
        ftp2.enterRemotePassiveMode();

        ftp1.enterRemoteActiveMode(InetAddress.getByName(ftp2.getPassiveHost()), ftp2.getPassivePort());

        // Although you would think the store command should be sent to server2
        // first, in reality, ftp servers like wu-ftpd start accepting data
        // connections right after entering passive mode.  Additionally, they
        // don't even send the positive preliminary reply until after the
        // transfer is completed (in the case of passive mode transfers).
        // Therefore, calling store first would hang waiting for a preliminary
        // reply.
        if (ftp1.remoteRetrieve(file1) && ftp2.remoteStoreUnique(file2)) {
            //      if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) {
            // We have to fetch the positive completion reply.
            ftp1.completePendingCommand();
            ftp2.completePendingCommand();
        } else {
            System.err.println("Couldn't initiate transfer.  Check that filenames are valid.");
            break __main;
        }

    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    } finally {
        try {
            if (ftp1.isConnected()) {
                ftp1.logout();
                ftp1.disconnect();
            }
        } catch (IOException e) {
            // do nothing
        }

        try {
            if (ftp2.isConnected()) {
                ftp2.logout();
                ftp2.disconnect();
            }
        } catch (IOException e) {
            // do nothing
        }
    }
}

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 w  w .  j  a v  a2s  .  c o m
        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:com.boulmier.machinelearning.jobexecutor.JobExecutor.java

public static void main(String[] args) throws ParseException, IOException, InterruptedException {
    Options options = defineOptions();/* w  w w. j  av a  2  s. c  o  m*/
    sysMon = new JavaSysMon();
    InetAddress vmscheduler_ip, mongodb_ip = null;
    Integer vmscheduler_port = null, mongodb_port = null;
    CommandLineParser parser = new BasicParser();

    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGPORTFIELD)) {
            vmscheduler_port = Integer.valueOf(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGPORTFIELD));
        }
        mongodb_port = (int) (cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGMONGOPORTFIELD)
                ? cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGMONGOPORTFIELD)
                : JobExecutorConfig.OPTIONS.LOGGING.MONGO_DEFAULT_PORT);
        mongodb_ip = InetAddress.getByName(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGMONGOIPFIELD));

        vmscheduler_ip = InetAddress.getByName(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGIPFIELD));

        decryptKey = cmd.getOptionValue("decrypt-key");

        debugState = cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGDEBUGFIELD);

        logger = LoggerFactory.getLogger();
        logger.info("Attempt to connect on master @" + vmscheduler_ip + ":" + vmscheduler_port);

        new RequestConsumer().start();

    } catch (MissingOptionException moe) {
        logger.error(moe.getMissingOptions() + " are missing");
        HelpFormatter help = new HelpFormatter();
        help.printHelp(JobExecutor.class.getSimpleName(), options);

    } catch (UnknownHostException ex) {
        logger.error(ex.getMessage());
    } finally {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                logger.info("JobExeutor is shutting down");
            }
        });
    }
}

From source file:com.knowbout.epg.processor.Downloader.java

public static void main(String[] args) throws Exception {
    InetAddress server = InetAddress.getByName("ftp.tmstv.com");
    File destinationFolder = new File("data/samples");
    Downloader downloader = new Downloader(server, "kno868cb", "FYS141ca", destinationFolder, "pub", false);
    int count = downloader.downloadFiles();
    System.err.println("Downloaded " + count + " files");
}

From source file:com.xiangzhurui.util.ftp.ServerToServerFTP.java

public static void main(String[] args) {
    String server1, username1, password1, file1;
    String server2, username2, password2, file2;
    String[] parts;//  w  w  w . j  a va 2  s  .  c  om
    int port1 = 0, port2 = 0;
    FTPClient ftp1, ftp2;
    ProtocolCommandListener listener;

    if (args.length < 8) {
        System.err.println(
                "Usage: com.xzr.practice.util.ftp <host1> <user1> <pass1> <file1> <host2> <user2> <pass2> <file2>");
        System.exit(1);
    }

    server1 = args[0];
    parts = server1.split(":");
    if (parts.length == 2) {
        server1 = parts[0];
        port1 = Integer.parseInt(parts[1]);
    }
    username1 = args[1];
    password1 = args[2];
    file1 = args[3];
    server2 = args[4];
    parts = server2.split(":");
    if (parts.length == 2) {
        server2 = parts[0];
        port2 = Integer.parseInt(parts[1]);
    }
    username2 = args[5];
    password2 = args[6];
    file2 = args[7];

    listener = new PrintCommandListener(new PrintWriter(System.out), true);
    ftp1 = new FTPClient();
    ftp1.addProtocolCommandListener(listener);
    ftp2 = new FTPClient();
    ftp2.addProtocolCommandListener(listener);

    try {
        int reply;
        if (port1 > 0) {
            ftp1.connect(server1, port1);
        } else {
            ftp1.connect(server1);
        }
        System.out.println("Connected to " + server1 + ".");

        reply = ftp1.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp1.disconnect();
            System.err.println("FTP server1 refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp1.isConnected()) {
            try {
                ftp1.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server1.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        int reply;
        if (port2 > 0) {
            ftp2.connect(server2, port2);
        } else {
            ftp2.connect(server2);
        }
        System.out.println("Connected to " + server2 + ".");

        reply = ftp2.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp2.disconnect();
            System.err.println("FTP server2 refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp2.isConnected()) {
            try {
                ftp2.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server2.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp1.login(username1, password1)) {
            System.err.println("Could not login to " + server1);
            break __main;
        }

        if (!ftp2.login(username2, password2)) {
            System.err.println("Could not login to " + server2);
            break __main;
        }

        // Let's just assume success for now.
        ftp2.enterRemotePassiveMode();

        ftp1.enterRemoteActiveMode(InetAddress.getByName(ftp2.getPassiveHost()), ftp2.getPassivePort());

        // Although you would think the store command should be sent to
        // server2
        // first, in reality, com.xzr.practice.util.ftp servers like wu-ftpd start accepting data
        // connections right after entering passive mode. Additionally, they
        // don't even send the positive preliminary reply until after the
        // transfer is completed (in the case of passive mode transfers).
        // Therefore, calling store first would hang waiting for a
        // preliminary
        // reply.
        if (ftp1.remoteRetrieve(file1) && ftp2.remoteStoreUnique(file2)) {
            // if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) {
            // We have to fetch the positive completion reply.
            ftp1.completePendingCommand();
            ftp2.completePendingCommand();
        } else {
            System.err.println("Couldn't initiate transfer.  Check that filenames are valid.");
            break __main;
        }

    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    } finally {
        try {
            if (ftp1.isConnected()) {
                ftp1.logout();
                ftp1.disconnect();
            }
        } catch (IOException e) {
            // do nothing
        }

        try {
            if (ftp2.isConnected()) {
                ftp2.logout();
                ftp2.disconnect();
            }
        } catch (IOException e) {
            // do nothing
        }
    }
}