I am using the same port number to send and receive UDP packets. Using the example in the post below, and I verified, using wireshark, that the datagrams I send and receive are using the same port number. And that the remote host is responding with the correct data. However, the EndReceive() function only returns the original datagram I sent, not the response from the remote host.
I suspect that what is happening is that, since the same port is being used, and that EndReceive listens on IPAddress.Any, it actually receives the packet that was sent. The purpose of the query is to find the IP Address of the remote device, so I send the query as a broadcast that has the serial number of the device in the query. Then the device that has that serial number will respond with a set of data that includes its IP Address. The remote device only responds to UDP packets from port 2100 and it sends its responses to port 2100. My first attempt was to use the client.Receive() function, but it produced the same results. So I switched to EndReceive(), but it didn't help.
Any suggestions on how to overcome this issue? Is there a way to determine the IP Address the PC uses to send the datagrams?
Simple UDP example to send and receive data from same socket
This is my code:
static int numRcvdBytes;
static Byte[] rcvdBytes = new Byte[512];
static void SendRequest()
{
numRcvdBytes = 0;
var data = Encoding.ASCII.GetBytes("0C1>" + amp.serial + ";000,P \r\n");
UdpClient client = new UdpClient();
IPEndPoint lep = new IPEndPoint(IPAddress.Any, 2100); // set source port to 2100.
IPEndPoint rep = new IPEndPoint(IPAddress.Parse(BroadcastIP), 2100); // set destination port to 2100.
client.ExclusiveAddressUse = false;
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
client.Client.Bind(lep);
client.BeginReceive(DataReceived, client);
client.Send(data, data.Length, rep);
Thread.Sleep(50); // allow time for remote host to respond.
if (numRcvdBytes > 2)
{
for ( int b=0; b < numRcvdBytes-2; b++)
{
Console.Write("{0}", Convert.ToChar(rcvdBytes[b]) );
}
}
else
{
LogEvent(tw, " Serial# " + amp.serial + " Not Found!" );
}
}
static void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)ar.AsyncState;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
Array.Copy(receivedBytes, 0, rcvdBytes, 0, receivedBytes.Length);
numRcvdBytes = receivedBytes.Length;
}