MyDatagramSocketFactory.java 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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.isPPInstalled()) {
  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. } catch (NoSuchFieldException e) {
  22. } catch (IllegalAccessException e) {
  23. } catch (IllegalArgumentException e) {
  24. }
  25. }
  26. return socket;
  27. }
  28. private DatagramSocketImpl getImpl(DatagramSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  29. Field implField = socket.getClass().getDeclaredField("impl");
  30. implField.setAccessible(true);
  31. return (DatagramSocketImpl) implField.get(socket);
  32. }
  33. private void injectFD(FileDescriptor fd, DatagramSocketImpl impl) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  34. Class<?> plainDatagramSocketImplClazz = impl.getClass();
  35. Class<?> datagramSocketImplClazz = plainDatagramSocketImplClazz.getSuperclass();
  36. Field fdField = datagramSocketImplClazz.getDeclaredField("fd");
  37. fdField.setAccessible(true);
  38. fdField.set(impl, fd);
  39. }
  40. }