Why does sending via a UdpClient cause subsequent receiving to fail? - c#

I'm trying to create a UDP server which can send messages to all the clients that send messages to it. The real situation is a little more complex, but it's simplest to imagine it as a chat server: everyone who has sent a message before receives all the messages that are sent by other clients.
All of this is done via UdpClient, in separate processes. (All network connections are within the same system though, so I don't think the unreliability of UDP is an issue here.)
The server code is a loop like this (full code later):
var udpClient = new UdpClient(9001);
while (true)
{
var packet = await udpClient.ReceiveAsync();
// Send to clients who've previously sent messages here
}
The client code is simple too - again, this is slightly abbreviated, but full code later:
var client = new UdpClient();
client.Connect("127.0.0.1", 9001);
await client.SendAsync(Encoding.UTF8.GetBytes("Hello"));
await Task.Delay(TimeSpan.FromSeconds(15));
await client.SendAsync(Encoding.UTF8.GetBytes("Goodbye"));
client.Close();
This all works fine until one of the clients closes its UdpClient (or the process exits).
The next time another client sends a message, the server tries to propagate that to the now-closed original client. The SendAsync call for that doesn't fail - but then when the server loops back to ReceiveAsync, that fails with an exception, and I haven't found a way to recover.
If I never send a message to the client that's disconnected, I never see the problem. Based on that I've also created a "fails immediately" repro which just sends to an endpoint assumed not to be listening, and then tries to receive. This fails with the same exception.
Exception:
System.Net.Sockets.SocketException (10054): An existing connection was forcibly closed by the remote host.
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.CreateException(SocketError error, Boolean forAsyncThrow)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ReceiveFromAsync(Socket socket, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.ReceiveFromAsync(Memory`1 buffer, SocketFlags socketFlags, EndPoint remoteEndPoint, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.ReceiveFromAsync(ArraySegment`1 buffer, SocketFlags socketFlags, EndPoint remoteEndPoint)
at System.Net.Sockets.UdpClient.ReceiveAsync()
at Program.<Main>$(String[] args) in [...]
Environment:
Windows 11, x64
.NET 6
Is this expected behaviour? Am I using UdpClient incorrectly on the server side? I'm fine with clients not receiving messages after they've closed their UdpClient (that's to be expected), and in the "full" application I'll tidy up my internal state to keep track of "active" clients (who have sent packets recently) but I don't want one client closing a UdpClient to bring down the whole server. Run the server in one console, and the client in another. Once the client has finished once, run it again (so that it tries to send to the now-defunct original client).
The default .NET 6 console app project template is fine for all projects.
Repro code
The simplest example comes first - but if you want to run a server and client, they're shown afterwards.
Deliberately broken server (fails immediately)
Based on the assumption that it really is the sending that's causing the problem, this is easy to reproduce in just a few lines:
using System.Net;
using System.Net.Sockets;
var badEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12346);
var udpClient = new UdpClient(12345);
await udpClient.SendAsync(new byte[10], badEndpoint);
await udpClient.ReceiveAsync();
Server
using System.Net;
using System.Net.Sockets;
using System.Text;
var udpClient = new UdpClient(9001);
var endpoints = new HashSet<IPEndPoint>();
try
{
while (true)
{
Log($"{DateTime.UtcNow:HH:mm:ss.fff}: Waiting to receive packet");
var packet = await udpClient.ReceiveAsync();
var buffer = packet.Buffer;
var clientEndpoint = packet.RemoteEndPoint;
endpoints.Add(clientEndpoint);
Log($"Received {buffer.Length} bytes from {clientEndpoint}: {Encoding.UTF8.GetString(buffer)}");
foreach (var otherEndpoint in endpoints)
{
if (!otherEndpoint.Equals(clientEndpoint))
{
await udpClient.SendAsync(buffer, otherEndpoint);
}
}
}
}
catch (Exception e)
{
Log($"Failed: {e}");
}
void Log(string message) =>
Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss.fff}: {message}");
Client
(I previously had a loop actually receiving the packets sent by the server, but that doesn't seem to make any difference, so I've removed it for simplicity.)
using System.Net.Sockets;
using System.Text;
Guid clientId = Guid.NewGuid();
var client = new UdpClient();
Log("Connecting UdpClient");
client.Connect("127.0.0.1", 9001);
await client.SendAsync(Encoding.UTF8.GetBytes($"Hello from {clientId}"));
await Task.Delay(TimeSpan.FromSeconds(15));
await client.SendAsync(Encoding.UTF8.GetBytes($"Goodbye from {clientId}"));
client.Close();
Log("UdpClient closed");
void Log(string message) =>
Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss.fff}: {message}");

