123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- use Getopt::Std;
- use Socket;
-
- getopts('quf:s:');
- if (defined($opt_f)) {
- unless (open(F, $opt_f)) {
- print STDERR "open: $opt_f: $!\n";
- } else {
- while (<F>) {
- next if /^\s*
- ($mac, $ip) = split;
- next if !defined($mac) or $mac eq '';
- next if defined($opt_s) and (!/$opt_s/);
- if (!defined($ip) or $ip eq '' or !$opt_u) {
- &send_broadcast_packet($mac);
- } else {
- &send_unicast_packet($mac, $ip);
- }
- }
- close(F);
- }
- }
- while (@ARGV) {
- send_broadcast_packet(shift(@ARGV));
- }
-
- sub send_broadcast_packet {
- ($mac) = @_;
-
- if ($mac !~ /^[\da-f]{2}:[\da-f]{2}:[\da-f]{2}:[\da-f]{2}:[\da-f]{2}:[\da-f]{2}$/i) {
- print STDERR "Malformed MAC address $mac\n";
- return;
- }
-
- $mac =~ tr/://d;
-
- $magic = ("\xff" x 6) . (pack('H12', $mac) x 16);
-
- socket(S, PF_INET, SOCK_DGRAM, getprotobyname('udp'))
- or die "socket: $!\n";
-
- setsockopt(S, SOL_SOCKET, SO_BROADCAST, 1)
- or die "setsockopt: $!\n";
-
- if (!$opt_q) {
- print "Sending wakeup packet to MAC address $mac";
- print " ($ip)" if (defined($ip));
- print "\n";
- }
- defined(send(S, $magic, 0, sockaddr_in(0x2fff, INADDR_BROADCAST)))
- or print STDERR "send: $!\n";
- close(S);
- }
-
- sub send_unicast_packet {
- ($mac, $ip) = @_;
-
- if (!defined($iaddr = inet_aton($ip))) {
- print STDERR "Cannot resolve $ip\n";
- return;
- }
- if ($mac !~ /^[\da-f]{2}:[\da-f]{2}:[\da-f]{2}:[\da-f]{2}:[\da-f]{2}:[\da-f]{2}$/i) {
- print STDERR "Malformed MAC address $mac\n";
- return;
- }
-
- system("arp -s $ip $mac") == 0
- or print STDERR "Warning: arp command failed, you need to be root\n";
-
- $mac =~ tr/://d;
-
- $magic = ("\xff" x 6) . (pack('H12', $mac) x 16);
-
- socket(S, PF_INET, SOCK_DGRAM, getprotobyname('udp'))
- or die "socket: $!\n";
-
- print "Sending wakeup packet to $ip at MAC address $mac\n" if (!$opt_q);
- defined(send(S, $magic, 0, sockaddr_in(0x2fff, $iaddr)))
- or print STDERR "send: $!\n";
- close(S);
- }
|