最近在做一个项目,需要用udp发送广播255.255.255.255到端口10000,然后局域网中的设备就会反回一个数据包到发送时的端口,由于不同的udpclient不能绑定同一个端口,所以我用了同一个udpClient发送和接收数据,但是却无法接受数据,数据是发送了的,我用网路岗抓包看到了的。
麻烦帮我看看是什么问题,谢谢!
public partial class search_tool : Form
{
//取随机端口
static Random rd = new Random();
static int port = rd.Next(10300,50300);
public Thread receiveDUPMessageThread;
UdpClient udpClient = new UdpClient(port);
public search_tool()
{
InitializeComponent();
}
//搜索摄像机
private void buttonSearchCamera_Click(object sender, EventArgs e)
{
//发送搜索摄像机包
byte[] searchCameraMessage = { 0,0,0,1 };
sendUDPMessageByMultipleWithByte(0,searchCameraMessage);
}
//发数据
public void sendUDPMessageNoPort(Byte[] message)
{
try
{
udpClient.Connect(IPAddress.Parse("255.255.255.255"), 10000);
udpClient.Send(message, message.Length);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
//拼2个字节数组
public byte[] combain2ByteArray(byte[] a, byte[] b)
{
byte[] c = new byte[a.Length+b.Length];
a.CopyTo(c, 0);
b.CopyTo(c, a.Length);
return c;
}
//传入操作码和正文,发送UDP数据包
public void sendUDPMessageByMultipleWithByte(short operateCodeShort,byte[] cententMessage)
{
byte[] head = System.Text.Encoding.ASCII.GetBytes("MO_I");
byte[] operteCode = BitConverter.GetBytes(operateCodeShort);
byte[] baoLiu1 = { 0x00 };
byte[] baoliu2 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
int messageLengthInt = cententMessage.Length;
byte[] messageLength = BitConverter.GetBytes(messageLengthInt);
byte[] baoliu3 = { 0x00, 0x00, 0x00, 0x00 };
byte[] a1 = combain2ByteArray(head, operteCode);
byte[] a2 = combain2ByteArray(a1, baoLiu1);
byte[] a3 = combain2ByteArray(a2, baoliu2);
byte[] a4 = combain2ByteArray(a3, messageLength);
byte[] a5 = combain2ByteArray(a4, baoliu3);
byte[] message = combain2ByteArray(a5, cententMessage);
sendUDPMessageNoPort(message);
}
//监听函数
public void receiveUDPMessage()
{
while (true)
{
try
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any,0);
Byte[] receiveByte = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveByte);
MessageBox.Show("Message" + returnData);
MessageBox.Show("This message was sent from" + RemoteIpEndPoint.Address.ToString() + " on their port number " + RemoteIpEndPoint.Port.ToString());
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
private void search_tool_Load(object sender, EventArgs e)
{
receiveDUPMessageThread = new Thread(new ThreadStart(receiveUDPMessage));
receiveDUPMessageThread.Start();
}
private void search_tool_FormClosing(object sender, FormClosingEventArgs e)
{
udpClient.Close();
receiveDUPMessageThread.Abort();
}
------解决思路----------------------
也可能是ARP病毒导致交换机的MAC地址表混乱造成,