As you may be aware, if a host receives a packet for a UDP port that is not currently bound, it may send back an ICMP "Port Unreachable" message. Whether or not it does this is dependent on the firewall, private/public settings, etc. On localhost, however, it will pretty much always send this packet back.
In your server code, you are calling SendAsync to old clients, which prompts these "port unreachable" messages.
Now, on Windows (and only on Windows), by default, a received ICMP Port Unreachable message will close the UDP socket that sent it; hence, the next time you try to receive on the socket, it will throw an exception because the socket has been closed by the OS.
Obviously, this causes a headache in the multi-client, single-server socket set-up you have here, but luckily there is a fix:
You need to utilise the not-often-required SIO_UDP_CONNRESET Winsock control code, which turns off this built-in behaviour of automatically closing the socket.
I don't believe this ioctl code is available in the dotnet IoControlCodes type, but you can define it yourself. If you put the following code at the top of your server repro, the error no longer gets raised.
const uint IOC_IN = 0x80000000U;
const uint IOC_VENDOR = 0x18000000U;
/// <summary>
/// Controls whether UDP PORT_UNREACHABLE messages are reported.
/// </summary>
const int SIO_UDP_CONNRESET = unchecked((int)(IOC_IN | IOC_VENDOR | 12));
var udpClient = new UdpClient(9001);
udpClient.Client.IOControl(SIO_UDP_CONNRESET, new byte[] { 0x00 }, null);
Note that this ioctl code is only supported on Windows (XP and later), not on Linux, since it is provided by the Winsock extensions. Of course, since the described behavior is only the default behavior on Windows, this omission is not a major loss. If you are attempting to create a cross-platform library, you should cordon this off as Windows-specific code.

As a result of other peoples work inhere, I made a little udpSocket creation code, that will handle the if windows/if not logic incapsulated:
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
public static class UdpSocketUtils
{
public static Socket CreateUdpSocket(IPEndPoint localEndpoint)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
socket.Bind(localEndpoint);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// Due to this issue: https://stackoverflow.com/questions/74327225/why-does-sending-via-a-udpclient-cause-subsequent-receiving-to-fail
// .. the following needs to be done on windows
const uint IOC_IN = 0x80000000U;
const uint IOC_VENDOR = 0x18000000U;
const int SIO_UDP_CONNRESET = unchecked((int)(IOC_IN | IOC_VENDOR | 12));
socket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0x00 }, null);
}
return socket;
}
}

Related

C# .Net 10054 UDP Exception? Cause, fix? [duplicate]

