MyDatagramSocketFactory.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 de.tudarmstadt.informatik.hostage.system.Device;
  8. import de.tudarmstadt.informatik.hostage.system.PrivilegedPort;
  9. import de.tudarmstadt.informatik.hostage.system.PrivilegedPort.TYPE;
  10. public class MyDatagramSocketFactory {
  11. public DatagramSocket createDatagramSocket(int port) throws IOException {
  12. DatagramSocket socket = null;
  13. if (port > 1023) {
  14. socket = new DatagramSocket(port);
  15. } else if (Device.isPorthackInstalled()) {
  16. FileDescriptor fd = new PrivilegedPort(TYPE.UDP, port).getFD();
  17. socket = new DatagramSocket();
  18. try {
  19. DatagramSocketImpl impl = getImpl(socket);
  20. injectFD(fd, impl);
  21. setBound(socket);
  22. } catch (NoSuchFieldException e) {
  23. } catch (IllegalAccessException e) {
  24. } catch (IllegalArgumentException e) {
  25. }
  26. }
  27. return socket;
  28. }
  29. private DatagramSocketImpl getImpl(DatagramSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  30. Field implField = socket.getClass().getDeclaredField("impl");
  31. implField.setAccessible(true);
  32. return (DatagramSocketImpl) implField.get(socket);
  33. }
  34. private void injectFD(FileDescriptor fd, DatagramSocketImpl impl) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  35. Class<?> plainDatagramSocketImplClazz = impl.getClass();
  36. Class<?> datagramSocketImplClazz = plainDatagramSocketImplClazz.getSuperclass();
  37. Field fdField = datagramSocketImplClazz.getDeclaredField("fd");
  38. fdField.setAccessible(true);
  39. fdField.set(impl, fd);
  40. }
  41. private void setBound(DatagramSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  42. Field boundField = socket.getClass().getDeclaredField("isBound");
  43. boundField.setAccessible(true);
  44. boundField.set(socket, true);
  45. }
  46. }