[yoy - Why-O-Why]yoy - “Why-O-Why”

» frame | home browse filter search | refresh | log on

  printed donderdag 23 mei 2013 2:35:43 from www.yoy.be

how-to
Comment...
Add another
Add child
Edit
Move
Delete
Add token
Add reference

Delphi code to send a Wake-up on LAN signal

Yes, it's that easy!

unit un_WakeUpOnLAN;

interface

type
  TMACAddress=array[0..5] of byte;

function MACAddressFromStr(x:string):TMACAddress;
procedure SendWakeUpOnLAN(Address:TMACAddress);

implementation

uses SysUtils, WinSock;

function MACAddressFromStr(x:string):TMACAddress;
var
  i,j,b:integer;
begin
  j:=0;
  for i:=1 to Length(x) do
    if x[i] in ['0'..'9','A'..'F','a'..'f'] then
     begin
      if byte(x[i])>$40 then b:=9 else b:=0;
      if j>12 then raise Exception.Create('MAC Address too long');
      if (j and 1)=0 then
        Result[j div 2]:=(b+(byte(x[i]) and $F)) shl 4
      else
        Result[j div 2]:=Result[j div 2] or (b+(byte(x[i]) and $F));
      inc(j);
    end;
  if j<12 then raise Exception.Create('MAC Address too short');
end;

procedure SendWakeUpOnLAN(Address:TMACAddress);
var
  s:TSocket;
  i:integer;
  a:TSockAddr;
  d:array[0..16] of TMACAddress;
const
  x:TMACAddress=($FF,$FF,$FF,$FF,$FF,$FF);
begin
  d[0]:=x;
  for i:=1 to 16 do d[i]:=Address;
  a.sin_family:=AF_INET;
  a.sin_port:=htons(0);
  a.sin_addr.S_addr:=INADDR_BROADCAST;
  s:=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
  if s=INVALID_SOCKET then
    raise Exception.Create(SysErrorMessage(WSAGetLastError));
  try
    if (connect(s,a,SizeOf(a))=SOCKET_ERROR)
      or (setsockopt(s,SOL_SOCKET,SO_BROADCAST,PChar(@i),4)=SOCKET_ERROR)
      or (sendto(s,d[0],102,0,a,SizeOf(a))=SOCKET_ERROR) then
      raise Exception.Create(SysErrorMessage(WSAGetLastError));
  finally
    closesocket(s);
  end;
end;

var
  WSAData:TWSAData;

initialization
  WSAStartup($0101, WSAData);
finalization
  WSACleanup;

end.

location: Application Development > Programming Languages > Object Pascal > Delphi
created: 29/03/2011 8:28:46 « modified: 29/03/2011 9:42:06 (diff) weight: 0

children, tokens, references