Suddenly server cannot connect due to SocketException - c#

I am using this server example from MSND: http://msdn.microsoft.com/en-us/library/fx6588te.aspx
and from some reason my server refuse to connect at this function at _listener.Bind(localEndPoint); with error Only one usage of each socket address (protocol/network address/port) is normally permitted
Until a few minutes ago I had no problems Sarver connect without problems and suddenly it happens
public static void StartListening(IPAddress ipAddress, int port)
{
_isServerRunning = true;
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
//IPAddress ipAddress = IPAddress.Parse("192.168.0.100"); //ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
_listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
_listener.Bind(localEndPoint);
_listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
_listener.BeginAccept(
new AsyncCallback(AcceptCallback),
_listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
//Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
What does this error means ?

It most likely means that the local port is still reserved. This can be idther because another process is still runnoing and holding the sockewt open, or because the timeout period defined by th dSO_LINGER socket option is not timed out. I'm not familiar with c# but there should be a way to set th elinger timeout.
You can tell the current status of the socket by using the netstat command.

I think you can find some solutions here http://blogs.msdn.com/b/dgorti/archive/2005/09/18/470766.aspx

Related

Server application get bad ipHostInfo.AddressList[0]

I have server application .
If I run it at server application just do not communicate with client. I try allow all ports used ports in firewall also whole application, but it did not helped. At localhost it works fine. Working system is correctly updated Win 10. Server is windows server 2012.
public void Listen(object data)
{
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...at" + localEndPoint.ToString());
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
Seems you should be using IPv4 Adresses.
You can use IPAdress's AdressFamily property to get a to valid IPv4 Address ("InterNetwork"). Also check isLoopback().
So, basically
IPAdress myIp = ipHostInfo
.AddressList
.Where( a => a.AddressFamily == AddressFamily.InterNetwork)
.FirstOrDefault(x => !IPAdress.IsLoopback(x));
should give you a good one if one exists.
... or as Damien_The_Unbeliever so greatly reminded me in comment:
Just use IPAdress.Any to listen on any ip.

C# Unable to connect to localhost

I'm writing a very simple .NET TCP Server and very simple TCP Client that should both run on the same machine (Window 10 Home PC) and connect each other (for testing purposes only).
In the server I'm waiting for the connection in this way:
public static void StartListening()
{
string hostname = Dns.GetHostName();
IPHostEntry ipHostInfo = Dns.GetHostEntry(hostname);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Properties.Settings.Default.Port);
Socket listener = new Socket(
ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(Properties.Settings.Default.Port);
while (true)
{
allDone.Reset();
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
var frames = Directory.EnumerateFiles(Properties.Settings.Default.FramesPath);
foreach (string filename in frames)
{
Console.Write("Sending frame: {}...", filename);
SendFile(handler, filename);
Thread.Sleep(Properties.Settings.Default.FrameDelay);
}
}
In the client I'm creating a connection in this way:
private void startClient(string host, int port)
{
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(host), port);
ClientTCP = new TcpClient();
ClientTCP.Connect(serverEndPoint);
Reader = new StreamReader(ClientTCP.GetStream());
Listen = true;
listner = Listener();
}
startClient is called in this way.
startClient(txtAddr.Text, (int)int.Parse(txtPort.Text));
When I run the client setting host variable to the current machine name (the same the server retrieve trough Dns.GetHostName() I got this exception:
An invalid ip address was specified.
I tried using 127.0.0.1 and I got:
Connection could not be established. Persistent rejection of the target computer 127.0.0.1:5002
I tried with localhost and I got
An invalid ip address was specified
again. I tried with the IP address assigned to WiFi and I got again
Connection could not be established. Persistent rejection of the target computer 192.168.10.11:5002
I'm sure the computer network works since I'm using it for many other things including connecting to local TCP services and I'm sure both client and server code works since on a different PC I'm able to connect them setting localhost as client host variable value. Why I'm unable to use loopback connections in my code?
Where did I fail?
P.S. I allowed connection to server binary in Windows firewall rules, I also allowed outgoing connection for client binary also.
For anyone willing to inspect the server code here it is:
Server code
You are using the constructor with the "IPEndPoint" parameter. This constructor does not connect to the server automatically and you must call the "Connect" method before using the socket. That is why you are getting the error message "Operation not allowed on unconnected sockets". Also, you have provided a wrong IPEndPoint for client.
Please try this on client:
private void startClient(string host, int port)
{
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(host), port);
ClientTCP = new TcpClient();
ClientTCP.Connect(serverEndPoint);
Reader = new StreamReader(ClientTCP.GetStream());
Listen = true;
listner = Listener();
}
You may need some exception handling here, but it should work now.
UPDATE:
The ipHostInfo.AddressList may have more than one addresses and just one of them is what you wanted. It is not necessarily the first one. I specified this manually and it works:
//string hostname = Dns.GetHostName();
//IPHostEntry ipHostInfo = Dns.GetHostEntry("127.0.0.1");
//IPAddress ipAddress = ipHostInfo.AddressList[0];
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 5002);

How to stop and start relisten for client socket connection in C#

I am working on an ATM project (tcp/ip, C#). I have to click the start button in server application to start listening client. OInce client sends sign on request (connect), connection between server and client is established (up to this part I am done).
When sign of request comes from the client, I have to disconnect the connection and start listen for client again. The code for listening client is as below.
public bool startlisten()
{
byte[] buffer = new byte[4000];
try
{
//Creates one SocketPermission object for access restrictions
permission = new SocketPermission(
NetworkAccess.Accept, // Allowed to accept connections
TransportType.Tcp, // Defines transport types
"", // The IP addresses of local host
SocketPermission.AllPorts // Specifies all ports
);
// Listening Socket object
sListener = null;
//Ensures the code to have permission to access a Socket
permission.Demand();
// Resolves a host name to an IPHostEntry instance
IPHostEntry ipHost = Dns.GetHostEntry("");
int portnumber = int.Parse(ConfigurationManager.AppSettings.Get("port"));
// Creates a network endpoint
ipEndPoint = new IPEndPoint(IPAddress.Any, portnumber);
// Create one Socket object to listen the incoming connection
sListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Associates a Socket with a local endpoint
sListener.Bind(ipEndPoint);
// Places a Socket in a listening state and specifies the maximum
// Length of the pending connections queue
sListener.Listen(10);
//Begins an asynchronous operation to accept an attempt
AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
sListener.BeginAccept(aCallback, sListener);
}
catch (Exception exc) {
return true;
}
return true;
}
Please guide me how to disconnect from client socket and start listening again.
i have tried
//handler.Disconnect(false);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
sListener and handler are the Socket object.while accepting (acceptconnection) listener is copied to handler.

How to disconnect from one end point and then connect to another? - C#

I have two servers and a client. One server is on the same computer where the client is. I need to disconnect from the local server and connect to the remote one.
AutoResetEvent disconnectDone = new AutoResetEvent(false);
IPEndPoint localEndPoint = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0], PORT);
Socket socket;
// somewhere I initialize the socket and connect to the local end point
public void someButton_Click(object sender, EventArgs e)
{
string IP = someTextBox.Text;
if (socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
socket.BeginDisconnect(true, DisconnectCallback, socket);
disconnectDone.WaitOne();
}
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), PORT);
socket.BeginConnect(remoteEndPoint, ConnectCallback, socket);
}
private void DisconnectCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndDisconnect(AR);
disconnectDone.Set();
}
It freezes at the line with the WaitOne method because DisconnectCallback doesn't answer.
If in the BeginDisconnect method I change true to false then it "works". But further BeginConnect gives me an exception that the socket is still connected.
I really do not understand how all these disconnect things work. Or maybe I'm wrong with those thread methods (WaitOne and Set). Please help!

C# UDP socket app to listen to messages from various sockets

I have a system monitor app that needs to listen to messages from various UDP sockets on another machine. The other sockets continuously send heartbeats to this given IP/port.
This exception gets thrown when calling BeginReceiveFrom:
"A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied"
I shouldn't have to call connect because data is already getting sent to this ip endpoint. plus the data is coming from various sockets.
private Socket m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// bind socket
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
m_localEndPoint = new IPEndPoint(ipAddress, 19018);
m_socket.Bind(m_localEndPoint);
m_socket.BeginReceiveFrom(m_data,
m_nBytes,
MAX_READ_SIZE,
SocketFlags.None,
ref m_localEndPoint,
new AsyncCallback(OnReceive),
null);
}
private void OnReceive(IAsyncResult ar)
{
int nRead = m_socket.EndReceiveFrom(ar, ref m_localEndPoint);
}
I was able to get the desired behavior with the UdpClient class.
Your problem was you were binding to the IP assigned to you, you should bind to IP you want receive from - in your case:
m_socket.Bind(new IPEndPoint(IPAddress.Any, 12345));

Categories