Guest User

Untitled

a guest
Jan 23rd, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. // Propossed solution for Assignment#3: Wake-On-LAN Server - 5662.blogspot.com
  2. import java.io.*;
  3. import java.net.*;
  4. import java.util.*;
  5.  
  6. class WolServer extends Thread {
  7. static Hashtable<String,Date> list = new Hashtable<String,Date>();
  8. static InetAddress ip = null;
  9.  
  10. public static void wakeOnLan(String mac, InetAddress ip) {
  11. DatagramSocket ds1 = null;
  12. try { ds1 = new DatagramSocket(); } catch(SocketException e) {System.err.println("Socket error"); }
  13. String[] addr=mac.split(":");
  14. byte[] buffer = new byte[102];
  15. for(int i=0;i<6; i++) {
  16. buffer[i]=-1; // -1 == 0xff
  17. for(int j=0;j<16; j++) buffer[(j+1)*6+i]=(byte) ((Character.digit(addr[i].charAt(0), 16) << 4)
  18. + Character.digit(addr[i].charAt(1), 16));
  19. }
  20. DatagramPacket dp = new DatagramPacket(buffer,102,ip,7);
  21. try { ds1.send(dp); } catch (IOException e) {System.err.println("Cannot send magic packet"); }
  22. // not asked for: list.remove(mac);
  23. }
  24.  
  25. public void run() { //check if it is the time
  26. while(true) {
  27. Date now = new Date();
  28. for(String key : list.keySet()) if(list.get(key).toString().equals(now.toString())) wakeOnLan(key, ip);
  29. try {sleep(1000); } catch (InterruptedException e) {}
  30. }
  31. }
  32.  
  33. public static void main(String s[]) throws SocketException, IOException{
  34. DatagramSocket ds = new DatagramSocket(2323);
  35. byte[] buffer = new byte[1024];
  36. Thread t = new WolServer();
  37. t.start();
  38. while(true) { // it is a server!!
  39. DatagramPacket dp = new DatagramPacket(buffer,buffer.length);
  40. ds.receive(dp);
  41. if(dp.getLength()<10) for(String key : list.keySet()) System.out.println(key + " " + list.get(key));
  42. else { // add to the list
  43. String line = new String(dp.getData(),0,dp.getLength()-1); // remove new-line char
  44. if(line.matches("([0-9a-f]{2}:){5}[0-9a-f]{2}\\s\\d+.\\d+.\\d+.\\d+\\s\\d+")) try { // correct format, then Ok
  45. Scanner sc = new Scanner(line);
  46. String mac = sc.next();
  47. ip = InetAddress.getByName(sc.next());
  48. long time = sc.nextLong();
  49. if(time==0) list.remove(mac);
  50. else list.put(mac, new Date( time*1000 + System.currentTimeMillis() ));
  51. dp.setData("Ok\n".getBytes());
  52. ds.send(dp);
  53. } catch(Exception e) { dp.setData("Error\n".getBytes()); ds.send(dp); } // Bad parameters error
  54. else {dp.setData("Error\n".getBytes()); ds.send(dp); } // Bad format => Error
  55. }
  56. }
  57. }
  58. }
Add Comment
Please, Sign In to add comment