# Ports and Sockets
## What are Ports
A port is a 16-bit number ranging from 0 to 65535 that is used to identify a specific application or service on a host. IP addresses identify hosts, but a host may be running many different applications simultaneously, all communicating over the same network interface. Port numbers allow the Transport layer to direct incoming data to the correct application. When a server application starts, it binds to a specific port number and listens for incoming connections or datagrams on that port.
## Port Number Ranges
Port numbers are divided into three ranges. Well-known ports from 0 to 1023 are assigned by the Internet Assigned Numbers Authority to specific well-known services. These ports are used by server applications to listen for incoming connections. HTTP uses port 80, HTTPS uses 443, SSH uses 22, FTP uses 21 for control and 20 for data, SMTP uses 25, DNS uses 53, DHCP uses 67 for server and 68 for client, and POP3 uses 110.
Registered ports from 1024 to 49151 are registered with IANA for specific applications but can be used by any process. Many database systems and application servers use ports in this range.
Dynamic or ephemeral ports from 49152 to 65535 are used by client applications for the client side of connections. When a client initiates a TCP connection to a server, the operating system automatically assigns an ephemeral port from this range as the source port. Different operating systems use different ranges for ephemeral ports.
## What is a Socket
A socket is an endpoint for communication defined by the combination of an IP address and a port number. A socket is written in the notation IP_address:port_number, such as 192.168.1.5:80. A TCP connection is uniquely identified by a pair of sockets: the source socket consisting of the source IP address and source port, and the destination socket consisting of the destination IP address and destination port. This four-tuple allows a server to maintain many simultaneous connections from different clients, and even multiple connections from the same client, because each connection has a unique combination.
## Socket API
The socket API is a programming interface that allows applications to create and use network connections. An application creates a socket, binds it to a local address and port, and then either connects to a remote server or listens for incoming connections. Data is sent and received through the socket as if it were a file. The socket API was originally developed for Unix systems and is now available on virtually all operating systems.
## Port Scanning
Port scanning is the process of sending probes to a range of port numbers on a host to determine which services are running. Network administrators use port scanning to audit their systems. Security tools like Nmap perform port scanning. A firewall can be configured to block port scanning attempts or to limit which ports are accessible from outside the network.Back to Course