fwhois.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.net.examples.unix;

  18. import java.io.IOException;
  19. import java.net.InetAddress;
  20. import java.net.UnknownHostException;

  21. import org.apache.commons.net.whois.WhoisClient;

  22. /**
  23.  * This is an example of how you would implement the Linux fwhois command in Java using NetComponents. The Java version is much shorter.
  24.  */
  25. public final class fwhois {

  26.     public static void main(final String[] args) {
  27.         final int index;
  28.         final String handle;
  29.         final String host;
  30.         InetAddress address = null;
  31.         final WhoisClient whois;

  32.         if (args.length != 1) {
  33.             System.err.println("usage: fwhois handle[@<server>]");
  34.             System.exit(1);
  35.         }

  36.         index = args[0].lastIndexOf('@');

  37.         whois = new WhoisClient();
  38.         // We want to timeout if a response takes longer than 60 seconds
  39.         whois.setDefaultTimeout(60000);

  40.         if (index == -1) {
  41.             handle = args[0];
  42.             host = WhoisClient.DEFAULT_HOST;
  43.         } else {
  44.             handle = args[0].substring(0, index);
  45.             host = args[0].substring(index + 1);
  46.         }

  47.         try {
  48.             address = InetAddress.getByName(host);
  49.             System.out.println("[" + address.getHostName() + "]");
  50.         } catch (final UnknownHostException e) {
  51.             System.err.println("Error unknown host: " + e.getMessage());
  52.             System.exit(1);
  53.         }

  54.         try {
  55.             whois.connect(address);
  56.             System.out.print(whois.query(handle));
  57.             whois.disconnect();
  58.         } catch (final IOException e) {
  59.             System.err.println("Error I/O exception: " + e.getMessage());
  60.             System.exit(1);
  61.         }
  62.     }

  63. }