SoFunction
Updated on 2025-03-07

C# network wake-up function implementation


private IPEndPoint point;
private UdpClient client = new UdpClient();
/**
* Wake up remote machine method
 * @param
* mac MAC of the machine to wake up
 * IP
* port udp message sending port
 *
* Abstract: The wake-up method provides magic packet function for network cards, that is, sending 6 FFs in broadcast mode plus 16 passes of the target MAC address
 **/
private void wakeUp(string mac, int port, string ip)
{
    byte[] magicBytes = getMagicPacket(mac);
point = new IPEndPoint((ip), port);//Broadcast mode: 255.255.255.255.255
    try
    {
        (magicBytes, , point);
    }
    catch (SocketException e) { (); }
}

/// <summary>
/// To string to hexadecimal byte array
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] strToHexByte(string hexString)
{
    hexString = (" ", "");
    if (( % 2) != 0)
        hexString += " ";
    byte[] returnBytes = new byte[ / 2];
    for (int i = 0; i < ; i++)
        returnBytes[i] = ((i * 2, 2), 16);
    return returnBytes;
}

/// <summary>
/// Assemble MAC Magic Package
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] getMagicPacket(string macString)
{
    byte[] returnBytes = new byte[102];
    string commandString = "FFFFFFFFFFFF";
    for (int i = 0; i < 6; i++)
        returnBytes[i] = ((i * 2, 2), 16);
    byte[] macBytes = strToHexByte(macString);
    for (int i = 6; i < 102; i++)
    {
        returnBytes[i] = macBytes[i % 6];
    }
    return returnBytes;
}