Page 1 of 1
Forum

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.

Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!



Share:
Notifications
Clear all

[Solved] Sending a Wake On LAN Packet the easiest way in Lazarus Pascal ...

1 Posts
1 Users
0 Reactions
235 Views
 Hans
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2858
Topic starter  

In the past I had a Wake on LAN function, based on Synapse. At the time it was the easiest way to do it without having to dig in code too much.

However, I found myself in the situation that I needed a more reliable and smaller implementation that was Apple App Store "safe" as well. Anywho, for those needing a Wake On LAN function in Lazarus (I suspect this works for Linux and Windows as well - haven't tested it), here ya have a simple function that does just that 

// Example on calling the function
SendMagicPacket('28:cf:b3:2c:f5:b7',WOL_DEFAULT_PORT,WOL_DEFAULT_MASK);

The function needs the unit "Sockets":

uses  ... Sockets ...;

Useful to define some default values like

const
  WOL_DEFAULT_PORT   = 9;
  WOL_DEFAULT_MASK   = '255.255.255.255';

And the function itself

function SendMagicPacket(MACAddress:AnsiString; WOLPort:integer = WOL_DEFAULT_PORT; BroadcastMask: AnsiString = WOL_DEFAULT_MASK):boolean;
var
  Counter             : integer;
  HexMacAddress       : AnsiString;
  MACSegment          : byte;
  WOLPacket           : AnsiString;
  WOLSocket           : LongInt;
  SocketAddress       : sockaddr_in;
  DummySocketOpt      : LongInt;
begin
  Result := false;

  MACAddress := StringReplace(MACAddress, ':', '', [rfReplaceAll]);
  if Length(MACAddress) < 12 then Exit;

  HexMacAddress := '';
  for Counter := 0 to 5 do
    begin
      MACSegment := StrToIntDef('$' + MACAddress[Counter * 2 + 1] + MACAddress[Counter * 2 + 2], 0);
      HexMacAddress := HexMacAddress + AnsiChar(MACSegment);
    end;

  WOLPacket := #$FF + #$FF + #$FF + #$FF + #$FF + #$FF;
  for Counter := 1 to 16 do
    WOLPacket := WOLPacket + HexMacAddress;

  WOLSocket := fpsocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  if WOLSocket<0 then exit;

  DummySocketOpt := 1;
  if (fpsetsockopt(WOLSocket, SOL_SOCKET, SO_BROADCAST, @DummySocketOpt, SizeOf(DummySocketOpt)) < 0) then
    begin
      CloseSocket(WOLSocket);
      exit;
    end;

  FillByte(SocketAddress,SizeOf(SocketAddress),0);
  SocketAddress.sin_family := AF_INET;
  SocketAddress.sin_port   := htons(WOLPort);
  SocketAddress.sin_addr   := StrToNetAddr(BroadcastMask);

  fpsendto(WOLSocket, @WOLPacket[1], Length(WOLPacket), 0, @SocketAddress, sizeof(sockaddr_in));

  CloseSocket(WOLSocket);
end;

   
ReplyQuote
Share: