Connecting to an SSH server on an alternate port allows secure remote access even when the default port 22 is blocked or restricted. Many environments shift SSH to a different TCP port to reduce automated scans or to comply with network policies, so specifying the correct port is required for every connection attempt.
An SSH client assumes port 22 unless a different port is provided explicitly. The port can be overridden on the command line with the -p option or encoded in the per-user configuration file at ~/.ssh/config, ensuring that the client opens the TCP connection to the exact endpoint defined by the server.
If the server listens on a custom port that is not reachable through firewalls or NAT rules, connections fail even when credentials are correct. Verifying reachability first helps distinguish network issues from authentication problems, and storing the port in the configuration file avoids mistakes in repeated manual input. The steps below assume a terminal using OpenSSH on Linux or macOS; other clients follow the same pattern for specifying a non-default port.
Steps to connect to SSH server on custom port:
- Identify the TCP port that the SSH server is configured to use.
Obtain this value from server documentation, the administrator, or the /etc/ssh/sshd_config setting on the host.
- Verify that the client can reach the server's specified port.
$ nc -zv host.example.net 2222 Connection to host.example.net (203.0.113.50) 2222 port [tcp/*] succeeded!
-v Produce more verbose output. -z Only scan for listening daemons, without sending any data to them. Cannot be used together with -l. - Connect to the server by specifying the custom port on the command line.
$ ssh -p 2222 user@host.example.net 'hostname' host
The -p option instructs ssh to connect to the given TCP port instead of the default 22.
- Optionally, define a host entry in the per-user SSH configuration file so future commands omit the port flag.
$ cat ~/.ssh/config Host host-alt-port HostName host.example.net User user Port 2222 IdentityFile ~/.ssh/id_ed25519Entries in ~/.ssh/config allow short host aliases with preconfigured HostName, User, and Port values.
- Connect to the server using the specified host name defined in the configuration file.
$ ssh host-alt-port hostname host
- Confirm that the SSH client resolves the alias to the expected port.
$ ssh -G host-alt-port | grep ^port port 2222
The ssh -G diagnostic command prints the final configuration after combining all files and defaults, making it useful for checking which port and user are selected.
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.
