MyDatagramSocketFactory.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.setReuseAddress(true);
  17. socket.bind(new InetSocketAddress(port));
  18. } else if (Device.isPPInstalled()) {
  19. FileDescriptor fd = new PrivilegedPort(TYPE.UDP, port).getFD();
  20. socket = new DatagramSocket();
  21. try {
  22. DatagramSocketImpl impl = getImpl(socket);
  23. injectFD(fd, impl);
  24. injectImpl(impl, socket);
  25. setBound(socket);
  26. } catch (NoSuchFieldException e) {
  27. } catch (IllegalAccessException e) {
  28. } catch (IllegalArgumentException e) {
  29. }
  30. }
  31. return socket;
  32. }
  33. private DatagramSocketImpl getImpl(DatagramSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  34. Field implField = socket.getClass().getDeclaredField("impl");
  35. implField.setAccessible(true);
  36. return (DatagramSocketImpl) implField.get(socket);
  37. }
  38. private void injectFD(FileDescriptor fd, DatagramSocketImpl impl) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  39. Class<?> plainDatagramSocketImplClazz = impl.getClass();
  40. Class<?> datagramSocketImplClazz = plainDatagramSocketImplClazz.getSuperclass();
  41. Field fdField = datagramSocketImplClazz.getDeclaredField("fd");
  42. fdField.setAccessible(true);
  43. fdField.set(impl, fd);
  44. }
  45. private void injectImpl(DatagramSocketImpl impl, DatagramSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  46. Field implField = socket.getClass().getDeclaredField("impl");
  47. implField.setAccessible(true);
  48. implField.set(socket, impl);
  49. }
  50. private void setBound(DatagramSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
  51. Field boundField = socket.getClass().getDeclaredField("isBound");
  52. boundField.setAccessible(true);
  53. boundField.set(socket, true);
  54. }
  55. }