发送和接收UDP数据包 [英] Sending and Receiving UDP packets

查看:436
本文介绍了发送和接收UDP数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码将在端口15000包:

The following code sends a packet on port 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();



然而,它是一种无用的,如果我不能再接受另一台计算机上。所有我需要的是将命令发送到局域网上的另一台计算机,并为它接受它,并做一些事情。

However, it's kind of useless if I can't then receive it on another computer. All I need is to send a command to another computer on the LAN, and for it to receive it and do something.

如果不使用PCAP库,有什么办法我能做到这一点?我的程序与通信电脑在Windows XP 32位,并发送计算机是Windows 7的64位,如果它的确与众不同。我看着成各种网​​络发送命令,但我不出来。

Without using a Pcap library, is there any way I can accomplish this? The computer my program is communicating with is Windows XP 32-bit, and the sending computer is Windows 7 64-bit, if it makes a difference. I've looked into various net send commands, but I can't figure them out.

我也有,获得了计算机(XP的)的本地IP,通过能够身体输入'就可以了IPCONFIG

I also have access to the computer (the XP one)'s local IP, by being able to physically type 'ipconfig' on it.

编辑:这里的接收功能,我使用的,由地方复制:

Here's the Receive function I'm using, copied from somewhere:

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

推荐答案

下面是简单服务器和客户端的版本,发送/接收UDP数据包

Here is the simple version of Server and Client to send/receive UDP packets

服务器

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

这篇关于发送和接收UDP数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