473,748 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Unexplainable Error "One Usage per IP Socket"

Using the TcpListener and TcpClient I created a program that just sends and
receives a short string - over and over again. The program is fine until it
gets to around 1500 to 1800 messages. At that time, I get a SocketException
with the message "Only one usage of each socket address (protocol/network
address/port) is normally permitted". This happen if you use localhost or
between two distinct computers. And, for a period of time after the error
(~1 - 5 minutes), the program errors out on the first Client socket
connection.

The message is bogus since its works for the first 1000 or so times. It's
something else and the best it can do is this error. At first I thought is
was not destructing the connection but I explicitly called Dispose and also
garbage collected after every 500 connections - but that did not work.

I am using VS 2003 / .NET Framework 1.1. But, the same thing happens with
VS.NET and .NET FW 1.0. I searched google and the knowledge base but nothing
points to this error that was helpful.

Any advice or fix would be appreciated. The stripped down code is below.

Thanks in advance,
// code for NetStreamtest
using System;
using System.Net.Sock ets;
using System.Net;
using System.Threadin g;
using System.Security .Permissions;

/*************** *************** *************** *************** ***
*
*
C:\Temp\vs.net\ NetStreamTest\b in\Debug>netstr eamtest localhost
Connecting to host->127.0.0.1
Number is 0 9/20/2003 3:19:15 PM
Number is 200 9/20/2003 3:19:15 PM
Number is 400 9/20/2003 3:19:16 PM
Number is 600 9/20/2003 3:19:16 PM
Number is 800 9/20/2003 3:19:17 PM
Number is 1000 9/20/2003 3:19:17 PM
Number is 1200 9/20/2003 3:19:18 PM
Number is 1400 9/20/2003 3:19:18 PM
Number is 1600 9/20/2003 3:19:19 PM
Number is 1800 9/20/2003 3:19:19 PM
CLIENT:Exceptio n->System.Net.Soc kets.SocketExce ption: Only one usage of each
soc
ket address (protocol/network address/port) is normally permitted
at System.Net.Sock ets.TcpClient.C onnect(String hostname, Int32 port)
at System.Net.Sock ets.TcpClient.. ctor(String hostname, Int32 port)
at NetStreamTest.T CPCommunication .GoClient(Strin g message) in
c:\temp\vs.net\
netstreamtest\n etstreamtest.cs :line 109
Main:Exception at i =1961: System.Net.Sock ets.SocketExcep tion: Only one
usage of
each socket address (protocol/network address/port) is normally permitted
at NetStreamTest.T CPCommunication .GoClient(Strin g message) in
c:\temp\vs.net\
netstreamtest\n etstreamtest.cs :line 123
at NetStreamTest.N etStreamTestMai n.Main(String[] args) in
c:\temp\vs.net\ nets
treamtest\netst reamtest.cs:lin e 35

Unhandled Exception: System.Net.Sock ets.SocketExcep tion: Only one usage of
each
socket address (protocol/network address/port) is normally permitted
at NetStreamTest.N etStreamTestMai n.Main(String[] args) in
c:\temp\vs.net\ nets
treamtest\netst reamtest.cs:lin e 45
*************** *************** *************** *************** ****/

