发送和接收UDP数据包

问题描述 投票:5回答:2

以下代码在端口15000上发送数据包:

int port = 15000;
UdpClient udp = new UdpClient();
//udp.EnableBroadcast = true;  //This was suggested in a now deleted answer
IPEndPoint groupEP = new IPEndPoint(IPAddress.Broadcast, port);
string str4 = "I want to receive this!";
byte[] sendBytes4 = Encoding.ASCII.GetBytes(str4);
udp.Send(sendBytes4, sendBytes4.Length, groupEP);
udp.Close();

但是,如果我不能在另一台计算机上接收它,那就没用了。我所需要的只是将命令发送到局域网上的另一台计算机,并让它接收它并做一些事情。

不使用Pcap库,有什么办法可以实现这个目标吗?我的程序正在与之通信的计算机是Windows XP 32位,而发送计算机是Windows 7 64位,如果它有所不同。我已经研究了各种net send命令,但我无法弄清楚它们。

我也可以访问计算机(XP one)的本地IP,因为它可以在其上物理输入'ipconfig'。

编辑:这是我正在使用的接收功能,从某处复制:

public void ReceiveBroadcast(int port)
{
    Debug.WriteLine("Trying to receive...");
    UdpClient client = null;
    try
    {
        client = new UdpClient(port);
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }

    IPEndPoint server = new IPEndPoint(IPAddress.Broadcast, port);

    byte[] packet = client.Receive(ref server);
    Debug.WriteLine(Encoding.ASCII.GetString(packet));
}

我打电话给ReceiveBroadcast(15000),但根本没有输出。

c# udp message broadcast packet
2个回答
19
投票

以下是用于发送/接收UDP数据包的服务器和客户端的simple版本

服务器

IPEndPoint ServerEndPoint= new IPEndPoint(IPAddress.Any,9050);
Socket WinSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
WinSocket.Bind(ServerEndPoint);

Console.Write("Waiting for client");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0)
EndPoint Remote = (EndPoint)(sender);
int recv = WinSocket.ReceiveFrom(data, ref Remote);
Console.WriteLine("Message received from {0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

客户

IPEndPoint RemoteEndPoint= new IPEndPoint(
IPAddress.Parse("ServerHostName"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork,
                           SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello, are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, RemoteEndPoint);

0
投票

在MSDN上实际上有一个非常好的UDP服务器和监听器示例:Simple UDP example

© www.soinside.com 2019 - 2024. All rights reserved.