当前位置:  开发笔记 > 编程语言 > 正文

C#从UDP消息中获取发件人地址

如何解决《C#从UDP消息中获取发件人地址》经验,为你挑选了1个好方法。

我有一个嵌入式以太网接口(Lantronix XPort),它响应UDP广播及其识别信息.

我能够多播"魔术数据包"并且数据报正确地被监听器接收,但是我还需要找出哪个IP地址发送该响应数据报.如果它是TCP,我会执行socket.RemoteEndPoint,但是当应用于UDP套接字时会引发异常.

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地址?

编辑:

通常情况下,我在SO上发布的那一刻,一个清晰的时刻打击了我.

事实证明我可以这样做:

                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现在包含远程端点信息!



1> Brad Nabholz..:

看看ReceiveFrom而不是Receive,它将允许您传递对Endpoint的引用.

推荐阅读
喜生-Da
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有