【问题标题】:Sending and Receiving UDP packets发送和接收 UDP 数据包
【发布时间】:2012-10-03 14:51:43
【问题描述】:

以下代码在 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();

但是,如果我不能在另一台计算机上接收它,那就没用了。我所需要的只是向 LAN 上的另一台计算机发送命令,并让它接收它并执行一些操作。

如果不使用 Pcap 库,我有什么办法可以做到这一点?我的程序与之通信的计算机是 Windows XP 32 位,发送计算机是 Windows 7 64 位,如果有区别的话。我查看了各种net send 命令,但我无法弄清楚。

我还可以访问计算机(XP 计算机)的本地 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),但根本没有输出。

【问题讨论】:

  • 你知道new IPEndPoint(IPAddress.Broadcast, port)的意义吗?
  • 老实说,不是真的。我试图了解主要是复制粘贴的内容,但这条线让我难以理解。 IPAddress.Broadcast 是 255.255.255.255,我的数据包正在发送,如 Wireshark 所示。对不起!
  • 嗯,广播一般是做什么的呢?如果您在广播某事的人附近,会发生什么?
  • 据我所知,广播发送的消息对 LAN 上的每个人都可见。我可以将 IPAddress.Parse() 与计算机的确切 IP 一起使用,如果这样更安全、更快或其他方式。我只是在 C# 中处理数据包,并没有取得太大的成功。
  • 对于无连接通信,你需要创建socket对象并绑定到你的IPEndPoint,给你一个例子

标签: c# udp message broadcast packet


【解决方案1】:

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

服务器

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);

【讨论】:

  • 谢谢!到目前为止,我正试图让客户工作。我将 byte[] 放在“数据”前面以创建一个字节数组(在客户端中),但我不确定将什么作为 ServerHostName。我会尝试我自己的本地IP。谢谢!
  • ServerHostName 将是您发送 UDP 数据的目标主机。如果你想在本地运行,可以输入localhost
猜你喜欢
  • 2012-05-20
  • 2019-01-04
  • 2014-11-14
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 2012-05-09
  • 2011-09-24
  • 1970-01-01
相关资源
最近更新 更多