I have an application where I need to receive UDP unicast packets from any IP address (on a particular port), but would like to know the sender's IP address of the received packet. I have created a socket and bound it via the following code:
Socket SocketLocal;
EndPoint epReceive;
int UCPort = 1000;
byte[] Buffer = new byte[1500];
SocketLocal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
SocketLocal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
// Bind Socket
epReceive = new IPEndPoint(IPAddress.Any, UCPort );
SocketLocal.Bind(epReceive);
SocketLocal.BeginReceiveFrom(Buffer, 0, Buffer.Length, SocketFlags.None, ref epReceive, new AsyncCallback(RxCallBack), Buffer);
The callback looks like:
public void RxCallBack(IAsyncResult aResult)
{
try
{
byte[] receivedData = new byte[1500];
receivedData = (byte[])aResult.AsyncState;
// I process/intepret the received data
// ...
// I have a list box where I simply want to display
// the sender's IP address
lstBox.Items.Add(SocketLocal.LocalEndPoint.ToString()));
// Here I simply get 0.0.0.0:<port number>
// If I modify SocketLocal.LocalEndPoint.ToString above to SocketLocal.RemoteEndPoint.ToString it throws an exception
Buffer = new byte[1500];
SocketLocal.BeginReceiveFrom(Buffer, 0, Buffer.Length, SocketFlags.None, ref epReceive, new AsyncCallback(RxCallBack), Buffer);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
} // End of RxCallBack
This works well, as I am able to receive data sent from any IP to my computer. However, I would like to know the sender's IP address.
When I try and extract the Sender's IP address I simply get "0.0.0.0" which would make sense given that I set the Socket to IPAddress.any
There must be a way to find out the sender's IP address. I have searched and tried all of the various options to no avail. Can anyone provide some guidance?