MyDatagramSocketFactory.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package de.tudarmstadt.informatik.hostage.net;
  2. import java.io.FileDescriptor;
  3. import java.io.IOException;
  4. import java.lang.reflect.Field;
  5. import java.net.DatagramSocket;
  6. import java.net.DatagramSocketImpl;
  7. import java.util.NoSuchElementException;
  8. import de.tudarmstadt.informatik.hostage.system.Device;
  9. import de.tudarmstadt.informatik.hostage.system.PrivilegedPort;
  10. import de.tudarmstadt.informatik.hostage.system.PrivilegedPort.TYPE;
  11. public class MyDatagramSocketFactory {
  12. public DatagramSocket createDatagramSocket(int port) throws IOException {
  13. DatagramSocket socket = null;
  14. //port = 1024;
  15. if (port > 1023) {
  16. socket = new DatagramSocket(port);
  17. } else if (Device.isPorthackInstalled()) {
  18. FileDescriptor fd = new PrivilegedPort(TYPE.UDP, port).getFD();
  19. socket = new DatagramSocket();
  20. try {
  21. DatagramSocketImpl impl = getImpl(socket);
  22. injectFD(fd, impl);
  23. injectLocalPort(port, impl);
  24. setBound(socket);
  25. } catch (NoSuchFieldException e) {
  26. } catch (IllegalAccessException e) {
  27. } catch (IllegalArgumentException e) {
  28. }
  29. }
  30. return socket;
  31. }
  32. private DatagramSocketImpl getImpl(DatagramSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  33. Field implField = socket.getClass().getDeclaredField("impl");
  34. implField.setAccessible(true);
  35. return (DatagramSocketImpl) implField.get(socket);
  36. }
  37. private void injectFD(FileDescriptor fd, DatagramSocketImpl impl) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  38. Class<?> plainDatagramSocketImplClazz = impl.getClass();
  39. Class<?> datagramSocketImplClazz = plainDatagramSocketImplClazz.getSuperclass();
  40. Field fdField = datagramSocketImplClazz.getDeclaredField("fd");
  41. fdField.setAccessible(true);
  42. fdField.set(impl, fd);
  43. }
  44. private void injectLocalPort(int port , DatagramSocketImpl impl)
  45. throws NoSuchElementException, NoSuchFieldException, IllegalAccessException {
  46. Class<?> plainDatagramSocketImplClazz = impl.getClass();
  47. Class<?> datagramSocketImplClazz = plainDatagramSocketImplClazz.getSuperclass();
  48. Field localPortField = datagramSocketImplClazz.getDeclaredField("localPort");
  49. localPortField.setAccessible(true);
  50. localPortField.set(impl, port);
  51. }
  52. private void setBound(DatagramSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  53. Field boundField = socket.getClass().getDeclaredField("isBound");
  54. boundField.setAccessible(true);
  55. boundField.set(socket, true);
  56. }
  57. }