namespace NetStreamTest
{
class NetStreamTestMa in
{
[STAThread]
static void Main(string[] args)
{
TCPCommunicatio n tcc = null;
Thread th = null;
int i=0;

string s = "localhost" ;

if( args.Length > 0 )
if( args[0].Length > 0 )
s = args[0];

try
{
tcc = new TCPCommunicatio n(s);
th = new Thread(new ThreadStart( tcc.GoServer ));
th.Start();

Thread.Sleep( 2 ); // wait for server to start...

for(i=0; i < 4000; i++) // it will fault before this is done
{
tcc.GoClient(i. ToString() + ":THIS IS A TEST ");
if( i % 200 == 0 ) // just so there is status
Console.Out.Wri teLine("Number is " + i.ToString() + " " +
DateTime.Now.To String() );
}

Thread.Sleep(2) ; // hopefully to clear out messages
}
catch (Exception e)
{
Console.WriteLi ne("Main:Except ion at i ={0}: {1}", i ,e);
throw( e ); // re-throw the exception to end
}
finally
{
if( th != null )
th.Abort();
}
}
}

class TCPCommunicatio n
{
private Int32 port = 812;
private bool DisplayItClient = false;
private bool DisplayItServer = false;
private string ServerName;

public TCPCommunicatio n( string ServerName )
{
this.ServerName = ServerName;
}
[SocketPermissio n(SecurityActio n.Demand, Unrestricted=tr ue)]
public void GoServer()
{
bool notDone = true;
IPHostEntry heserver = Dns.Resolve(thi s.ServerName);
Console.Out.Wri teLine("Connect ing to host->" +
heserver.Addres sList[0].ToString() );

TcpListener server = new TcpListener( heserver.Addres sList[0], port);
server.Start();

if( this.DisplayItS erver )
Console.Out.Wri teLine("In GoServer thread");

while( notDone )
{
try
{
Socket s = server.AcceptSo cket();
NetworkStream stream = new NetworkStream( s );

string response = this.ReadMessag e(stream, this.DisplayItS erver);
this.WriteMessa ge(response+" ***** GOT IT! ***** ", stream ,
this.DisplayItS erver);

if( this.DisplayItS erver )
Console.Out.Wri teLine("SERVER: response = " + response);
}
catch (Exception e)
{
Console.WriteLi ne("SERVER:Exce ption-> {0}", e);
notDone = false;
}
}

server.Stop();
}

public void GoClient(string message )
{
try
{
if( this.DisplayItC lient )
Console.Out.Wri teLine("CLIENT: Msg"+message);

TcpClient client = new TcpClient(this. ServerName, port);
NetworkStream stream = client.GetStrea m();
this.WriteMessa ge(message,stre am,this.Display ItClient);

string response = this.ReadMessag e(stream,this.D isplayItClient) ;
if( this.DisplayItC lient )
Console.Out.Wri teLine("respons e = "+response) ;

// Close everything.
client.Close();
}
catch (Exception e)
{
Console.WriteLi ne("CLIENT:Exce ption->{0}", e);
throw( e );
}

}
void WriteMessage( string message, NetworkStream ns, bool log )
{
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Enc oding.ASCII.Get Bytes(message);
// Send the message to the connected TcpServer.
ns.Write(data, 0, data.Length);

if( log )
Console.WriteLi ne("Sent: {0}", message);
}

string ReadMessage( NetworkStream ns, bool log )
{
// Buffer to store the response bytes.
Byte [] data = new Byte[512];

// String to store the response ASCII representation
String responseData = String.Empty;

// Read the first batch of the TcpServer response bytes.
Int32 bytes = ns.Read(data, 0, data.Length);
responseData = System.Text.Enc oding.ASCII.Get String(data, 0, bytes);

if( log )
Console.WriteLi ne("Sent: {0}", responseData);

return responseData;
}

}
}
Nov 15 '05 #1
8 21911
Hi Grant,

Thanks for posting. Currently I am conducting research on your program. I
will get back to you as soon as possible.

Have a nice day!

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #2
Hi Grant,

I think the problem is that you have opened too many sockets on the server
side without closing them.

On my machine, I can reach around 3900 before the exception pops up. After
adding one line, the program can run continuously:

s.Close();

I put this line in your GoServer() method to close the Socket s. You may
also close the NetworkStream by calling stream.Close(), and call
s.ShutDown() method first to ensure all data is sent or received.

I hope this helps.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #3
Yes and no. It did solve the initial problem. The changed loop looks like.

....

