Broadcast captured unicast packets

Apr 28, 2010 at 4:20 PM
Edited Apr 28, 2010 at 10:28 PM

I have a situation like this. Device A is sending unicast UDP packets from port 10001 to computer B. I want to install a windows service on computer B that will capture those packets and forward them to computer C (via broadcast). Wireshark shows that my computer C is receiving the broadcast but in my sample C# app using UdpClient, I am unable to receive it. Any ideas why? Is it possible to send packets with different IP/MAC than the interface it's being send from?

Device simulator:

        static void Main(string[] args)
{
var sender = new UdpClient(10001);
var port = new Random((int) DateTime.Now.Ticks).Next(20000, 40000);
var receiver = new IPEndPoint(IPAddress.Parse("10.0.0.128"), port);
var data = Encoding.ASCII.GetBytes("Hello World!");
Console.WriteLine(String.Format("Sending to port {0}", port));

while (true)
{
var sendCount = sender.Send(data, data.Length, receiver);
Console.WriteLine(String.Format("Data sent {0}", sendCount));
Console.ReadLine();
}
}

Computer B (capturing service):

        private static void OnPacketReceived(PacketCommunicator device, Packet p)
{
var ethernetLayer = (EthernetLayer)p.Ethernet.ExtractLayer();
var backup = ethernetLayer.Source;
ethernetLayer.Destination = new IpV4Address("255.255.255.255");

var ipV4Layer = (IpV4Layer) p.Ethernet.IpV4.ExtractLayer();
ipV4Layer.Destination = new MacAddress("ff:ff:ff:ff:ff:ff");
ipV4Layer.HeaderChecksum = null;

var udpLayer = (UdpLayer) p.Ethernet.IpV4.Udp.ExtractLayer();
udpLayer.DestinationPort = 12345;

var otherLayers = p.Ethernet.IpV4.Udp.Payload.ExtractLayer();

var targetPacket = PacketBuilder.Build(p.Timestamp, ethernetLayer, ipV4Layer, udpLayer, otherLayers);

device.SendPacket(targetPacket);
}

Computer C:

        static void Main(string[] args)
{
var port = 12345;
var sock = new UdpClient(port);
sock.EnableBroadcast = true;

Console.WriteLine(String.Format("Waiting for data on port {0} ...", port ));
var iep = new IPEndPoint(IPAddress.Any, 10001);

while (true)
{
var data = sock.Receive(ref iep);
var stringData = Encoding.ASCII.GetString(data, 0, data.Length);
Console.WriteLine("received: {0} from: {1}", stringData, iep);
}
}
Coordinator
May 1, 2010 at 6:56 PM

Hi,

Since computer C receives the packets, it seems that your Pcap.Net program works fine.

I've never used UdpClient, but after googling and looking for a way to receive broadcast messages in C# it seems that using UdpClient doesn't work for many people.

You can try doing this using Pcap.Net (I believe you know how).

You can try using a Socket instead of UdpClient. There's an example here: http://www.java2s.com/Code/CSharp/Network/ReceiveBroadcast.htm