发送UDP广播以填充USR-TCP232 LAN模块信息

时间:2016-09-23 08:15:39

标签: c# sockets udp broadcast

我正在使用USR-TCP232 LAN模块进行嵌入式项目。 我有一个工具来查询制造商生产的那些模块,效果很好。 但是,我希望它在我的C#代码中。所以,我决定为自己制作一个。我相信我是如此亲密,但我想一个小故障给了我很多困难,我需要有人给我一些照亮。

我可以发送UDP广播,我可以通过“WireShark”观察流量。 它与原始工具非常相似。但是,我无法在我的代码中收到网络上设备发送的应答数据。

C#中的控制台应用

using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;

namespace UDPer
{
    class Program
    {
        static void Main(string[] args)
        {
            UDPer udp = new UDPer();
            udp.Starter();

            ConsoleKeyInfo cki;
            do
            {
                if (Console.KeyAvailable)
                {
                    cki = Console.ReadKey(true);
                    switch (cki.KeyChar)
                    {
                        case 's':
                            udp.Send("0123456789012345678901234567890123456789");

                            break;
                        case 'x':
                            udp.Stop();
                            return;
                    }
                }
                Thread.Sleep(10);
            } while (true);
        }
    }

    class UDPer
    {
        private Socket udpSock;
        private byte[] buffer;
        public void Starter()
        {
            //Setup the socket and message buffer
            udpSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpSock.Bind(new IPEndPoint(IPAddress.Any, 0));
            udpSock.EnableBroadcast = true;
            buffer = new byte[1024];

             udpSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            //udpSock.ExclusiveAddressUse = false; // only if you want to send/receive on same machine.

             //The socket must not be bound or connected.
            //Start listening for a new message.
            EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
            udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, udpSock);
        }

        public void Stop()
        {
            try
            {
                udpSock.Close();
                Console.WriteLine("Stopped listening");
            }
            catch { /* don't care */ }

        }
        private void DoReceiveFrom(IAsyncResult iar)
        {
            try
            {
                //Get the received message.
                Socket recvSock = (Socket)iar.AsyncState;
                recvSock.EnableBroadcast = true;
                EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
                int msgLen = recvSock.EndReceiveFrom(iar, ref clientEP);
                byte[] localMsg = new byte[msgLen];
                Array.Copy(buffer, localMsg, msgLen);

                //Start listening for a new message.
                EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
                udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, udpSock);

                //Handle the received message
                Console.WriteLine("Recieved {0} bytes from {1}:{2}",
                                  msgLen,
                                  ((IPEndPoint)clientEP).Address,
                                  ((IPEndPoint)clientEP).Port);
                //Do other, more interesting, things with the received message.
                string message = Encoding.ASCII.GetString(localMsg);
                Console.WriteLine("Message: {0} ", message);
            }
            catch (ObjectDisposedException)
            {
                //expected termination exception on a closed socket.
            }
        }

        public void Send(string message)
        {
            UdpClient udp = new UdpClient(1500);
            var ipEndPoint = new IPEndPoint(IPAddress.Broadcast, 1500);
            byte[] data = Encoding.ASCII.GetBytes(message);
            udp.Send(data, data.Length, ipEndPoint);
            udp.Close();
        }
    }
}

Wireshark捕获

enter image description here

请注意:此Wireshark捕获与原始工具完全相同。

一些定义:

我的PC所在的C#应用​​程序:192.168.65.82

LAN模块IP地址:192.168.65.8

端口必须为1500,这一切都没问题。

发送有效负载以查询LAN模块; “0123456789012345678901234567890123456789”

所以,我已经逐一尝试了很多不同的选择,但到目前为止还没有。 我在这里错过了什么?

1 个答案:

答案 0 :(得分:1)

套接字始终具有专用端口。传递端口号为0的IPEndPoint并不意味着您收到发送到任何端口的数据包。而是绑定到底层服务提供商分配的端口。

udpSock.Bind(new IPEndPoint(IPAddress.Any, 0));
  

如果您不关心使用哪个本地端口,则可以使用0作为端口号创建IPEndPoint。在这种情况下,服务提供商将分配1024到5000之间的可用端口号

https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.bind(v=vs.110).aspx

您需要使用

udpSock.Bind(new IPEndPoint(IPAddress.Any, 1500));