In C#, .Net 4, I have a need to send a UDP message on a port and listen for responses on the same port.
I was using a fixed port, but a customer ran into an issue with that, so I want to use any available port. It seems like I can do that by using 0 for the port number, but it isn't working. Digging into that some more, it appears it doesn't assign the port until it is actually used, so my two bind statements might be going to different ports.
From MSDN:
"If you do not care which local port is used, you can create an
IPEndPoint using 0 for the port number. In this case, the service
provider will assign an available port number between 1024 and 5000.
If you use the above approach, you can discover what local network
address and port number has been assigned by calling the
LocalEndPoint. ... If you are using a connectionless protocol, you
will not have access to this information until you have completed a
send or receive."
Trouble is, I want to set up my send and receive on initialization. If I wait until the first send to set up the receive, I might miss some responses. Is there a better answer than just sending a garbage message to assign the port so I can finish the initialization?
My code:
public bool InitializeSockets()
{
try
{
IPAddress localaddr = LocalIPAddress();
localep = new IPEndPoint(localaddr, 0); //(was port 50000);
//-----------------------------------------------------------------
// set up listener port for responses coming back on the same port
//-----------------------------------------------------------------
listener = new UdpClient();
listener.ExclusiveAddressUse = false;
listener.Client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, true);
listener.Client.Bind(localep);
detailsOutputText = "Ready to listen on " + localep;
ustate = new UdpState();
ustate.e = localep;
ustate.u = listener;
//------------------------
// set up broadcast port
//------------------------
bcast = new UdpClient();
bcast.Client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, true);
bcast.Client.Bind(localep);
//-------------------------------
// start listening for responses
//-------------------------------
msgRxCallback = listener.BeginReceive(new AsyncCallback(DiscoveryCallback), ustate);
return true;
}
catch (Exception exc)
{
if (exc is SocketException)
{
// This only catches if another process has opened that port without sharing it
// or if firewall blocks it?
MessageBox.Show("Error opening IP address:Port : " + localep;
}
else
MessageBox.Show(exc.ToString());
return false;
}
}
Thanks
Two options:
Create a configuration file that contains the port number. On initialization, read the config file and use that port number when setting up the clients. Supply a config file with a default port number, and give your customer instructions about how to change it if required.
In your initialization, create a receiver, give it a very short receive timeout, and call Receive. That will cause the port to bind. You can then get the local end point and use that when you create your sender. See Can I set the timeout for UdpClient in C#? regarding setting the receive timeout.
Related
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.
I'm currently developing a network application on my machine with 2 network interfaces with the following setup -
I want to send UDP message by using the first configuration with IP 192.168.1.2.
using (var udpClient = new UdpClient(5556))
{
udpClient.Connect(IPAddress.Parse("192.168.1.2"), 5556);
// DO STUFF
}
When I try this I get the following error -
No connection could be made because the target machine actively
refused it
Strange this is that when I disable my other network that this works perfectly but with 2 connections (LAN & WiFi) it doesn't work anymore...
I guess that it is sending on wrong adapter?
Is this because my Default gateway is the same or what am I doing wrong?
I'm new to developing network-based applications...
You have to specify an IPEndPoint with networking card IP like this:
var endpoint = new IPEndPoint(IPAddress.Parse("192.168.1.2"), portNum);
UdpClient client = new UdpClient(endpoint);
You are not telling UdpClient which IP to use.
UdpClient has a constructor that can take an IPEndPoint.
const string ip = "192.168.1.2";
const int port = 5556;
var listenEndpoint = new IPEndPoint(IPAddress.Parse(ip), port);
var udpClient = new UdpClient(listenEndpoint);
I'm not that good in C# but I think I understand the problem. You are binding your udpClient to port 5556 but you're not specifying the IP address. The OS will select the IP address for you. I suppose it could be either 192.168.1.2 or 192.168.1.5, you cannot tell which one.
Then with the same udpClient you are trying to connect to a remote host listening on 192.168.1.2, port 5556. And probably nobody is listening there. This is why you receive the error.
I would do the following (sorry for my bad C# skills):
Have two udpClient's, in one thread or program/process:
var udpClient1 = new UdpClient("192.168.1.2", 5556);
This one will listen on IP addres 192.168.1.2, port 5556.
in second thread or program/process:
var udpClient2 = new UdpClient(); //doesn't matter which (IP, port) the OS will bind it to.
udpClient2.Connect(IPAddress.Parse("192.168.1.2"), 5556); //connect to peer/server listening in (IP=192.168.1.2, port=5556)
You could handle both udpClient1 and udpClient2 in the same thread also.
The important is that if you connect to and (IP, port) there has to be some application/process listening there. Otherwise, the remote host will send an ICMP message indicating the datagram cannot be delivered. The connection is refused.
Apparently ICMP isn't the only way to create a Traceroute. This and this answer indicates it's possible to send a UDP packet (or any other) with a low TTL and wait for the ICMP message.
How would I go about implementing this in C#? System.IO.Sockets? The TCP objects? Anyone know of an easy/best way?
Update 1:
The following code seems to correctly throw an exception when the TTL is hit. How do I extract information from the returned UDP Packet?
How do I know that the UDP packet I'm receiving is intended for me (and not some other application on my host?)
public void PingUDPAsync(IPAddress _destination, short ttl)
{
// This constructor arbitrarily assigns the local port number.
UdpClient udpClient = new UdpClient(21000);
udpClient.Ttl = ttl;
// udpClient.DontFragment = true;
try
{
udpClient.Connect(_destination, 21000);
// Sends a message to the host to which you have connected.
Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
udpClient.Send(sendBytes, sendBytes.Length);
//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// 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 (SocketException socketException)
{
Console.WriteLine(socketException.ToString());
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Yes, System.Net.Sockets should provide you all the primitive objects you would need to send/receive UDP/TCP packets. Plenty of documentation and samples online, the two articles you included in your question are very interesting and a good starting point :)
https://learningnetwork.cisco.com/thread/87497
You can check out the answer here that goes into detail on Cisco's UPD traceroute implementation. It is rather comprehensive and can easily adapted to target a specific UDP port. You do not get a UDP packet back from the target. Rather, you get an ICMP reply to indicate the traffic was not received. The UDP packet that you originate has a random response port number included and your host tracks what ports are used by what applications. When the ICMP response is sent back, it is sent to the host IP and the response port included in the UDP header. Your host will then see the port and know it is bound to your application. It then delivers the packet to your application.
I have a server application. I also have a client application. I am able to establish a tcp connection between the applications when both applications happen to be on the same network. so let's say that the computer running the server application is listening from new connections on port 2121 and it has the LAN ip address 192.168.0.120. On a different computer running the client application I will be able to establish a connection by providing port number 2121 and ip address 192.168.0.120.
Is there a way to find all computers on a network that are listening on port 2121?
One algorithm that I am thinking now is like:
get ip address of current computer and lets say it comes out as 192.168.0.145.
now most likely the server will be listening on ip addresss 192.168.0.?
then ping 192.168.0.1 on port 2121 then 192.168.0.2 on port 2121 ... and then keep going.
I don't know if that method is efficient. moreover there might be a possibility that the server happens to be listening on ip address 192.168.1.x
So what changes will I have to make to my server and client application so that the client is able to find all the servers listening on port 2121?
The algorithm you proposed is the one you need. One problem is in the dynamic generation of the candidate IP addresses.
Normally, the possible IP address range is the one given by the subnet mask ( http://en.wikipedia.org/wiki/Subnetwork ). More exactly, the part of the IP that change is that part when in the subnet mask you have 0bits (always at the end of mask).
In your example:
if the mask is 255.255.255.0, then your possible ip address range is
192.168.0.*.
if the IP can also be 192.168.1.* then probably the mask should be 255.255.0.0
you can also have mask like 255.255.255.128 and the range would be 192.18.1.[1-126]. You can practically learn more using http://www.subnet-calculator.com/
The only other possibilities which cause your problem that I see to have these distinct ranges are:
you have more DHCP servers in your network, which is really bad as you will have "race conditions". The solution here is to fix your infrastructure by removing all but 1 DHCP server
you have manually set IP addresses (probably on laptops). The solution is to change to DHCP (if you need a specific IP that will always be assigned to a specific computer, use static DHCP)
Getting back to the problem of finding the problem of checking if "something" is listening on a specific port, the ICMP protocol is not the best here, as the majority of firewalls filter both the broadcast ICMP and single ICMP. If we are truly talking of a server, chances are you had to manually open the port you are looking for. Also, even if all computers respond, you still don't know if they host your wanted service.
The solution below involves computing the possible range of candidate IP addresses. After that you iterate through them to see if you can connect to your port.
In this implementation I test sequentially, which proves to be very slow as the timeout for connect is 30 seconds if the host is not on. For several hundred candidates, it doesn't sound too good. However, if the majority of host are available (even if they don't host your service), everything will go several times faster.
You can improve the program by either finding out how to decrease this timeout (I couldn't find out how in my allocated time) or to use a custom timeout as presented in How to configure socket connect timeout . You could also use multi-threading and adding the address that worked in a thread-safe collection and work with it from there.
Also, you could try pinging (ICMP) before, but you could miss valid servers.
static void Main(string[] args)
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
int wantedPort = 21; //this is the port you want
byte[] msg = Encoding.ASCII.GetBytes("type msg here");
foreach (NetworkInterface netwIntrf in NetworkInterface.GetAllNetworkInterfaces())
{
Console.WriteLine("Interface name: " + netwIntrf.Name);
Console.WriteLine("Inteface working: {0}", netwIntrf.OperationalStatus == OperationalStatus.Up);
//if the current interface doesn't have an IP, skip it
if (! (netwIntrf.GetIPProperties().GatewayAddresses.Count > 0))
{
break;
}
//Console.WriteLine("IP Address(es):");
//get current IP Address(es)
foreach (UnicastIPAddressInformation uniIpInfo in netwIntrf.GetIPProperties().UnicastAddresses)
{
//get the subnet mask and the IP address as bytes
byte[] subnetMask = uniIpInfo.IPv4Mask.GetAddressBytes();
byte[] ipAddr = uniIpInfo.Address.GetAddressBytes();
// we reverse the byte-array if we are dealing with littl endian.
if (BitConverter.IsLittleEndian)
{
Array.Reverse(subnetMask);
Array.Reverse(ipAddr);
}
//we convert the subnet mask as uint (just for didactic purposes (to check everything is ok now and next - use thecalculator in programmer mode)
uint maskAsInt = BitConverter.ToUInt32(subnetMask, 0);
//Console.WriteLine("\t subnet={0}", Convert.ToString(maskAsInt, 2));
//we convert the ip addres as uint (just for didactic purposes (to check everything is ok now and next - use thecalculator in programmer mode)
uint ipAsInt = BitConverter.ToUInt32(ipAddr, 0);
//Console.WriteLine("\t ip={0}", Convert.ToString(ipAsInt, 2));
//we negate the subnet to determine the maximum number of host possible in this subnet
uint validHostsEndingMax = ~BitConverter.ToUInt32(subnetMask, 0);
//Console.WriteLine("\t !subnet={0}", Convert.ToString(validHostsEndingMax, 2));
//we convert the start of the ip addres as uint (the part that is fixed wrt the subnet mask - from here we calculate each new address by incrementing with 1 and converting to byte[] afterwards
uint validHostsStart = BitConverter.ToUInt32(ipAddr, 0) & BitConverter.ToUInt32(subnetMask, 0);
//Console.WriteLine("\t IP & subnet={0}", Convert.ToString(validHostsStart, 2));
//we increment the startIp to the number of maximum valid hosts in this subnet and for each we check the intended port (refactoring needed)
for (uint i = 1; i <= validHostsEndingMax; i++)
{
uint host = validHostsStart + i;
//byte[] hostAsBytes = BitConverter.GetBytes(host);
byte[] hostBytes = BitConverter.GetBytes(host);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(hostBytes);
}
//this is the candidate IP address in "readable format"
String ipCandidate = Convert.ToString(hostBytes[0]) + "." + Convert.ToString(hostBytes[1]) + "." + Convert.ToString(hostBytes[2]) + "." + Convert.ToString(hostBytes[3]);
Console.WriteLine("Trying: " + ipCandidate);
try
{
//try to connect
sock.Connect(ipCandidate, wantedPort);
if (sock.Connected == true) // if succesful => something is listening on this port
{
Console.WriteLine("\tIt worked at " + ipCandidate);
sock.Close();
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
//else -. goes to exception
}
catch (SocketException ex)
{
//TODO: if you want, do smth here
Console.WriteLine("\tDIDN'T work at " + ipCandidate);
}
}
}
Console.ReadLine();
}
sock.Close();
}
(sorry for my bad english) I am actually needing something similar to this and just found out about multicast. Here you can find an article and example. The sample app from the article worked fine on my lan. I do not know exactly how it works but maybe you can multicast something from the client and have the server(s) to respond with its IP? Or if that do not work, have the server multicasting his IP in a timed interval should do it. Sorry for the lack of informations, i just learned about this :)
An option i am not seeing beeing discussed here is to have a Master Server.
The idea is quite simple: A server where your application's server can register and where you application clients can get a list of active servers.
Server A is loaded and imediatly sends a hello message to the Master Server
Server B is loaded and sends an hello message to the Master Server
Both Server A and B keep sending hello's to Master Server every X Minutes so he knows they are still on
Client A is loaded - Needs to issue command - asks Master Server for List of Active Servers - Picks a server from the list - issues command
Things to keep in mind:
Master Server must be on a known address / port - either fixed ip or get ip throw well known ServerName
Purpose of Master Server is simply register servers and supply clients with their addresses - At first glance i see no other service it could provide your application
If any server is as good as any other for your application, i would advise the list to be ordered according to timestamp of last hello message received from that server - that way client will have at the top of that list the server most likelly to still be up (since it reported beeing up last) and can go down the list subsequentially.
More over, every time the Master Server receives an hello that list changes, so every so often client requests will get a different server list and use a different preferencial server, relieving load on servers accross the board.
can't you use the same method as when you get your ip.
let the client send a broadcast - if no response wait
server receive broadcast and send one back with its own ip.
now the client know that the server is out there and on what ip.
I assume you have a single server. If you can guarantee that the server location (ip address and port) is constant (or can be looked up) then each client application can 'register' with the server by connecting to it and informing the server about the ip address and local port to call back.
ICMP Ping does not determine if a computer is listening on a specific port, only if the computer is configured to response to a ping. ICMP is a protocol, different then TCP or UDP. It's only use for you would be to determine if an IP Address is use, and even then is becoming less viable.
You have two options.
Have the client constantly check every IP address on your local network and try to open port 2121. This is not a good option.
Have every server send out a ICMP ping to the broadcast address with specific data announcing it is on (and optionally not connected to a client) the never every so often (I would recommend a minute for testing, and 5 minutes minimum for production). All your software has to do is look for the broadcast ping and connect to the sending IP Address.
Update:
using System.Net.NetworkInformation;
private Ping _Ping = new Ping();
private PingOptions _PingOptions = new PingOptions(64, true);
private byte[] _PingID = Encoding.ASCII.GetBytes("MyPingID");
private _PingResponse = new AutoResetEvent(false);
public <classname> //Constructor
{
_Ping.PingCompleted += new PingCompletedEventHander(PingCompleted);
}
public void PingCompleted(object Sender, PingCompletedEventArgs e)
{
if (e.Cancelled)
{
//Status Unknown;
}
else if (e.Error != null)
{
//Status Error;
}
else if (e.Reply.Status == IPStatus.Success)
{
// Device Replying
}
else
{
// Status Unknown
}
}
public void StartPing(string AddressToPing)
{
IPAddress ipAddress = IPAddress.Parse(AddressToPing);
_Ping.SendAsync(ipAddress, 15000, _PingID, _PingOptions, _PingResponse);
}
you can make the server send his location to a specific port using UDP, and the client listen to it then the client establish a connection with the server based on the given ip and port.
In c# I am using the UdpClient.Receive function:
public void StartUdpListener(Object state)
{
try
{
udpServer = new UdpClient(new IPEndPoint(IPAddress.Broadcast, 1234));
}
catch (SocketException ex)
{
MessageBox.Show(ex.ErrorCode.ToString());
}
IPEndPoint remoteEndPoint = null;
receivedNotification=udpServer.Receive(ref remoteEndPoint);
...
However I am getting a socket exception saying that the address is not available with error code 10049
What do I do to negate this exception?
Here's the jist of some code I am currently using in a production app that works (we've got a bit extra in there to handle the case where the client are server apps are running on a standalone installation). It's job is to receive udp notifications that messages are ready for processing. As mentioned by Adam Alexander your only problem is that you need to use IPAddress.Any, instead of IPAddress.Broadcast. You would only use IPAddress.Broadcast when you wanted to Send a broadcast UDP packet.
Set up the udp client
this.broadcastAddress = new IPEndPoint(IPAddress.Any, 1234);
this.udpClient = new UdpClient();
this.udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
this.udpClient.ExclusiveAddressUse = false; // only if you want to send/receive on same machine.
And to trigger the start of an async receive using a callback.
this.udpClient.Client.Bind(this.broadcastAddress);
this.udpClient.BeginReceive(new AsyncCallback(this.ReceiveCallback), null);
Hopefully this helps, you should be able to adapt it to working synchronously without too much issue. Very similar to what you are doing. If you're still getting the error after this then something else must be using the port that you are trying to listen on.
So, to clarify.
IPAddress.Any = Used to receive. I want to listen for a packet arriving on any IP Address.
IPAddress.Broadcast = Used to send. I want to send a packet to anyone who is listening.
for your purposes I believe you will want to use IPAddress.Any instead of IPAddress.Broadcast. Hope this helps!
That error means the protocol cant bind to the selected IP/port combination.
I havent used UDP broadcast in ages, but I do recall you need to use different IP ranges.
There's nothing wrong with the way you have configured your UdpClient. Have you tried a different port number? Perhaps 1234 is already in use on your system by a different app.