I need to obtain UDP datagram from Asynchronous Socket Server but an exception occurred in my application :
Problem appear there :
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
The full source code:
class Program
{
static void Main(string[] args)
{
const int PORT = 30485;
IPAddress IP;
IPAddress.TryParse("92.56.23.87", out IP);
// This constructor arbitrarily assigns the local port number.
UdpClient udpClient = new UdpClient(PORT);
Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try
{
udpClient.Connect("92.56.23.87", PORT);
if (udpClient.Client.Connected)
Console.WriteLine("Connected.");
// Sends a message to the host to which you have connected.
Byte[] sendBytes = Encoding.ASCII.GetBytes("CONNECT");
udpClient.Send(sendBytes, sendBytes.Length);
//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IP, PORT);
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
// Uses the IPEndPoint object to determine which of these two hosts responded.
Console.WriteLine("This is the message you received " + returnData.ToString());
Console.WriteLine("This message was sent from " + RemoteIpEndPoint.Address.ToString() + " on their port number " + RemoteIpEndPoint.Port.ToString());
udpClient.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
Exception:
Connected.
System.Net.Sockets.SocketException (0x80004005): An existing connection
was forcibly closed by the remote host at System.Net.Sockets.Socket.ReceiveFrom(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, EndPoint& remoteEP) at ystem.Net.Sockets.UdpClient.Receive(IPEndPoint& remoteEP) at ConsoleApplication7.Program.Main(String[] args) in c:\users\user\documents\visual studio 2010\Projects\ConsoleApplication7\ConsoleApplication7\Program.cs
What can be the problem?
To provide more information, i bought the private socks connection on this page: http://rapidsocks.com/
this services give me a list of IP and port who in really is not a proxy .. just a connection that give me a proxyIP:proxyPort from a pool on server in response...
How to get that answer with proxyIP:proxyPort from the server?
In UDP land, one way this can occur is when you send a UDP packet to a host, and the remote host doesn't have a listener on that port, and bounces an ICMP host unreachable message in response.
In plain English, what this exception tells you that no process is listening on the far-end on that port.
Update: You should be able to avoid that behavior with the following code:
var udpClient = new UdpClient();
uint IOC_IN = 0x80000000;
uint IOC_VENDOR = 0x18000000;
uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
udpClient.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
Microsoft Article 263823 said this on the subject: [hard to find as of 2019]
SYMPTOMS
In Windows 2000, a User Datagram Protocol (UDP) program may
not work and may generate a WSAECONNRESET response.
CAUSE
If sending a datagram using the sendto function results in an
"ICMP port unreachable" response and the select function is set for
readfds, the program returns 1 and the subsequent call to the recvfrom
function does not work with a WSAECONNRESET (10054) error response. In
Microsoft Windows NT 4.0, this situation causes the select function to
block or time out.
RESOLUTION
A new sockets IOCTL called "SIO_UDP_CONNRESET" has been
introduced in Windows 2000. When this IOCTL is used, the program must
be rewritten specifically for Windows 2000 to obtain the original
Windows NT 4.0 behavior. Windows NT 4.0, Microsoft Windows 95, and
Microsoft Windows 98 have no support for this new IOCTL. In addition
to rewriting your application, you will need the hotfix referenced
further down in this article.
This really is a generic error message that could mean anything. Time to get the low level network traffic sniffers to filter what is actually going wrong. Adding extra error handling try catch blocks on the server with decent logging is always a great place to start.

Sending UDP messages works, receiving not - C# on Unity3d

Hello,
I am trying to set up a UDP connection in Unity3d and it has been giving me some headace the past days:
The Unity script I am running is supposed to receive and maybe in the future send UDP messages.
Next to Unity I am using Wireshark to track the packets and PacketSender to generate and receive UDP messages.
The source of the messages is a PLC which sends a package every second, containing two floats (8 bytes) for testing.
The PLC IP is 192.168.0.1 and it is connected directly via Ethernet to the Laptop running Unity. (no switch, no router)
My Ethernet Port has the IP 192.168.0.41, and the messages are coming in via Port 8052.
What I can see in Wireshark via :
Packages arriving from the PLC to Unity
Packages leaving from Unity to the PLC
The packages have the expected structure
What I can see / do in PacketSender:
packages arriving from the PLC (via Port 8052)
send messages to the PLC that are visible in Wireshark
by receiving the packages here it should also be safe to say that the firewall port window works.
I can NOT receive packages with PacketSender if I already started my Unity-receive script...
... which should be an indicator, that the Unity UDP socket is up and running, hopefully swallowing messages.
If I call netstat -aon I can see the Unity UPD Process at the expected Port & IP;
0.0.0.0:8052 or 192.168.0.41:8052, depending on how it is created. Also I can see that no other process is using the same port.
But what does not work is to actually receive and use the data in my Unity script.
What works is to receive data send via the local IP 127.0.0.1 from another Unity script.
By now I have tried several ways to create a socket:
var udpClient = new UdpClient(8052,AddressFamily.InterNetwork)
var udpClient = new UdpClient(8052)
UdpClient udpClient = new UdpClient(8052,AddressFamily.InterNetwork)
var udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
I have tried...
...to receive the messages sychronous or asychronous
...to run the receive-loop in the Main thread or in a background thread
...to en-/disable blocking of the client
...to bind the client to an IP or leave it on IPAddress.Any
...to shut down the HyperV switch I had on the Ethernet Port (still shut down)
...to open the relevant ports in the firewall
...to restart the laptop
...about every solution I could find in any forum.
It feels like either the C# socket and the Step7 socket speak a different UDP or the C# socket is not functioning on the receiving side as expected.
The package is really at the doorstep of the socket and it ignores it.
Setup specs:
PLC: CPU315-2 PN/DP
Laptop: Dell Latitude, i5, 8GB RAM, Win10 Enterprise, 64-bit
Unity: Unity 2017.3.1f1, Only asset is PlayMaker
Current test code:
using System;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
using System.Threading;
public class UDPReceive03 : MonoBehaviour
{
Thread receiveThread;
public UdpClient socket;
private bool canReceive;
public static bool messageReceived;
public String statusThread;
public int UDP_LISTEN_PORT;
private int alive;
// Use this for initialization
void Start()
{
UDP_LISTEN_PORT = 8052;
print("started");
canReceive = true;
messageReceived = false;
alive = 0;
receiveThread = new Thread(new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
}
// Update is called once per frame
void Update()
{
// I know the code below is ugly, but that was my rebellion agains the situation
statusThread = (canReceive) ? "Waiting" : "Busy";
if (alive % 180 == 0)
sendResponse(1);
alive = (alive<180) ? alive + 1 : 1;
}
private void ReceiveData()
{
using (var udpClient = new UdpClient(8052,AddressFamily.InterNetwork))
{
int loggingEvent = 0;
while (true)
{
print("started to receive");
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
var receivedResults = udpClient.Receive(ref remoteEndPoint);
loggingEvent += receivedResults.Length;
print("Success, received " + loggingEvent.ToString() + " bytes.");
sendResponse(loggingEvent);
}
}
}
private void sendResponse(int count)
{
socket = new UdpClient(8051);
// sending data
IPEndPoint target = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 2000);
// send a couple of sample messages:
for (int num = 1; num <= count; num++)
{
byte[] message = new byte[num];
socket.Send(message, message.Length, target);
}
socket.Close();
}
}
I am aware of the lack of comments in the code, but as you might have guessed, the code changed a lot lately.
Thank you for the help.
If you want to receive from external source you need to allow Unity on firewall or disable firewall. Firewall blocks unity editor connection with external source, that is why you can send data but can not receive. If you build your project, your code will work, because it will ask you on first running
So after a very frustrating journey I found a work-around that is not nice but does the job:
I wrote a python script that opens a socket, receives the external data and forwards it via the local IP to Unity. And that works.
Here is the code:
# Import libraies
import socket
import time
# Set send IP adress and port
UDP_IP = "127.0.0.1"
UDP_PORT_Rec = 8052
UDP_PORT_Unity = 8055
print("Receiving on Port:" + str(UDP_PORT_Rec))
print("Sending to IP:" + UDP_IP + ":" + str(UDP_PORT_Unity))
# Set socket to send udp messages and bind port
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('',UDP_PORT_Rec));
## Keep sending message from file location
while True:
data, addr = sock.recvfrom(1024) #buffer size, hopefully no problem if too big
print("Received")
sock.sendto(data, (UDP_IP, UDP_PORT_Unity))
print("Send")
Tools that are useful for your trouble shooting:
Install Wireshark! It is probably the best tool out there to track Internet traffic. Packages that are visible in Wireshark might not be visible for a normal application!
Use Packet Sender to generate and receive traffic. The application uses a basic approach to receive packages - If it can then your programm should be able to as well.
Check with netstat -aon if your socket is running.
For completion: Check your firewall settings.

Sending UDP Messages to IPAddress.Broadcast fails with SocketError 10065 (WSAEHOSTUNREACH)

Our C# applications targeting .NET 4.0 sends an udp broadcast from time to time to IPAddress.Broadcast. We recently received a log (run on Win 8.1 Pro), which shows up that sending to 255.255.255.255:somePort resulted in a SocketException with ErrorCode 10065 (WSAEHOSTUNREACH).
I'd consider this as non remarkable, if either the network connection is lost or if sending to a specific machine. But at the time of the exception, the network was up and running, even incoming UDP packages could be read from the same socket.
Here's the code being used:
public void Setup(){
_incoming = new IPEndPoint(IPAddress.Any, IncomingPort);
_outgoing = new IPEndPoint(IPAddress.Broadcast, OutgoingPort);
_udpClient = new UdpClient();
_udpClient.Client.ExclusiveAddressUse = false;
_udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_udpClient.Client.Bind(_incoming);
}
public void Send(byte[] dataToSend)
{
_udpClient.Send(dataToSend, dataToSend.Length, _outgoing);
}
Now the two questions regarding this issue:
1.) What could cause this behavior?
2.) What scenario do i need to setup to, in order to be able to test the same behavior?