while( notDone )
{
try

{
Socket s = server.AcceptSo cket();
NetworkStream stream = new NetworkStream( s );
string response = this.ReadMessag e(stream, this.DisplayItS erver);
this.WriteMessa ge(response+" ***** GOT IT! ***** ", stream ,
this.DisplayItS erver);
if( this.DisplayItS erver )
Console.Out.Wri teLine("SERVER: response = " + response);
s.Close();
} ...

That worked fine but at around 28000 interactions, the same message cropped
up.

Number is 28000 10/20/2003 8:39:42 AM
Number is 28200 10/20/2003 8:39:43 AM
Number is 28400 10/20/2003 8:39:43 AM
Number is 28600 10/20/2003 8:39:44 AM
CLIENT:Exceptio n->System.Net.Soc kets.SocketExce ption: Only one usage of each
soc
ket address (protocol/network address/port) is normally permitted
at System.Net.Sock ets.TcpClient.C onnect(String hostname, Int32 port)
at System.Net.Sock ets.TcpClient.. ctor(String hostname, Int32 port)
at NetStreamTest.T CPCommunication .GoClient(Strin g message) in
c:\temp\vs.net\
netstreamtest\n etstreamtest.cs :line 145
Main:Exception at i =28613: System.Net.Sock ets.SocketExcep tion: Only one
usage o
f each socket address (protocol/network address/port) is normally permitted
at NetStreamTest.T CPCommunication .GoClient(Strin g message) in
c:\temp\vs.net\
netstreamtest\n etstreamtest.cs :line 159
at NetStreamTest.N etStreamTestMai n.Main(String[] args) in
c:\temp\vs.net\ nets
treamtest\netst reamtest.cs:lin e 69

"Felix Wang" <v-*****@online.mi crosoft.com> wrote in message
news:NR******** ******@cpmsftng xa06.phx.gbl...
Hi Grant,

I think the problem is that you have opened too many sockets on the server
side without closing them.

On my machine, I can reach around 3900 before the exception pops up. After
adding one line, the program can run continuously:

s.Close();

I put this line in your GoServer() method to close the Socket s. You may
also close the NetworkStream by calling stream.Close(), and call
s.ShutDown() method first to ensure all data is sent or received.

I hope this helps.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #4
Hi Grant,

Thanks for your reply.

The same program can run to 70000 without any exception on my machine. I
did not continue because it took too long and made my computer become slow.
If you open a command line interface and input the "netstat" command, you
will see how many TCP connections are active.

I think that everything has a limitation. If you could let us know what
goal you are trying to achieve, maybe we can be more helpful to you on this
issue.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #5
Hi Grant,

Let me elaborate a little bit more on this issue.

I think that every operating system has its limits. On my Windows 2003
Server, I was able to loop for more than 70000 times. However, the CPU
utilization keeps at 100%. When we close the session by calling "Close()",
the connection is not closed immediately. If we use "NetStat" to view the
TCP states, we can see a lot of connections have the status as "TIME_WAIT" .
On your machine, I guess that 28000 loops is too many for the system.

I still think that If you could let us know what you are trying to achieve,
we may provide you with some workarounds.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #6
Hi Grant,

I have found some additional information on the "TIME_WAIT" status for you:

Problem: Netstat shows lots of sockets in the TIME_WAIT state. What's
wrong?
Solution: Nothing's wrong. TIME_WAIT is absolutely normal. If you go
through the state-transition diagram above, you see that every socket that
gets closed normally goes through this state after it's closed. The
TIME_WAIT state is a safety mechanism, to catch stray packets for that
connection after the connection is "officially " closed. Since the maximum
time that such stray packets can exist is 2 times the "maximum segment
lifetime" (the time for a packet to go from your machine to the remote peer
and for the response to come back), the TIME_WAIT state lasts for 2 * MSL.
The only tricky bit is, there is no easy way to estimate MSL on the fly, so
stacks traditionally hard-code a value for it, from 15 to 60 seconds. Thus,
TIME_WAIT usually lasts 30-120 seconds.

I think that when we run the program, there will be too many sockets enter
into the "TIME_WAIT" state and as a result, the system refuses further
connection. For a previous post discussing a similar issue, you may visit
the following site:

http://groups.google.com/groups?hl=e...readm=OUreRodj
DHA.2364%40TK2M SFTNGP11.phx.gb l&rnum=10&pre v=/groups%3Fhl%3De n%26lr%3D%26ie%
3DUTF-8%26oe%3DUTF-8%26q%3D%2522On ly%2Bone%2Busag e%2Bof%2Beach%2 Bsocket%2Bad
dress%2522%2BSo cketException

I hope the information is useful to you.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #7
My understanding now is that after a certain number of messages going back
and forth, the server socket is overwhelmed and spews out the misleading
error message. This makes sense expect I'd prefer to have a error message
that is not misleading. But, if you goal is to provide a high
speed/throughput interface, how do you avoid such a problem?

As suggestions would be appreciated.
Grant
"Grant Richard" <dg**********@h otmail.com> wrote in message
news:Oc******** ******@TK2MSFTN GP11.phx.gbl...
Yes and no. It did solve the initial problem. The changed loop looks like.
....

while( notDone )
{
try

{
Socket s = server.AcceptSo cket();
NetworkStream stream = new NetworkStream( s );
string response = this.ReadMessag e(stream, this.DisplayItS erver);
this.WriteMessa ge(response+" ***** GOT IT! ***** ", stream ,
this.DisplayItS erver);
if( this.DisplayItS erver )
Console.Out.Wri teLine("SERVER: response = " + response);
s.Close();
} ...

That worked fine but at around 28000 interactions, the same message cropped up.

Number is 28000 10/20/2003 8:39:42 AM
Number is 28200 10/20/2003 8:39:43 AM
Number is 28400 10/20/2003 8:39:43 AM
Number is 28600 10/20/2003 8:39:44 AM
CLIENT:Exceptio n->System.Net.Soc kets.SocketExce ption: Only one usage of each soc
ket address (protocol/network address/port) is normally permitted
at System.Net.Sock ets.TcpClient.C onnect(String hostname, Int32 port)
at System.Net.Sock ets.TcpClient.. ctor(String hostname, Int32 port)
at NetStreamTest.T CPCommunication .GoClient(Strin g message) in
c:\temp\vs.net\
netstreamtest\n etstreamtest.cs :line 145
Main:Exception at i =28613: System.Net.Sock ets.SocketExcep tion: Only one
usage o
f each socket address (protocol/network address/port) is normally permitted at NetStreamTest.T CPCommunication .GoClient(Strin g message) in
c:\temp\vs.net\
netstreamtest\n etstreamtest.cs :line 159
at NetStreamTest.N etStreamTestMai n.Main(String[] args) in
c:\temp\vs.net\ nets
treamtest\netst reamtest.cs:lin e 69

"Felix Wang" <v-*****@online.mi crosoft.com> wrote in message
news:NR******** ******@cpmsftng xa06.phx.gbl...
Hi Grant,

I think the problem is that you have opened too many sockets on the server side without closing them.

On my machine, I can reach around 3900 before the exception pops up. After adding one line, the program can run continuously:

s.Close();

I put this line in your GoServer() method to close the Socket s. You may
also close the NetworkStream by calling stream.Close(), and call
s.ShutDown() method first to ensure all data is sent or received.

I hope this helps.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.


Nov 15 '05 #8
Hi Grant,

Thanks for your feedback. You new question is quite difficult to answer.
Here are two facts:

1. On my Windows 2003 Server with 512MB RAM and 600MHZ CPU, the program can
run continuously.
2. On my Windows XP Pro with 256MB RAM and 733MHZ CPU, the program stops at
around 9800 loops.

Theoretically, there seems to be no problem with the program itself. It is
some other factors that matters. As general rules, the server should have a
good operating system, a powerful CPU, sufficient memory and so on.
Sometimes we even use round-robin clustering to further enhance the service
availibility and performance.

Probably we can try adjusing the time_wait delay
(HKEY_LOCAL_MAC HINE\SYSTEM\Cur rentControlSet\ Services\Tcpip\ Parameters\TcpT i
medWaitDelay). But this can have detrimental effects as well.

I hope this makes sense to you.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
3192
by: Paulo da Silva | last post by:
How are those "files" of type "socket", whose name begins with "=", created? How can I create them with python? Thanks.
2
4705
by: akbarhome | last post by:
Hi, I am following this tutorial https://www14.software.ibm.com/webapp/iwm/web/preLogin.do?source=dw-linux-pysocks&S_TACT=105AGX59&S_CMP=GR&ca=dgr-lnxw07PythonSockets ( free reg. req. ) The article told me to do this: $ python Python 2.4 (#1, Feb 20 2005, 11:25:45)
1
16455
by: Dr. J | last post by:
I have an application that opens a socket and connects to another application listening over a port. The problem I am encountering is that when the listening application is closed my application cannot detect it to take appropriate action. I am using "Connected" property of the Socket class, but it seems this property does not reflect the true state of the socket connection. Here is the code snippet. Basically, I am checking the...
0
1089
by: Sherry | last post by:
We are using the sample code "AsynchronousClient" from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconnon-blockingclientsocketexample.asp. It works for the wired (ethernet) connection. While the laptop is in wireless environment, the laptop get exception: "System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it at...
4
3355
by: Niron kag | last post by:
Hi, I have a windows service, which is currently installed, on my local computer. The problem is that when I look at the task manager, I see that the “Mem Usage”, become bigger and bigger. Has someone any idea why this happens? Anyway to solve this problem I thought to stop the service and start it programmatically when it’s “Mem Usage” is too big. Is it possible?
1
2082
by: shonclark | last post by:
"Hi there, I am having a bit of a headache trying to get the following coding to work. What I am trying to accomplish is turn around totals between and open date and resolution date. My coding works fine if the fields are filled in, but how do I get the blank data set to zero so that I am not getting and error message? Will using the Nz function eliminate this problem? See Below.... This is the field from my query... TimeElapsed:...
4
2054
by: wswilson | last post by:
Here is my code: listing = {'id': , 'name': } I need to output: id name a Joe b Jane c Bob
7
1842
by: twang090 | last post by:
I find in other team member's project, they are referencing a type in following format " public static global::ErrorReport.Description Description = new global::ErrorReport.Description(); " I do not understand the usage of "global" here, could anyone please clarify its usage and what benift of using that. Thanks in advance.
36
2659
by: mdh | last post by:
May I ask the group this somewhat non-focused question....having now seen "continue" used in some of the solutions I have worked on. ( Ex 7-4 solution by Tondo and Gimpel comes to mind) Is there a good principle/s for the good usage of "continue"...or...do any of the regular/irregular contributors have a "favorite" way in which it is particularly useful. Thanks as usual.
0
8979
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8818
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9522
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9355
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9307
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8234
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
3296
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2773
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2203
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.