#!/usr/bin/perl -Tw

# wakeup.pl : Send "Magic Packet(TM)" to "Wake up" Powered off Machine.
# Copyright (C) 1998 Takeshi Ueno <tueno@vio.co.jp>

# Version 0.1

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

# Magic Packet(TM) Technology was developped by Advanced Micro Device,Inc.
# Technical document was published at:
# http://www.amd.com/products/npd/overview/20212d.html

# I referred "sndmagic" program written by Katsuyuki Yumoto.
# c.f. http://www.st.rim.or.jp/~yumo/pub/sndmagic.html

# Usage: wakeup.pl broadcastaddress MACaddress
# broadcastaddress: network broadcast address (ex: 192.168.0.255)
# MACaddress: target machine's MAC address

require 5.003;
use strict;
use Socket;

my ($remote_address, $remote_port, $proto, $pac, $iaddr, $paddr, $macadd,
$macstr, $i);

# Usage
if($ARGV[0] eq "") {
    die "Usage: wakeup.pl broadcastaddress MACaddress\n";
}

if($ARGV[1] eq "") {
    die "Usage: wakeup.pl broadcastaddress MACaddress\n";
}

# MAC address decode
$macadd=$ARGV[1];
$macadd=~s/://g;
if(length($macadd) != 12) {
    die "MAC address ERROR.\n";
}
$macstr=pack("H12", $macadd);

# Magic Packet create
$pac = "\xff\xff\xff\xff\xff\xff";
for($i=0; $i<20;$i++) {
    $pac .=$macstr;
}

# open socket
$remote_address=$ARGV[0];
$remote_port="7";
$proto=getprotobyname('udp');
socket(S, PF_INET, SOCK_DGRAM, $proto) or die "ERROR at open socket: $!";
setsockopt(S, SOL_SOCKET, SO_BROADCAST,1) or die "ERROR at sockopt: $!";

# send Magic Packet
$iaddr=inet_aton($remote_address) or die "ERROR at get broadcast address: $!";
$paddr=sockaddr_in($remote_port,$iaddr) or die "ERROR at make broadcast: $!";
send(S,$pac,0,$paddr) or die "ERROR at send broadcast:$!";

exit(0);
# end
