无法接收指定给我的IP地址的数据包

时间:2018-08-07 13:49:32

标签: c# network-programming

我有一个应用程序,可以在特定端口上发送广播消息,并在LAN上监听答案。根据Wireshark会话,某些设备将响应IP地址(例如192.168.1.255),而其他设备将响应我的特定IP地址(例如,再次)192.168.10.13

我遇到的问题是我的应用程序将看到在广播IP地址(192.168.10.255)上发送其答案的设备的响应,但是我的应用程序无法看到针对我的IP地址的响应。

这是我设置和发送数据包的方式

public struct UdpState
{
    public System.Net.IPEndPoint EP;
    public System.Net.Sockets.UdpClient UDPClient;
}

public static void StartTimers()
{
    //setting up "GlobalUdp" as a UdpClient, with an endpoint of the NIC selected and the port 30303
    //making the endpoint the ip address of the NIC
    System.Net.IPEndPoint BindEP = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(Properties.Settings.Default.selectedNic), 30303);
    GlobalUdp.UDPClient = new UdpClient(BindEP); //binding to that NIC and port
    GlobalUdp.EP = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("255.255.255.255"), 30303);
    GlobalUdp.UDPClient.EnableBroadcast = true;
    GlobalUdp.UDPClient.MulticastLoopback = false;       
}

public static void SendBroadcast(object source, ElapsedEventArgs f)
{
    byte[] DiscoverMsg = Encoding.ASCII.GetBytes("Discovery: Who is out there?"); //this has to be the message sent for devices to reply
    GlobalUdp.UDPClient.Send(DiscoverMsg, DiscoverMsg.Length, new System.Net.IPEndPoint(System.Net.IPAddress.Parse("255.255.255.255"), 30303)); //sending the message
}

这就是我监听数据包的方式

public static void WaitingForMessages()
{
    UdpClient listener = new UdpClient(30303); //creating a UDPClient that will listen on port 30303
    IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 30303); //making the endpoit listen to any IP Address on port 30303
    string received_data; //this string will hold data about the ansering device
    byte[] receive_byte_array; //this array will hold all the data about the device in an order fashion
    while (Properties.Settings.Default.keepListening) //while the user setting that controls listening is set to true
    {
        try
        {
            receive_byte_array = listener.Receive(ref groupEP); //getting the data from the listener
            received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length); //getting the data
            string[] messageComponents = received_data.Split(new[] { Environment.NewLine }, StringSplitOptions.None); //splitting the data into an array
            List<string> deviceCompenentsList = new List<string>(messageComponents); //creating a list from that array
            deviceCompenentsList.Add(groupEP.Address.ToString()); //adding the IP Address of the device to the list
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString()); //for troubleshooting
        }
    }
    Console.WriteLine("Exiting listening"); //for troubleshooting
    listener.Close(); //close the listener
    listener.Dispose();
}

该应用程序设置为绑定到NIC,开始监听,然后在计时器(30秒)上发送广播消息。

为什么我的应用程序没有收到去往我的IP地址的消息?

0 个答案:

没有答案