The class has three constructors:

 public DatagramSocket() throws SocketException
 public DatagramSocket(int port) throws SocketException
 public DatagramSocket(int port, InetAddress laddr) throws SocketException

The first is used for datagram sockets that are primarily intended to act as clients; that is sockets that will send datagrams before receiving any. The secned two that specify the port and optionally the IP address of the socket, are primarily intended for servers that must run on a well-known port.

The LocalPortScanner developed earlier only found TCP ports. The following program detects UDP ports in use. As with TCP ports, you must be root on Unix systems to bind to ports below 1024.


public class UDPPortScanner {

  public static void main(String[] args) {

    // first test to see whether or not we can bind to ports
    // below 1024
    boolean rootaccess = false;
    for (int port = 1; port < 1024; port += 50) {
      try {
        ServerSocket ss = new ServerSocket(port);
        // if successful
        rootaccess = true;
      catch (IOException ex) {
    int startport = 1;
    if (!rootaccess) startport = 1024;
    int stopport = 65535;
    for (int port = startport; port <= stopport; port++) {
      try {
        DatagramSocket ds = new DatagramSocket(port);
      catch (IOException ex) {
        System.out.println("UDP Port " + port + " is occupied.");



Since UDP is connectionless it is not possible to write a remote UDP port scanner. The only way you know whether or not a UDP server is listening on a remote port is if it sends something back to you.

Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
Last Modified April 18, 1997