If something throws an exception, you neither return the socket nor Close
/Dispose
it.
Try:
try
{
tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream,
ProtocolType.Tcp);
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
return tempSocket;
}
tempSocket.Close();
tempSocket = null;
}
catch (Exception)
{
if (tempSocket != null)
tempSocket.Close();
throw;
}