Receive UDP Broadcast - c#

I am trying to figure out how to receive UDP packets that are being broadcast out by a set of devices. I can see them coming in using Wireshark, but cant figure out how to receive them in my application. The packets are being broadcast out to all devices on the network on the same port. I need to be able to receive them from any IP address sending them. I also have 2 NIC cards if it makes a difference. I only need to listen on 1, but I'm not sure if I have to specify that. I have tried some various things with the UdpClient, but have had no luck.
192.168.1.20 255.255.255.255 UDP 768 Source port: 3001 Destination port: 3002
bool done = false;
UdpClient listener = new UdpClient(3001);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 3002);
string received_data;
byte[] receive_byte_array;
try
{
while (!done)
{
Debug.WriteLine("Waiting for broadcast");
receive_byte_array = listener.Receive(ref groupEP);
Debug.WriteLine("Received a broadcast from {0}", groupEP.ToString() );
received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
Debug.WriteLine("data follows \n{0}\n\n", received_data);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
listener.Close();

Related

Reading UDP datagrams from GNSS receiver

I am trying to read location data coming from a Airlink MP70 GNSS Gateway into a mock up console app. The GNSS sentences are sent to my computer through ethernet and UDP.
Gateway IP: 192.168.13.31 (GNSS receiver)
Source Port: 17335
Destination IP: 192.168.13.100
Port: 12351
I can see the UDP datagrams with wireshark. The highlighted area is the GNSS data I am trying to extract.
How would I go receiving this data into a basic console app preferably c# but c++/java python ok too.
Here is what I have so far but I am not seeing any output (it is just the basic code for a UDP client on Microsoft c# site).
private const int listenPort = 12351;
public static void Main()
{
UdpClient receivingUdpClient = new UdpClient(listenPort);
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
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());
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
My bad - was firewall blocking connection. Thanks from those who helped

Search server with UDP

The task of the code is to find the servers that answers the #SERVER question. If I enter the server's IP address works fine, but not at 192.168.1.255 adress.
Thanks for the help!
My code is here:
static void Main(string[] args)
{
Console.WriteLine(IPAddress.IPv6Any);
UdpClient udpClient = new UdpClient();
try
{
udpClient.EnableBroadcast = true;
udpClient.Connect("192.168.1.255",80);
// Sends a message to the host to which you have connected.
Byte[] sendBytes = Encoding.ASCII.GetBytes("#SERVER");
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 (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadKey();
}
'''
192.168.1.255or better ANY IP address ending with 255 is a broadcast address.
Messages sent to this IP are not targeted specifically but will (in the most cases) be broadcasted to all devices in your network (exceptions might be up to your local configuration). If the devices in your network react to broadcast messages or not depends on their configuratation. However sending a discovery message to the brodcast-address as you do, does not make much sense as it is not allowed to assign this IP address to any device.

Receiving unexpected udp packets in my c# client

I receive unexpected udp packets when i run the code in windows(both client and server in same system). My client is written in c# and the server is in python.
When i run in the same code in mac i don't have any problem and i receive expected messages(here i opened a port in mac for udp).
client(c#):
public static void Main(string[] args)
{
Console.WriteLine("Receiver");
// This constructor arbitrarily assigns the local port number.
UdpClient udpClient = new UdpClient();
//udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, 137));
try
{
//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 137);
string message ;
do
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
message = Encoding.ASCII.GetString(receiveBytes);
// Uses the IPEndPoint object to determine which of these two hosts responded.
Console.WriteLine("This is the message you received: " +
message);
//Console.WriteLine("This message was sent from " +
// RemoteIpEndPoint.Address.ToString() +
// " on their port number " +
// RemoteIpEndPoint.Port.ToString());
}
while (message != "exit");
udpClient.Close();
//udpClientB.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("Press Any Key to Continue");
Console.ReadKey();
}
server(python-3.6):
import socket
from time import sleep
rx=0 #000
ry=0 #000
rz=0 #000
e=0 #000
UDP_IP = "172.20.10.4"
UDP_PORT = 137
MESSAGE = ""
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
while(1):
if (rx<360):
rx=rx+1
if ((ry<360) & (rx>=360)):
ry=ry+1
if ((rx>=360) & (ry>=360)):
rx=0
ry=0
if (rz<360):
rz=rz+1
if (rz>=360):
rz = 0
if (e<10):
e=e+1
if(e>=10):
e=0
#verify rx
if (rx<10):
rxs='00'+str(rx)
if ((rx>=10) & (rx<100)):
rxs='0'+str(rx)
if (rx>=100):
rxs=str(rx)
#verify ry
if (ry<10):
rys='00'+str(ry)
if ((ry>=10) & (ry<100)):
rys='0'+str(ry)
if (ry>=100):
rys=str(ry)
#verify rz
if (rz<10):
rzs='00'+str(rz)
if ((rz>=10) & (rx<100)):
rzs='0'+str(rz)
if (rz>=100):
rzs=str(rz)
#verify e
if (e<10):
es='00'+str(e)
if ((e>=10) & (e<100)):
es='0'+str(e)
if (e>=100):
es=str(e)
MESSAGE = 'h'+'01'+'rx'+rxs+'ry'+rys+'rz'+rzs+'e'+es
#sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))
sleep(0.1)
Expected message(i receive the below in mac):
This is the message you received: h01rx360ry151rz009e007
I receive the below in windows:
This is the message you received: ?{ EJFDEBFEEBFACACACACACACACACACAAA
Can someone please letme know where i went wrong with.
thanks in advance
If the udp packets are not associated with your server this might be helpful: https://forum.fortinet.com/tm.aspx?m=106656 and here: https://superuser.com/questions/637696/what-is-netbios-does-windows-need-its-ports-137-and-138-open
Windows is using port 137 for its own services. Try change your port on the Windows device.
Looks like you are having issues with port selection. The packets you see are from Windows.
You don't need the bind statement. This is a working example I'm using with .net core
internal class Program
{
private const int PORT = 5678;
private static void Main(string[] args)
{
Console.WriteLine("Packet Forwarding UP!");
var client = new UdpClient(PORT);
// can use IPAddress.Any or other IP depending on where they are coming from.
var ipEndPoint = new IPEndPoint(IPAddress.Loopback, PORT);
while (true)
{
Console.Write("Waiting... ");
var receive = client.Receive(ref ipEndPoint);
Console.WriteLine(" - Received Data - " + receive.Length);
}
}
}
I've been testing the client with PacketSender's Intense Traffic Generator and confirming traffic with NirSoft TcpUdpWatch

C#. UDP unicast

I try to receive six messages from UDP unicast clients. Receiver looks like:
UdpClient udpclient = new UdpClient();
IPEndPoint localEp = new IPEndPoint(IPAddress.Parse(ClientIP), ClientPort);
udpclient.Client.Bind(localEp);
udpclient.Client.ReceiveTimeout = 10000;
bool isTimeExpired = false;
while (!isTimeExpired)
{
byte[] buffer;
try
{
buffer = udpclient.Receive(ref localEp);
}
catch (SocketException)
{
isTimeExpired = true;
continue;
}
// Deserialize
// ...
}
udpclient.Close();
Program works, but sometimes I don't receive 6 messages (2 or 3). Sender application:
UdpClient client = new UdpClient();
IPEndPoint remoteep = new IPEndPoint(IPAddress.Parse(ClientIP), ClientPort);
// Serialize
// ...
stream.Position = 0;
byte[] data = new Byte[stream.Length];
stream.Read(data, 0, Convert.ToInt32(stream.Length));
client.Send(data, data.Length, remoteep);
stream.Close();
client.Close();
I run 6 instances of sender application at the same machine (and one instance of receiver). I need to receive messages from every sender (six messages total) all the time. Where is my mistake?
Thank you very much!
It's UDP. There's no guarantee you'd receive any of the datagrams that were sent. UDP is, by design, unreliable. The "User" in the UDP might as well stand for "Unreliable" instead. :)
FYI: there also is no guarantee that you'll receive only one copy of any given datagram that was sent. There is also no guarantee that the datagrams will arrive in the same order in which they were sent.
If you need that kind of reliability, then you need TCP, not UDP (or you need to do a bunch of extra work to re-invent the TCP wheel).

Fetching Source IpAddress of the broadmessage meesage recieved on port 137

I am trying to fetch the IP address from the broadcast packets sent by a DSL modem and received on port 137 using UDP protocol. I am able to read the IP address when connectivity is present.
However, in unidentified network state, when my modem is configured for DHCP, and a specific range of IPs are allowed, and setting on my machine is auto-detect:
I get the default Local IP Address of the machine on reading the broadcast messages. That would be starting with 169.
Note: I am restarting the modem in order to receive the broadcast messages.
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 137);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
int iLoopCount=0;
while (iLoopCount <= 10000)
{
Console.WriteLine("Ready to receiveā€¦");
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.Default.GetString(data, 0, recv);
Console.WriteLine("{1}: from: {0}",((IPEndPoint)ep).Address.ToString(),DateTime.Now.ToString());
iLoopCount++;
// Console.WriteLine(sock.RemoteEndPoint.ToString());
}
sock.Close();
Console.Read();
Found the answer to my question at
http://www.codeproject.com/Articles/17031/A-Network-Sniffer-in-C

Categories

Resources