Java Tutorial/Network/Port

Материал из Java эксперт
Версия от 05:03, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

High Port Scanner

import java.net.InetAddress;
import java.net.Socket;
public class MainClass {
  public static void main(String[] args) {
    String host = "localhost";
    try {
      InetAddress theAddress = InetAddress.getByName(host);
      for (int i = 1024; i < 65536; i++) {
        Socket theSocket = new Socket(theAddress, i);
        System.out.println("There is a server on port " + i + " of " + host);
      }
    } catch (Exception ex) {
      System.err.println(ex);
    }
  }
}





Local Port Scanner

import java.io.IOException;
import java.net.ServerSocket;
public class MainClass {
  public static void main(String[] args) {
    for (int port = 1; port <= 65535; port++) {
      try {
        // the next line will fail and drop into the catch block if
        // there is already a server running on the port
        ServerSocket server = new ServerSocket(port);
      } catch (IOException ex) {
        System.out.println("There is a server on port " + port + ".");
      }
    }
  }
}





Low Port Scanner

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainClass {
  public static void main(String[] args) {
    String host = "localhost";
    for (int i = 1; i < 1024; i++) {
      try {
        Socket s = new Socket(host, i);
        System.out.println("There is a server on port " + i + " of " + host);
      } catch (UnknownHostException ex) {
        System.err.println(ex);
        break;
      } catch (IOException ex) {
      }
    }
  }
}





Port Scanner

import java.net.InetAddress;
import java.net.Socket;
public class MainClass {
  public static void main(String[] args) {
    String host = "localhost";
    try {
      InetAddress theAddress = InetAddress.getByName(host);
      for (int i = 1; i < 65536; i++) {
        Socket connection = null;
        connection = new Socket(host, i);
        System.out.println("There is a server on port " + i + " of " + host);
        if (connection != null)
          connection.close();
      } // end for
    } catch (Exception ex) {
      System.err.println(ex);
    }
  }
}





UDP Port Scanner

import java.net.DatagramSocket;
import java.net.SocketException;
public class MainClass {
  public static void main(String[] args) {
    for (int port = 1024; port <= 65535; port++) {
      try {
        // the next line will fail and drop into the catch block if
        // there is already a server running on port i
        DatagramSocket server = new DatagramSocket(port);
        server.close();
      } catch (SocketException ex) {
        System.out.println("There is a server on port " + port + ".");
      }
    }
  }
}