Could someone write me this easy, short java program? 10 points!?

Short Run Printing

I need a program that, when run, will do the cmd command that is in the program. For example, I want it to ping www.google.com and then print the IP address.


One Response to “Could someone write me this easy, short java program? 10 points!?”

  1. tgtips — May 12, 2010 @ 2:27 pm

    Hi,

    There are several means to achieve your goal, but only since Java 1.5 onwards when they began supporting low level port controls.

    Having said, several ways, I cannot think of a short way, however, here is some code that would allow the user to enter a web address and get the IP, or to enter an IP and get the web address.

    If you do not want both, just delete the one you’d rather not use, or comment it out using either // or /* */

    Here goes:

    import java.net.*;
    import java.io.*;

    public class nslookup {

    public static void main (String args[]) {

    BufferedReader myInputStream =
    new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Name Service lookup utility\r\n"+
    "Enter names or IP addresses. Enter \"exit\" to quit.");
    while (true) {
    String inputString;
    try {
    System.out.print("> ");
    inputString = myInputStream.readLine();
    }
    catch (IOException e) {
    break;
    }
    if (inputString.equals("exit")) break;
    lookup(inputString);
    }
    } /* end main */
    private static void lookup(String s) {
    InetAddress address;
    // get the bytes of the IP address
    try {
    address = InetAddress.getByName(s);
    }
    catch (UnknownHostException ue) {
    System.out.println("** Can’t find host " + s);
    return;
    }
    if (isHostname(s)) {
    System.out.println(" Address: "+address.getHostAddress());
    }
    else { // this is an IP address
    System.out.println(" Name: "+address.getHostName());
    }
    } // end lookup
    private static boolean isHostname(String s) {
    char[] ca = s.toCharArray();
    // if we see a character that is neither a digit nor a period
    // then s is probably a hostname
    for (int i = 0; i < ca.length; i++) {
    if (!Character.isDigit(ca[i]) &&
    ca[i] != ‘.’) return true;
    }
    // Everything was either a digit or a period
    // so s looks like an IP address in dotted quad format
    return false;
    } // end isHostName
    } // end nslookup

    Regards,

    TgTips

    PS: I saw you original post also, but it was not one of those 2 min answers, so after writing some code, I noticed you reposted and figured I better reply to this one.

Leave a Reply

Powered by Yahoo! Answers
Powered by WP VideoTube