473,715 Members | 6,043 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(AddressF amily.InterNetw ork, SocketType.Dgra m,
ProtocolType.Ud p);
_socket.Bind(ne w IPEndPoint(IPAd dress.Any, 1400) );

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

_readThread = new Thread(new ThreadStart(rea d) );
_readThread.Sta rt();

_sendThread = new Thread(new ThreadStart(sen d) );
_sendThread.Sta rt();

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 11693
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**********@h otmail.com> wrote in message
news:e$******** *****@tk2msftng p13.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(AddressF amily.InterNetw ork, SocketType.Dgra m,
ProtocolType.Ud p);
_socket.Bind(ne w IPEndPoint(IPAd dress.Any, 1400) );

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

_readThread = new Thread(new ThreadStart(rea d) );
_readThread.Sta rt();

_sendThread = new Thread(new ThreadStart(sen d) );
_sendThread.Sta rt();

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******** ******@TK2MSFTN GP12.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**********@h otmail.com> wrote in message
news:e$******** *****@tk2msftng p13.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(AddressF amily.InterNetw ork, SocketType.Dgra m,
ProtocolType.Ud p);
_socket.Bind(ne w IPEndPoint(IPAd dress.Any, 1400) );

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

_readThread = new Thread(new ThreadStart(rea d) );
_readThread.Sta rt();

_sendThread = new Thread(new ThreadStart(sen d) );
_sendThread.Sta rt();

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**********@h otmail.com> wrote in message
news:e#******** ******@tk2msftn gp13.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******** ******@TK2MSFTN GP12.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**********@h otmail.com> wrote in message
news:e$******** *****@tk2msftng p13.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(AddressF amily.InterNetw ork, SocketType.Dgra m,
ProtocolType.Ud p);
_socket.Bind(ne w IPEndPoint(IPAd dress.Any, 1400) );

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

_readThread = new Thread(new ThreadStart(rea d) );
_readThread.Sta rt();

_sendThread = new Thread(new ThreadStart(sen d) );
_sendThread.Sta rt();

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.Threadin g;
using System.Net;
using System.Net.Sock ets;

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(IPAd dress.Parse("19 4.70.27.10"),27 016),
new IPEndPoint(IPAd dress.Parse("21 3.139.175.131") ,27025),
new IPEndPoint(IPAd dress.Parse("64 .156.2.132"),27 019),
new IPEndPoint(IPAd dress.Parse("81 .2.166.133"),27 015),
new IPEndPoint(IPAd dress.Parse("66 .208.100.134"), 27015),
new IPEndPoint(IPAd dress.Parse("62 .73.33.10"),270 15),
new IPEndPoint(IPAd dress.Parse("62 .73.33.10"),270 15),
new IPEndPoint(IPAd dress.Parse("20 8.187.58.4"),27 015),
new IPEndPoint(IPAd dress.Parse("80 .55.110.10"),27 015), // Throws
exception
new IPEndPoint(IPAd dress.Parse("10 .0.0.199"),2701 5) // Invalid IP
};

_socket = new Socket(AddressF amily.InterNetw ork, SocketType.Dgra m,
ProtocolType.Ud p);
// Timeout after 3 seconds
_socket.SetSock etOption(Socket OptionLevel.Soc ket,
SocketOptionNam e.ReceiveTimeou t, 3000);

// Create the receiving thread
Thread recvThread = new Thread(new ThreadStart(rec v) );
recvThread.Name = "Receive Thread";
recvThread.Star t();

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

recvThread.Join ();
_socket.Shutdow n(SocketShutdow n.Both);
_socket.Close() ;

Console.WriteLi ne("Press Enter to exit...");
Console.ReadLin e();
}

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(IPAd dress.Any, 0 );
EndPoint ep = (EndPoint)iep;

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

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

"William Stacey" <st***********@ mvps.org> wrote in message
news:#L******** ******@tk2msftn gp13.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
3366
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 >>> import socket >>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) >>> s.bind(('localhost',9000))
5
1582
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 get the "Address Already In Use" problem until I stop myserver.py. Can someone shed some light on why this happens ? Why would the socket be held up in the other process ? Thanks
0
1535
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 are written in C# The server is quite simple: two threads, one accepts new connections and decides whether the client is authenticated to send data or not, and the other thread serves already connected clients: performs a Socket.Select and then...
0
1222
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 again. I had stuck in a GC.Collect() and GC.WaitForFinalizers() call in the code so I could more easily watch the gen2 heap size and see if it was steady or not. But if I put it in one place, it would be steady, in another it would grow!!?? (see...
8
2008
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 for each class/resource creates own connection. Instead I'd like to use raw sockets with simple protocol: - class loader sends a line terminated with \n with resource to get - python server reads that line, gets the file and sends back an
0
1249
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 written in C# The server is quite simple: two threads, one accepts new connections and decides whether the client is authenticated to send data or not, and the other thread serves already connected clients: performs a Socket.Select and then gets...
1
1915
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 clients to my tomcat server, this proxy is written in python, and i'm starting a new thread to handle (redirect) the requests whenever there's a new client connected to my proxy. Each handler thread will read the http request line from the client...
6
4654
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, SocketType.Raw, ProtocolType.Tcp); System.Net.Sockets.Socket remSocket = new System.Net.Sockets.Socket (AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Tcp); locSocket.Bind (new IPEndPoint (locIP, 2126)); /*
8
3215
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: Whenever I declare the sockaddr_in structure inside the main, the debugger crashes at line X*, not being able to access argv parameters (see code below). It is very strange.. by only being there, sockaddr_in does not allow me to question argc...
0
8821
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8718
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
9340
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
9196
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...
0
9047
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7973
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 project—planning, coding, testing, and deployment—without 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
6646
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5967
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
3
2118
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.