Reputation: 73
I am trying to use a TcpListener. Every time I try to start the listener I get the error that the Address is already in use. I have looked at netstat and cant see anything on that endpoint(IP Address, Port).
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(ip, 58000);
listener.Start();
}
}
When I run that I the error every time.
Upvotes: 1
Views: 430
Reputation: 4883
You have for sure another process(most probably the same you are trying to run) running in background so you cannot open the port. Try to open and and ensure to close the connections:
public static void Main()
{
TcpListener server=null;
try
{
Int32 port = 58000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// DO ALL YOUR WORK
}
catch(SocketException e)
{
Console.WriteLine(e.ToString());
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
Upvotes: 1
Reputation: 13146
The error is pretty clear that another process (it's probably because of unfinisted exe of your program) bind the same port which you want to listen. Try to listen different port and see the case;
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(ip, 58001);
listener.Start();
Also, I strongly suggest you to use TcpView to inspect allocated ports.
Upvotes: 1