title: Test if Socket is connected in C#
body: <p>Hi i am writing a simple server program that is listening for connections. My Question is, How  can I test if the socket is connected or not. Here is my code</p>
  
  <pre><code>using System;
  using System.Net;
  using System.Net.Sockets;
  
  class server
  {
      static int port = 0;
      static String hostName = Dns.GetHostName();
      static IPAddress ipAddress;
      static bool listening = true;
  
      public static void Main(String[] args)
      {
          IPHostEntry ipEntry = Dns.GetHostByName(hostName);
  
          //Get a list of possible ip addresses
          IPAddress[] addr = ipEntry.AddressList;
  
          //The first one in the array is the ip address of the hostname
          ipAddress = addr[0];
  
          TcpListener server = new TcpListener(ipAddress,port);
  
          Console.Write("Listening for Connections on " + hostName + "...");
  
          do
          {
  
              //start listening for connections
              server.Start();
  
  
  
          } while (listening);
  
  
          //Accept the connection from the client, you are now connected
          Socket connection = server.AcceptSocket();
  
          Console.Write("You are now connected to the server");
  
          connection.Close();
  
  
      }
  
  
  }
  </code></pre>