views:

2311

answers:

4

Solution for Windows XP or higher. Preferably in C# or else in C++.

We do not want to broadcast using a subnet directed broadcast (e.g. 192.168.101.255) since the device we are trying to contact is not responding to this. Instead, we want to be able to send UDP datagram with a destination of 255.255.255.255 from a specific NIC/IPAddress only, such that the broadcast is NOT send out on other NICs.

This means we have to circumvent the IP stack, which is, thus, the question. How can we circumvent the IP stack on windows to send a UDP/IP compliant datagram from a specific NIC/MAC address only?

+2  A: 

Just bind() the socket to the desired interface instead of using INADDR_ANY ?

// Make a UDP socket
SOCKET s = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
// Bind it to a particular interface
sockaddr_in name={0};
name.sin_family = AF_INET;
name.sin_addr.s_addr = inet_addr("192.168.101.3"); // whatever the ip address of the NIC is.
name.sin_port = htons(PORT);
bind(s,(sockaddr*)name);
Chris Becke
Is this possible directly in C#? Or would you have to create your own wrapper in e.g. C++/CLI?
harrydev
var localEndPoint = new IPEndPoint(IPAddress.Parse("192.168.103.1"), 0); using (var socket = new UdpClient(localEndPoint)) { var remoteEndPoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 3956); var datagram = new byte[] { 0x11, 0x22, 0x33, 0x44 }; // Trying to send broadcast datagram from the local end point only // but the send broadcasts the packet from all NICs according to Wireshark socket.Send(datagram, datagram.Length, remoteEndPoint); }
harrydev
Hmm how do you paste code correctly? Anyhoo, this does not work so the answer given does not work.
harrydev
+1  A: 

I've not tried this, but I know that WinPCap allows you to do a raw send. Since it works at a pretty low level, it might allow you to send low enough on the stack to bypass the full broadcast. There are various C# wrappers out there, and of course you can use the normal C/C++ code available out there. I think the trick might be to bind to the right adapter you want to send out of and it might just work.

Erich Mirabal
+1  A: 

The broadcast address 255.255.255.255 is too general. You have to craft a different broadcast address for each network interface separately.

Jim Bell
Will not work for my issue, since destination device will only accept 255.255.255.255.
harrydev
+1  A: 

In order to use WinPcap to send a raw pcaket in C#, you can use Pcap.Net. It's a wrapper for WinPcap written in C++/CLI and C# and includes a packet interpretation and creation framework.

brickner