发送和接收UDP数据包

时间:2012-10-12 18:26:45

标签: c# udp message broadcast packet

以下代码在端口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),但根本没有输出。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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