C# .Net Socket Server Client

I've got a little problem with the .Net Sockets in C#.
I programmed a client and a server working with TCP.
As the client is opened it sends a handshake to the server. The server answers with it's state (clientexists, clientaccepted,...). After that the application sends a getdata-request, abandons the connection and listens for the server's 'response'. Now, the server builds a connection to the client and sends all the data the client needs.
The code and everything else works, but the problem:
On our company testserver it works fine, on the live server only the handshake works. After it the client doesn't receive any more data. Serverapplication is the same on both servers.
I thought the problem was caused by some firewall (server wants to build a tcp connection to the client -> not good), but the system administrator said there is no firewall that could block that.
Now I'm searching for a ('cheap') solution that doesn't take too much time and changes in code. If anyone knows how to theoretically solve that, that would be great.
BTW: I am not allowed to do anything on the live server other than run the serverapplication. I don't have the possibility to debug on this server.
I can't publish all of my code, but if you need to see specific parts of it, ask for it please.
---EDIT---
Client-Server communication
1) Client startup
Client send handshake (new tcp connection)
2) Server validates handshake and saves IP
Server responds with it's client state (same tcp connection)
3) Client acknowledges this response and abandons this connection
Client sends getdata-request (new tcp connection)
Client abandons this tcp connection, too
4) Server receives getdata-request and collects the needed data in the main database
Server sends all the collected data to the client (multiple tcp connections)
5) Client receives all data and displays it in it's GUI (multiple tcp connections and the order of the data is kept by working with AutoResetEvents and Counts of sockets to send)
This is the main part my code does. It's by far not the best but it was for me as I wrote it I guess. Step one, two and three work as intended. The processing of the data works fine, too.
Another thing i forgot to mention is that the solution uses two Ports '16777' and '16778'. One to receive/listen and one to send.
My code is based on the MSDN example of the asynchronous server and client.
Sending a handshake (and getdata-request)
public void BeginSend(String data)
{
try
{
StateObject state = new StateObject();
state.workSocket = sender;
byte[] byteData = Encoding.UTF8.GetBytes(data);
sender.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback((IAsyncResult e) =>
{
Socket socket = (Socket)e.AsyncState;
SocketBase.StateObject stateObject = new SocketBase.StateObject();
stateObject.workSocket = socket;
socket.BeginReceive(stateObject.buffer, 0, 256, SocketFlags.None, new AsyncCallback(this.ReadCallback), (object)stateObject);
}), sender);
sender = RetrieveSocket(); //Socketreset
Thread.Sleep(100);
}
catch /*(Exception e)*/
{
//--
}
}
Server listener
public void StartListening()
{
listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(System.Int32.MaxValue);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
//--
}
}
public void AcceptCallback(...);
public void ReadCallback(...);
Socket send
private void Send(Socket handler, String data)
{
Socket t = RetrieveSocket(((IPEndPoint)handler.RemoteEndPoint).Address);
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.UTF8.GetBytes(data);
// Begin sending the data to the remote device.
t.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), t);
}
Socket send all data part (answer to getdata-request | socToHandle should be the socket of the previous connection of the getdata-request)
private void SendAllData(Socket socToHandle, string PakContent)
{
#region IsThereADatetime? //Resolve a given datetime
#region GiveClientNumberOfPackets //Send the client info about how much he has to receive (See line below)
Send(socToHandle, "ALERT#TASKCOUNT;OPT-" + GetBestDate(dateStart) + EndSocket);
#region #SendResouces
#region #SendGroups
#region #SendTasks
}
Looking through my old code I have one idea =>
Could I send everything over the same connection by changing:
Socket t = RetrieveSocket(((IPEndPoint)handler.RemoteEndPoint).Address);
(which creates a new connection) to something that uses the same connection?
If that would work, how can I do that?
And would the listener part of the client still receive single packets?
Servers and their environment are configured to handle incoming requests properly. Clients are usually behind a router, which by default make them unable to receive incoming connections from outside their network (a good thing).
To enable incoming connections, you could configure your router to forward all requests for a certain port number to your machine. No one else on your network would be able to run the client then, though.
This is why in a typical multiple clients-single server environment, the client makes all the connections, and only the server requires any changes to the network landscape.
I don't know why you chose to connect to the clients from the server side, but I would strongly advise against this - any cheap solution that uses this mechanism may turn out to be very expensive in the end.

