Error Handling and Socket Shutdown
What you'll learn: How to properly detect, handle socket errors, and gracefully close network connections without leaving resources dangling.
When working with sockets, things go wrong—networks drop, servers crash, buffers fill up. Without proper error handling, your application can leak resources, hang indefinitely, or crash unexpectedly. Just as important as opening a connection is closing it cleanly so both sides know communication has ended.
Common Socket Errors
Socket operations can fail in many ways:
- Connection refused: The server isn't listening on that port
- Broken pipe: Writing to a socket after the other end has closed
- Timeout: Operations taking too long (if timeouts are configured)
- Network unreachable: Routing problems prevent connection
- Address already in use: Trying to bind to a port already bound
Most socket functions return -1 (or similar error indicators) on failure and set an error code you can inspect to understand what went wrong.
Error Handling Strategies
Always check return values from socket operations like send(), recv(), connect(), accept(), etc. When errors occur:
- Log meaningful error messages
- Clean up resources (close sockets)
- Decide whether to retry or fail gracefully
- Don't assume operations succeed—network programming is inherently unreliable
Graceful Shutdown
Think of socket shutdown like ending a phone call politely rather than just hanging up. Use a proper close/shutdown sequence:
- Stop sending new data
- Flush any remaining buffered data
- Close the socket to release the file descriptor
- Handle any errors during shutdown itself
For TCP, you can use half-close (shutdown one direction while keeping the other open) to signal "I'm done sending" while still receiving.
Key Takeaway: Robust socket programs always check for errors on every operation and perform graceful shutdowns to prevent resource leaks and ensure both endpoints cleanly terminate connections.