开发者

C# Receive UPD Broadcast bytes (Magic WOL Packet) Get Destination Mac

I've implemented a function to send magic packets over a broadcast. It Works fine, but I would like to receive all UDP broadcast requests on a special server. Works as well. But if I try to read the bytes and convert the bytes to hexadecimal (MAC Address) back, the mac address will be wrong.

Send UDP Request开发者_JS百科 to: 255.255.255.255 with MAC = "001a4d5f84f8"

The special server receive successfull 16 times the MAC Address, but it has changed: From: 001a4d5f84f8 To: 001a4d5f3f3f

Any ideas?

My functions:

//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();
}


Your problem is Encoding.ASCII.GetString(). It can read strings encoded using ASCII, but that's not what you're sending. You have to decode the bytes as bytes.

If you want the result as string, you can use something like

string.Join("", bytes.Select(b => b.ToString("x2")))

Here, bytes is a sequence of the bytes you want to convert to string.

(If you're not on .Net 4, you need to add .ToArray() after the Select().)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