Catch socket errors in C#

The System.Net.Sockets SocketException represents the error that occurs when a socket error occurs. A SocketException is thrown by the Socket and System.Net.Dns classes when a network error occurs.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SocketExceptionSample
{
    public static void Main()
    {
        try
        {
            FetchPage();
        }
        catch (SocketException se)
        {
            Console.WriteLine("Socket Error - code:" + se.ErrorCode);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine("Press Enter to continue");
        Console.ReadLine();
    }
    private static void FetchPage()
    {
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        string targ = "/default.htm";
        Socket skt = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp);
        try
        {
            IPEndPoint ep = new IPEndPoint(ip, 9999);
            skt.Connect(ep);
            if (skt.Connected)
            {
                Byte[] req = Encoding.ASCII.GetBytes("GET " + targ + "\n");
                skt.Send(req);
                Byte[] res = new Byte[1024];
                int rec = skt.Receive(res);
                skt.Shutdown(SocketShutdown.Both);
                Console.WriteLine("Received {0} bytes for {1}:",
                rec, targ);
                Console.WriteLine(Encoding.ASCII.GetString(res, 0, rec));
            }
            else
            {
                throw new Exception("Cannot connect to Host");
            }
        }
        catch (Exception e)
        {
            throw new SocketException();
        }
        finally
        {
            skt.Close();
        }
    }
}

Output:

Socket Error – code:10061
Press Enter to continue

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.