C#从UDP消息中获取发件人地址 [英] C# Getting sender address from UDP message
问题描述
我有一个嵌入式以太网接口(Lantronix XPort),它以其标识信息响应UDP广播.
I have an embedded Ethernet interface (Lantronix XPort) that responds to a UDP broadcast with its identifying information.
我能够多播魔术包",并且侦听器可以正确接收数据报,但是我还需要找出发送该响应数据报的IP地址.如果是TCP,我会做socket.RemoteEndPoint,但是在应用于UDP套接字时会抛出异常.
I am able to multicast the "magic packet" and datagrams are received by the listener correctly, however I also need to find out what IP Address send that response datagram. If it were TCP, I would do socket.RemoteEndPoint, but that throws an exception when applied to a UDP socket.
public class Program
{
public static void Main(string[] args)
{
// magic packet
byte[] magicPacket = new byte[4] { 0, 0, 0, 0xf6 };
// set up listener for response
Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// EDIT: Also, had to add this to for it to broadcast correctly
sendSocket.EnableBroadcast = true;
IPEndPoint listen_ep = new IPEndPoint(IPAddress.Any, 0);
sendSocket.Bind(listen_ep);
// set up broadcast message
EndPoint send_ep = new IPEndPoint(IPAddress.Parse("192.168.255.255"), 30718);
sendSocket.SendTo(magicPacket, magicPacket.Length, SocketFlags.None, send_ep);
DateTime dtStart = DateTime.Now;
while (true)
{
if (sendSocket.Available > 0)
{
byte[] data = new byte[2048];
// throws SocketException
//IPEndPoint ip = sendSocket.RemoteEndPoint as IPEndPoint;
sendSocket.Receive(data, SocketFlags.None);
if (data.Length > 4)
{
PrintDevice(data);
}
}
if (DateTime.Now > dtStart.AddSeconds(5))
{
break;
}
Console.WriteLine(".");
Thread.Sleep(100);
}
// wait for keypress to quit
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
有什么想法吗?是否有更好的策略来读取响应数据报,以便让我确定远程IP地址?
Any thoughts? Is there a better strategy to reading the response datagrams that would let me ascertain the Remote IP Address?
通常,我在SO上发表的那一刻,清晰的一刻击中了我.
As is typical, the minute I post on SO, a moment of clarity hits me.
结果证明我可以这样做:
Turns out I can just do this:
EndPoint remote_ep = new IPEndPoint(IPAddress.Any, 0);
// Use ReceiveFrom instead of Receieve
//sendSocket.Receive(data, SocketFlags.None);
sendSocket.ReceiveFrom(data, ref remote_ep);
remote_ep现在包含远程端点信息!
And remote_ep now contains the remote endpoint information!
推荐答案
Take a look at ReceiveFrom instead of Receive, it will let you pass in a reference to an Endpoint.
这篇关于C#从UDP消息中获取发件人地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!