In C, how to check if a TCP port is available?
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
In C#, checking if a TCP port is available means verifying that no other process is currently listening on or bound to that port. The most reliable method is to attempt to bind a TcpListener to the port and catch the SocketException if it fails. Alternatively, you can query the system's active TCP connections using IPGlobalProperties.GetActiveTcpListeners() for a non-binding check. Both approaches have trade-offs between reliability and race conditions.
Method 1: Try to Bind with TcpListener
The most reliable approach — actually attempt to use the port:
This method is reliable because it tests the actual system state. However, there is a race condition — the port could be taken between checking and actually using it.
Method 2: Check Active TCP Listeners
Query the OS for all active TCP endpoints without binding:
This avoids the side effect of binding, but can miss ports in TIME_WAIT state or ports bound to specific interfaces.
Method 3: Find a Free Port Automatically
Let the OS assign an available port:
This is the safest approach when you need any free port and do not require a specific number.
Method 4: Check a Range of Ports
Method 5: Check with Async Support
Checking Both TCP and UDP
Bind-Then-Use Pattern (Race-Free)
To avoid the race condition between checking and using:
Common Pitfalls
- Race condition between check and use: Checking port availability and then starting a server are two separate operations. Another process can bind the port in between. The safest pattern is to attempt to bind directly and handle
SocketExceptionif the port is taken, rather than checking first. - Only checking IPAddress.Loopback: A port bound to
IPAddress.Any(0.0.0.0) is not detected by a check againstIPAddress.Loopback(127.0.0.1) on some platforms. Check against the same address your server will use, or check bothLoopbackandAny. - Ignoring TIME_WAIT state: After a TCP connection closes, the port enters TIME_WAIT for 60-240 seconds.
GetActiveTcpListeners()may not show it, but binding fails. UseSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true)to bind to TIME_WAIT ports. - Checking ports in the ephemeral range: Ports 49152-65535 are used by the OS for outbound connections. Even if a port appears free, the OS may assign it to an outbound connection at any time. Use ports in the registered range (1024-49151) for services.
- Not running as administrator for well-known ports: Binding to ports 0-1023 requires elevated privileges on most operating systems. A
SocketExceptionon these ports does not necessarily mean the port is in use — it may be a permission issue. Check the exception'sSocketErrorCodeproperty.
Summary
- Use
TcpListenerwith try/catch to reliably test if a port is available - Use
IPGlobalProperties.GetActiveTcpListeners()for a non-binding check (less reliable) - Bind to port 0 to let the OS assign any available port automatically
- Prefer the bind-then-use pattern to avoid race conditions between checking and binding
- Check both
IPAddress.LoopbackandIPAddress.Anyto match your server's binding address - Handle
SocketException.SocketErrorCodeto distinguish "port in use" from "permission denied"
Related reading
- In Tensorflow's Dataset API how do you map one element into multiple elements?
- In Terraform, how do you specify an API Gateway endpoint with a variable in the request path?
- In what order are Netty handlers called?
- In what way do socket reads differ from file reads?
- In C, should I use string.Empty or String.Empty or to intitialize a string?
- In C, What is FuncT1, T2, and what is it for?
- In which case do you use the JPA JoinTable annotation?
- inconsistent state after zookeeper leader crash?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.