JavaTest.java 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import java.net.InetAddress;
  2. import java.net.UnknownHostException;
  3. import java.nio.ByteBuffer;
  4. import fr.free.miniupnp.libnatpmp.NatPmp;
  5. import fr.free.miniupnp.libnatpmp.NatPmpResponse;
  6. class JavaTest {
  7. public static void main(String[] args) {
  8. NatPmp natpmp = new NatPmp();
  9. natpmp.sendPublicAddressRequest();
  10. NatPmpResponse response = new NatPmpResponse();
  11. int result = -1;
  12. do{
  13. result = natpmp.readNatPmpResponseOrRetry(response);
  14. try {
  15. Thread.sleep(4000);
  16. } catch (InterruptedException e) {
  17. //fallthrough
  18. }
  19. } while (result != 0);
  20. byte[] bytes = intToByteArray(response.addr);
  21. try {
  22. InetAddress inetAddress = InetAddress.getByAddress(bytes);
  23. System.out.println("Public address is " + inetAddress);
  24. } catch (UnknownHostException e) {
  25. throw new RuntimeException(e);
  26. }
  27. }
  28. public static final byte[] intToByteArray(int value) {
  29. return new byte[] {
  30. (byte)value,
  31. (byte)(value >>> 8),
  32. (byte)(value >>> 16),
  33. (byte)(value >>> 24)};
  34. }
  35. }