Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Propossed solution for Assignment#3: Wake-On-LAN Server - 5662.blogspot.com
- import java.io.*;
- import java.net.*;
- import java.util.*;
- class WolServer extends Thread {
- static Hashtable<String,Date> list = new Hashtable<String,Date>();
- static InetAddress ip = null;
- public static void wakeOnLan(String mac, InetAddress ip) {
- DatagramSocket ds1 = null;
- try { ds1 = new DatagramSocket(); } catch(SocketException e) {System.err.println("Socket error"); }
- String[] addr=mac.split(":");
- byte[] buffer = new byte[102];
- for(int i=0;i<6; i++) {
- buffer[i]=-1; // -1 == 0xff
- for(int j=0;j<16; j++) buffer[(j+1)*6+i]=(byte) ((Character.digit(addr[i].charAt(0), 16) << 4)
- + Character.digit(addr[i].charAt(1), 16));
- }
- DatagramPacket dp = new DatagramPacket(buffer,102,ip,7);
- try { ds1.send(dp); } catch (IOException e) {System.err.println("Cannot send magic packet"); }
- // not asked for: list.remove(mac);
- }
- public void run() { //check if it is the time
- while(true) {
- Date now = new Date();
- for(String key : list.keySet()) if(list.get(key).toString().equals(now.toString())) wakeOnLan(key, ip);
- try {sleep(1000); } catch (InterruptedException e) {}
- }
- }
- public static void main(String s[]) throws SocketException, IOException{
- DatagramSocket ds = new DatagramSocket(2323);
- byte[] buffer = new byte[1024];
- Thread t = new WolServer();
- t.start();
- while(true) { // it is a server!!
- DatagramPacket dp = new DatagramPacket(buffer,buffer.length);
- ds.receive(dp);
- if(dp.getLength()<10) for(String key : list.keySet()) System.out.println(key + " " + list.get(key));
- else { // add to the list
- String line = new String(dp.getData(),0,dp.getLength()-1); // remove new-line char
- if(line.matches("([0-9a-f]{2}:){5}[0-9a-f]{2}\\s\\d+.\\d+.\\d+.\\d+\\s\\d+")) try { // correct format, then Ok
- Scanner sc = new Scanner(line);
- String mac = sc.next();
- ip = InetAddress.getByName(sc.next());
- long time = sc.nextLong();
- if(time==0) list.remove(mac);
- else list.put(mac, new Date( time*1000 + System.currentTimeMillis() ));
- dp.setData("Ok\n".getBytes());
- ds.send(dp);
- } catch(Exception e) { dp.setData("Error\n".getBytes()); ds.send(dp); } // Bad parameters error
- else {dp.setData("Error\n".getBytes()); ds.send(dp); } // Bad format => Error
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment