What is a port?

Tim Rohaly

Port numbers are the means by which an operating system routes incoming packets to the appropriate waiting process. Only one process at a time can listen for incoming packets on a given port. The combination of destination IP address and port uniquely identifies the destination process for a packet. Likewise, the combination of source IP address and port uniquely identifies the source process.

For both TCP and UDP, the port number field of a packet is specified as a 16-bit unsigned integer - this means that valid port numbers range from 1 through 65535. (Port number 0 is reserved and can't be used).

Java does not have any unsigned data types; Java's short data type is 16 bits, but its range is -32768 to 32767 because it is a signed type. Thus, short is not large enough to hold a port number, so all classes which use or return a port number must represent the port number as an int. In the JDK 1.1+, using an int with a value greater than 65535 will generate an IllegalArgumentException. In the JDK 1.0.2 and earlier, values greater than 65535 are truncated and only the low-order 16 bits are used.

Port numbers 1 through 255 are reserved for well-known services. A well-known service is a service that is widely implemented which resides at a published, "well-known", port. If you connect to port 80 of a host, for instance, you may expect to find an HTTP server. On UNIX machines, ports less than 1024 are privileged and can only be bound by the root user. This is so an arbitrary user on a multi-user system can't impersonate well-known services like TELNET (port 23), creating a security problem. Windows has no such restrictions, but you should program as if it did so that your applications will work cross-platform.