UdpClient Receive not receiving datagram

I trying to write a TFTP client for a class project.
Using the UdpClient class I can successfully request data from the server but the returned packet never reaches my code.
My firewall is turned off.
I can observe the returned packet in wireshark but UdpClient.Receive blocks indefinitely.
mUdpClient is initialized like this in the constructor: mUdpClient = new UdpClient();
mUdpClient is connected like this
public void connect(String host, int port) {
mServerAddress = System.Net.Dns.GetHostAddresses(host)[0];
var endPoint = new IPEndPoint(mServerAddress, port);
mUdpClient.Connect(endPoint);
}
After the connect I send my request which is successful (as observed in wireshark)
This is what my receive code looks like
private void receiveResponse() {
var newEndpoint = new IPEndPoint(IPAddress.Any, 0);
byte[] response = mUdpClient.Receive(ref newEndpoint);
Console.Out.WriteLine(response);
}
This has been tested on my Surface Pro and a Windows 8.1 VirtualBox VM running under Debian.
Note that since you are using the Connect() method on your UDP socket, you will only see datagrams actually sent from that IPEndPoint. If your remote host for some reason uses a different IPEndPoint to send data back to you, you won't see it. So maybe try not using the default host feature (i.e. don't call Connect...just provide the remote IPEndPoint on each Send() call).

Categories

Resources