我已经实现了一个通过广播发送魔术包的功能。 它工作正常,但我想在特殊服务器上收到所有UDP广播请求。 也适用。 但是,如果我尝试读取字节并将字节转换为十六进制(MAC地址),则mac地址将出错。
发送UDP请求:255.255.255.255,MAC =“001a4d5f84f8”
特殊服务器成功接收MAC地址的16倍,但它已更改: 从: 001a4d5f84f8 至: 001a4d5f3f3f
有什么想法吗?
我的职能:
//Send Packets
//------------------------------------------------------
string MAC_ADDRESS = "001a4d5f84f8";
UdpClient UDP = new UdpClient();
try
{
IPAddress IPBCast = IPAddress.Parse("255.255.255.255");
UDP.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
int offset = 0;
byte[] buffer = new byte[512];
//first 6 bytes should be 0xFF
for (int y = 0; y < 6; y++)
buffer[offset++] = 0xFF;
//now repeate MAC 16 times
for (int y = 0; y < 16; y++)
{
int i = 0;
for (int z = 0; z < 6; z++)
{
buffer[offset++] =
byte.Parse(MAC_ADDRESS.Substring(i, 2), NumberStyles.HexNumber);
i += 2;
}
}
UDP.EnableBroadcast = true;
UDP.Send(buffer, 512, new IPEndPoint(IPBCast, 0x1));
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
UDP.Close();
}
//Receive Packets
//------------------------------------------------------
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0x1);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
Console.WriteLine("Ready to receive...");
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}", (StringToHex(stringData)), ep.ToString());
//Convert Received String To Hex
//------------------------------------------------------
public static string StringToHex(string hexstring)
{
var sb = new StringBuilder();
foreach (char t in hexstring)
sb.Append(Convert.ToInt32(t).ToString("x") + " ");
return sb.ToString();
}
答案 0 :(得分:0)
您的问题是Encoding.ASCII.GetString()
。它可以读取使用ASCII编码的字符串,但这不是您要发送的字符串。您必须将字节解码为字节。
如果您希望将结果作为字符串,则可以使用类似
的内容string.Join("", bytes.Select(b => b.ToString("x2")))
此处,bytes
是您要转换为字符串的字节序列。
(如果您不在.Net 4上,则需要在.ToArray()
之后添加Select()
。