How to get one process’s port number?

Finding Ports Used by a Process

Identifying which ports a specific process is using comes up regularly in debugging, security audits, and infrastructure management. Here are the practical methods.

Using ss

The ss command is the modern standard for socket inspection:

ss -tlnp | grep <PID>

This shows listening TCP sockets (-t for TCP, -l for listening). Add -u if you need UDP ports too:

ss -tlnup | grep <PID>

The flags break down as:

  • -t / -u: TCP / UDP protocols
  • -l: listening sockets only
  • -n: numeric output (no service name lookups)
  • -p: show the process name and PID

If you know the process name but not the PID, combine it with pgrep:

ss -tlnp | grep $(pgrep -f nginx)

For all sockets (not just listening), drop the -l:

ss -tnp | grep <PID>

Using lsof

lsof (list open files) also works, though it’s typically slower on systems with many connections:

lsof -i -P -n | grep <PID>

Flags:

  • -i: show network sockets
  • -P: numeric ports (no service names)
  • -n: numeric addresses (no DNS lookups)

You can also be more specific with protocol and port:

lsof -i :8080
lsof -i TCP:3306

This approach is useful when you know the port and want to find what’s using it.

Checking Ports by Name

If you only have the process name:

ss -tlnp | grep nginx

Or with lsof:

lsof -i -P -n | grep postgres

In Containers

For Docker containers, inspect port mappings with:

docker port <container_id>
docker inspect <container_id> | grep -A 5 PortBindings

In Kubernetes, check service-to-pod port mappings:

kubectl get svc <service_name> -o wide
kubectl get pods <pod_name> -o jsonpath='{.spec.containers[*].ports}'

If you need to see ports from inside a container, the same ss and lsof commands work—just exec in:

docker exec <container_id> ss -tlnp
kubectl exec <pod_name> -- ss -tlnp

Common Scenarios

Find what’s using a specific port:

ss -tlnp | grep :8080
lsof -i :8080

List all listening ports for a service:

systemctl show -p MainPID <service_name> | cut -d= -f2 | xargs -I {} ss -tlnp | grep {}

Or simpler, if systemd integration is enabled:

ss -tlnp | grep <service_name>

Monitor connections to a port in real-time:

watch -n 1 'ss -tnp | grep :8080'

Why ss Over netstat

ss is significantly faster than the deprecated netstat on systems with thousands of connections. It queries /proc directly and scales better with modern workloads. If you’re still using netstat, migrate to ss—the command syntax is nearly identical.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *