473,387 Members | 1,435 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Strange UDP Socket problem

It's my understanding of UDP sockets that if there is a thread blocked on a
"recvFrom()" call and other thread sends a UDP packet to some address, that
if the machine on the other end isn't up, that the "recvFrom()" call should
just continue blocking. Right?

What I'm seeing is that when I send a packet to a particular address that is
not responding, my "recvFrom()" call throws an exception. I get "An
existing connection was forcibly closed by the remote host". It shouldn't
do that, right? UDP is connectionless, so if the machine on the other end
isn't running (well, I assume it's not running) it should just continue
blocking right?

Here's the basics of the code. I create the socket.
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
_socket.Bind(new IPEndPoint(IPAddress.Any, 1400) );

Then I spawn two threads, one for reading, one for sending:

_readThread = new Thread(new ThreadStart(read) );
_readThread.Start();

_sendThread = new Thread(new ThreadStart(send) );
_sendThread.Start();

The read thread just blocks on a "recvFrom()" until it gets data (or in this
case throws the above exception). The sending thread has a list of IPs it
needs to send requests to. It may or may not get a response to the request.

Why would I be getting a "connection closed" exception on a UDP socket?
What am I missing in my understanding of how UDP works?

Terry


Nov 15 '05 #1
5 11620
I suspect you would get the same response if you used one thread to send and
receive. That IP likely does exist and closed the connect, you justed
picked up the exception on the other thread because your sharing the socket
(at least it looks that way.) Even if you can't ping the ip, it could still
exist, just ICMP is being blocked. Try it to a local private ip that you
know for sure does not exist. You may just want to send and receive in same
thread on same socket. Add another thread or two (each doing send/receive)
on ephemeral ports if your looking to get more sends off while waiting for
receives.

--
William Stacey, MVP

"Terry" <ch**********@hotmail.com> wrote in message
news:e$*************@tk2msftngp13.phx.gbl...
It's my understanding of UDP sockets that if there is a thread blocked on a "recvFrom()" call and other thread sends a UDP packet to some address, that if the machine on the other end isn't up, that the "recvFrom()" call should just continue blocking. Right?

What I'm seeing is that when I send a packet to a particular address that is not responding, my "recvFrom()" call throws an exception. I get "An
existing connection was forcibly closed by the remote host". It shouldn't
do that, right? UDP is connectionless, so if the machine on the other end
isn't running (well, I assume it's not running) it should just continue
blocking right?

Here's the basics of the code. I create the socket.
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
_socket.Bind(new IPEndPoint(IPAddress.Any, 1400) );

Then I spawn two threads, one for reading, one for sending:

_readThread = new Thread(new ThreadStart(read) );
_readThread.Start();

_sendThread = new Thread(new ThreadStart(send) );
_sendThread.Start();

The read thread just blocks on a "recvFrom()" until it gets data (or in this case throws the above exception). The sending thread has a list of IPs it
needs to send requests to. It may or may not get a response to the request.
Why would I be getting a "connection closed" exception on a UDP socket?
What am I missing in my understanding of how UDP works?

Terry

Nov 15 '05 #2
I guess I was just expecting different behavior. I figured that if I send a
UDP packet to an IP that doesn't have anything at the other end that my
"recvFrom()" call would just block forever waiting for something to come
back.

Hmm. Maybe I can't do what I'm trying to do. I have a list of IP's that I
need to send an identical packet to and time the round-trip time. I thought
I could just have one thread just cycling through the IPs sending the
datagram, and having another thread to just read the responses as they come
in.

So, are you saying that I won't be able to do another "sendTo()" until the
response has been received or I get a WSAECONNRESET indicating there's
nothing at the other end?
"William Stacey" <st***********@mvps.org> wrote in message
news:#o**************@TK2MSFTNGP12.phx.gbl...
I suspect you would get the same response if you used one thread to send and receive. That IP likely does exist and closed the connect, you justed
picked up the exception on the other thread because your sharing the socket (at least it looks that way.) Even if you can't ping the ip, it could still exist, just ICMP is being blocked. Try it to a local private ip that you
know for sure does not exist. You may just want to send and receive in same thread on same socket. Add another thread or two (each doing send/receive) on ephemeral ports if your looking to get more sends off while waiting for
receives.

--
William Stacey, MVP

"Terry" <ch**********@hotmail.com> wrote in message
news:e$*************@tk2msftngp13.phx.gbl...
It's my understanding of UDP sockets that if there is a thread blocked on
a
"recvFrom()" call and other thread sends a UDP packet to some address, that
if the machine on the other end isn't up, that the "recvFrom()" call

should
just continue blocking. Right?

What I'm seeing is that when I send a packet to a particular address

that is
not responding, my "recvFrom()" call throws an exception. I get "An
existing connection was forcibly closed by the remote host". It

shouldn't do that, right? UDP is connectionless, so if the machine on the other end isn't running (well, I assume it's not running) it should just continue
blocking right?

Here's the basics of the code. I create the socket.
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
_socket.Bind(new IPEndPoint(IPAddress.Any, 1400) );

Then I spawn two threads, one for reading, one for sending:

_readThread = new Thread(new ThreadStart(read) );
_readThread.Start();

_sendThread = new Thread(new ThreadStart(send) );
_sendThread.Start();

The read thread just blocks on a "recvFrom()" until it gets data (or in

this
case throws the above exception). The sending thread has a list of IPs it needs to send requests to. It may or may not get a response to the

request.

Why would I be getting a "connection closed" exception on a UDP socket?
What am I missing in my understanding of how UDP works?

Terry


Nov 15 '05 #3
> I guess I was just expecting different behavior. I figured that if I send
a
UDP packet to an IP that doesn't have anything at the other end that my
"recvFrom()" call would just block forever waiting for something to come
back.
It should unless you set the receive timeout (which I would do). I am
guessing that a host by that IP does, infact, exist and it closed the
connect. Do you get the same behavior using an IP you know for sure does
not exist? If you don't set a timeout, it will wait forever unless it gets
closed (like yours) or get a reply.
Hmm. Maybe I can't do what I'm trying to do. I have a list of IP's that I need to send an identical packet to and time the round-trip time.
Sounds like ping? You have a udp server program listening on the other
side?
I could just have one thread just cycling through the IPs sending the
datagram, and having another thread to just read the responses as they come in.


AFAICT, that should work ok if your sharing the same UdpClient or socket.
As long as one thread does nothing but post sends and the other posts reads.
Again, not sure if socket exceptions will be thrown on the right thread or
in some random fashion. Not sure if this helps, buy I got this reply from a
ms poster awhile back:

"However for some of the user scenarios the UdpClient class can be used
without explicit synchronization.
Such as one thread could be doing read and other thread could be doing
send, fine.
Concurrent Reads are not supported on UdpClient though they are supported
on the socket level.
Concurrent Sends are supported as far as the remote address does not
change."

You could also show the code your using and I could test a few things.

hth

--
William Stacey, MVP
Nov 15 '05 #4
I did some testing on this and its does not have to do with the threads.
You get the same error sending and receiving to an IP that exists, but is
not listening on that port. If the IP does not exist then it blocks forever
or until timeout. Guess that makes sense. You don't get an error until you
actually try to read something. You can catch that exception and move on.
You know the IP is alive, but nothing is listening on that port or is forced
down. If you could not reach the IP at all, it would block waiting as you
never get any udp reply back to post an exception.
HTH

--
William Stacey, MVP

"Terry" <ch**********@hotmail.com> wrote in message
news:e#**************@tk2msftngp13.phx.gbl...
I guess I was just expecting different behavior. I figured that if I send a UDP packet to an IP that doesn't have anything at the other end that my
"recvFrom()" call would just block forever waiting for something to come
back.

Hmm. Maybe I can't do what I'm trying to do. I have a list of IP's that I need to send an identical packet to and time the round-trip time. I thought I could just have one thread just cycling through the IPs sending the
datagram, and having another thread to just read the responses as they come in.

So, are you saying that I won't be able to do another "sendTo()" until the
response has been received or I get a WSAECONNRESET indicating there's
nothing at the other end?
"William Stacey" <st***********@mvps.org> wrote in message
news:#o**************@TK2MSFTNGP12.phx.gbl...
I suspect you would get the same response if you used one thread to send and
receive. That IP likely does exist and closed the connect, you justed
picked up the exception on the other thread because your sharing the

socket
(at least it looks that way.) Even if you can't ping the ip, it could

still
exist, just ICMP is being blocked. Try it to a local private ip that you
know for sure does not exist. You may just want to send and receive in

same
thread on same socket. Add another thread or two (each doing

send/receive)
on ephemeral ports if your looking to get more sends off while waiting for receives.

--
William Stacey, MVP

"Terry" <ch**********@hotmail.com> wrote in message
news:e$*************@tk2msftngp13.phx.gbl...
It's my understanding of UDP sockets that if there is a thread blocked on
a
"recvFrom()" call and other thread sends a UDP packet to some address,

that
if the machine on the other end isn't up, that the "recvFrom()" call

should
just continue blocking. Right?

What I'm seeing is that when I send a packet to a particular address

that
is
not responding, my "recvFrom()" call throws an exception. I get "An
existing connection was forcibly closed by the remote host". It

shouldn't do that, right? UDP is connectionless, so if the machine on the other end isn't running (well, I assume it's not running) it should just continue blocking right?

Here's the basics of the code. I create the socket.
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
_socket.Bind(new IPEndPoint(IPAddress.Any, 1400) );

Then I spawn two threads, one for reading, one for sending:

_readThread = new Thread(new ThreadStart(read) );
_readThread.Start();

_sendThread = new Thread(new ThreadStart(send) );
_sendThread.Start();

The read thread just blocks on a "recvFrom()" until it gets data (or in this
case throws the above exception). The sending thread has a list of
IPs it needs to send requests to. It may or may not get a response to the

request.

Why would I be getting a "connection closed" exception on a UDP

socket? What am I missing in my understanding of how UDP works?

Terry



Nov 15 '05 #5
Well, for what it's worth, here's the code boiled down to a small console
example. I grabbed 9 IPs from my set and added a bogus IP for the 10th.
I'm not sure what was going on yesterday, but this works great (as
expected). I didn't realize that a WSAECONNRESET error was expected on a
udp socket if the other end is up, but not open on the specified port.

Here's the code - maybe it will be useful to someone else. I suppose you
could use it as a Half-Life server pinger. :-)

using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace TestUdpSendRecv
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
private static Socket _socket = null;

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
byte[] buffer = {0xFF, 0xFF, 0xFF, 0xFF,
(byte)'p', (byte)'i', (byte)'n', (byte)'g', 0x00};

IPEndPoint[] eps = {
new IPEndPoint(IPAddress.Parse("194.70.27.10"),27016),
new IPEndPoint(IPAddress.Parse("213.139.175.131"),2702 5),
new IPEndPoint(IPAddress.Parse("64.156.2.132"),27019),
new IPEndPoint(IPAddress.Parse("81.2.166.133"),27015),
new IPEndPoint(IPAddress.Parse("66.208.100.134"),27015 ),
new IPEndPoint(IPAddress.Parse("62.73.33.10"),27015),
new IPEndPoint(IPAddress.Parse("62.73.33.10"),27015),
new IPEndPoint(IPAddress.Parse("208.187.58.4"),27015),
new IPEndPoint(IPAddress.Parse("80.55.110.10"),27015), // Throws
exception
new IPEndPoint(IPAddress.Parse("10.0.0.199"),27015) // Invalid IP
};

_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
// Timeout after 3 seconds
_socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 3000);

// Create the receiving thread
Thread recvThread = new Thread(new ThreadStart(recv) );
recvThread.Name = "Receive Thread";
recvThread.Start();

int nBytesSent = 0;
for (int i=0; i<eps.Length; i++ )
{
Console.WriteLine("Sending to {0}", eps[i]);
nBytesSent = _socket.SendTo(buffer, eps[i]);
//Thread.Sleep(10); // Testing - try throttling
}

recvThread.Join();
_socket.Shutdown(SocketShutdown.Both);
_socket.Close();

Console.WriteLine("Press Enter to exit...");
Console.ReadLine();
}

private static void recv()
{
// Sleep for a bit - get "invalid option exception" if ReceiveFrom is
called before a send
Thread.Sleep(50);

byte[] buff = new byte[8192];
int nBytes = 1; // Init to '1' just to get into while loop
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0 );
EndPoint ep = (EndPoint)iep;

try
{
while (nBytes > 0)
{
try
{
nBytes = _socket.ReceiveFrom(buff, ref ep);
Console.WriteLine("{0} bytes from {1}", nBytes, ep);
}
catch (SocketException ex)
{
if (ex.ErrorCode != 10054 )
{
// Break out of not an 'expected' exception (WSAECONNRESET)
Console.WriteLine(ex.Message);
break;
}

Console.WriteLine("Caught exception \"{0}\"", ex.Message);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}

"William Stacey" <st***********@mvps.org> wrote in message
news:#L**************@tk2msftngp13.phx.gbl...
I guess I was just expecting different behavior. I figured that if I
send a
UDP packet to an IP that doesn't have anything at the other end that my
"recvFrom()" call would just block forever waiting for something to come
back.
It should unless you set the receive timeout (which I would do). I am
guessing that a host by that IP does, infact, exist and it closed the
connect. Do you get the same behavior using an IP you know for sure does
not exist? If you don't set a timeout, it will wait forever unless it

gets closed (like yours) or get a reply.
Hmm. Maybe I can't do what I'm trying to do. I have a list of IP's
that I
need to send an identical packet to and time the round-trip time.
Sounds like ping? You have a udp server program listening on the other
side?
> I could just have one thread just cycling through the IPs sending the
datagram, and having another thread to just read the responses as they

come
in.


AFAICT, that should work ok if your sharing the same UdpClient or socket.
As long as one thread does nothing but post sends and the other posts

reads. Again, not sure if socket exceptions will be thrown on the right thread or
in some random fashion. Not sure if this helps, buy I got this reply from a ms poster awhile back:

"However for some of the user scenarios the UdpClient class can be used
without explicit synchronization.
Such as one thread could be doing read and other thread could be doing
send, fine.
Concurrent Reads are not supported on UdpClient though they are supported
on the socket level.
Concurrent Sends are supported as far as the remote address does not
change."

You could also show the code your using and I could test a few things.

hth

--
William Stacey, MVP

Nov 15 '05 #6

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

Similar topics

4
by: Jane Austine | last post by:
Running Python 2.3 on Win XP It seems like socket is working interdependently with subprocesses of the process which created socket. ------------------------------------ #the server side >>>...
5
by: huy | last post by:
Hi, I'm using cherrypy to provide a user interface for users to start a linux server program eg. os.system("nohup myserver.py &"). The problem is that if I stop cherrypy server and restart, I...
0
by: Grzegorz Kaczor | last post by:
Hello all, I've got a VERY strange network problem with Win2k Server and .NET. I've got one central server (hub) getting raw binary data (files) from many locations. Both server and clients...
0
by: jack | last post by:
Situation - server having memory growth issues cut out all the code except this bit, where a client is constantly sending message and this just receives them, does nothing, and then receives...
8
by: Skink | last post by:
Hi, I'm preparing a python server that sends java classes and resources to custom java class loader. In order to make it faster I don't want to use URLClassLoader that uses HTTP protocol 1.0 and...
0
by: Grzegorz Kaczor | last post by:
Hello, I've got a VERY strange network problem with Win2k Server and .NET. I've got one central server (hub) getting raw binary data (files) from many locations. Both server and clients are...
1
by: liubojin | last post by:
Hi guys, I have got some strange system behaviors regarding i/o delays in socket in python, here's the details: I'm writing a web proxy like program that intercepts and redirects requests from...
6
by: White Spirit | last post by:
I have the following code to send a packet to a remote socket and receive a response in return: System.Net.Sockets.Socket locSocket = new System.Net.Sockets.Socket (AddressFamily.InterNetwork,...
8
by: FBM | last post by:
Hi there, I am puzzled with the behavior of my code.. I am working on a networking stuff, and debugging with eclipse (GNU gdb 6.6-debian).. The problem I am experiencing is the following: ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
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,...
0
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...
0
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...

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.