5

以下代码在端口 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命令,但我无法弄清楚。

我还可以通过在其上物理键入“ipconfig”来访问计算机(XP 计算机)的本地 IP。

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

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),但根本没有输出。

4

1 回答 1

20

这是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);
于 2012-10-12T20:57:24.697 回答