MyDatagramSocketFactory.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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.net.InetSocketAddress;
  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. if (port > 1023) {
  15. socket = new DatagramSocket();
  16. socket.bind(new InetSocketAddress(port));
  17. } else if (Device.isPPInstalled()) {
  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. injectImpl(impl, socket);
  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 injectImpl(DatagramSocketImpl impl, DatagramSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  45. Field implField = socket.getClass().getDeclaredField("impl");
  46. implField.setAccessible(true);
  47. implField.set(socket, impl);
  48. }
  49. private void setBound(DatagramSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  50. Field boundField = socket.getClass().getDeclaredField("isBound");
  51. boundField.setAccessible(true);
  52. boundField.set(socket, true);
  53. }
  54. }