Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

c# - Why would a socket in use exception be thrown for TcpClient(IPEndPoint) but not TcpClient(String, Int32)?

Why would a socket in use exception be thrown for TcpClient(IPEndPoint) but not TcpClient(String, Int32)?

I have in my code a listener that I use with (ip is ::1, port is 12345)

listener = new TcpListener(ip, port); //create listener
listener.Start(); //start listener
//now code will wait at the while loop until someone connects.
while (listener.Pending()) { System.Threading.Thread.Sleep(1000); } //check for pending connections every second.
client = listener.AcceptTcpClient(); //when incoming connection is found accept it.

Note that code is inside a Task listenerTask = Task.Run(() =>{});

in another task I have the following

//client = new TcpClient(new IPEndPoint(ip, port)); //does not work
client = new TcpClient("localhost", port); //localhost resolves to ::1

So what's the deal? What is the difference? Am I wrong about localhost resolving to ::1? If it doesn't resolve to that then how can my program echo back on itself?

I will try to get more information in the meantime.

Exception details:

System.Net.Sockets.SocketException was unhandled
ErrorCode=10048
HResult=-2147467259
Message=Only one usage of each socket address (protocol/network address/port) is normally permitted
NativeErrorCode=10048
Source=System
StackTrace:
     at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
     at System.Net.Sockets.Socket.Bind(EndPoint localEP)
     at System.Net.Sockets.TcpClient..ctor(IPEndPoint localEP)
     at ConsoleApplication1.Program.Connector(IPAddress[] ips, Int32 port)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My code of:

client = new TcpClient(new IPEndPoint(ip, port)); 

Binds the local port with the local IP address for later use.

Once knowing this I was able to change my code to the following and it works how I intended it to:

client = new TcpClient(new IPEndPoint(localIp, localPort)); //sets up how we are going to be connecting.
client.Connect(remoteIp, remotePort); //does the real connecting.

Source: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient%28v=vs.110%29.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...