This exception is thrown when a socket-related error occurs during network operations.
Details
The SocketException class derives from IOException and provides information about socket errors. It contains a SocketErrorCode property that specifies the specific error that occurred.
Common Causes
- Network unreachable or unavailable.
- Connection refused by the remote host.
- Invalid IP address or port number.
- Timeout during connection or data transfer.
- Firewall blocking the connection.
- Insufficient network resources.
- Trying to use a socket that has been closed.
SocketErrorCode Enum
The SocketError enumeration defines the possible errors that can occur. Some common values include:
- 10004 (
SocketError.ConnectionAborted): A connection attempt failed because the connected party did not properly respond after a period of time or the established connection was broken or re-established. - 10013 (
SocketError.AccessDenied): An attempt was made to access a socket in a way forbidden by its access permissions. - 10048 (
SocketError.AddressInUse): Only one usage of each socket address (protocol/network address/port) is normally permitted. - 10051 (
SocketError.NetworkUnreachable): A socket operation encountered a dead end. The local system is unable to deliver the IP datagram to the intended destination. - 10054 (
SocketError.ConnectionReset): An existing connection was forcibly closed by the remote host. - 10060 (
SocketError.ConnectionRefused): A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection was broken or re-established. - 10061 (
SocketError.ConnectionRefused): No connection could be made because the target machine actively refused it.
Handling the Exception
It is crucial to handle SocketException to gracefully manage network errors in your application. You can use a try-catch block to intercept and process these exceptions.
try { // Network operation that might throw SocketException Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect("invalid.host.name", 12345); } catch (SocketException ex) { // Log the exception or display an error message to the user Console.WriteLine($"SocketException caught: {ex.SocketErrorCode} - {ex.Message}"); // You can also check specific error codes for different handling if (ex.SocketErrorCode == SocketError.ConnectionRefused) { Console.WriteLine("Connection refused. Ensure the server is running."); } }