/ JavaTest.java
JavaTest.java
1 // vim: tabstop=8 shiftwidth=4 softtabstop=4 noexpandtab 2 import java.net.InetAddress; 3 import java.net.UnknownHostException; 4 import java.nio.ByteBuffer; 5 6 import fr.free.miniupnp.libnatpmp.NatPmp; 7 import fr.free.miniupnp.libnatpmp.NatPmpResponse; 8 9 class JavaTest { 10 public static void main(String[] args) { 11 NatPmp natpmp = new NatPmp(); 12 13 natpmp.sendPublicAddressRequest(); 14 NatPmpResponse response = new NatPmpResponse(); 15 16 int result = -1; 17 for(;;) { 18 result = natpmp.readNatPmpResponseOrRetry(response); 19 if (result == 0) break; 20 if (result != -100) { // -100 = NATPMP_TRYAGAIN 21 String errorString = String.format("NATPMP error %d", result); 22 throw new RuntimeException(errorString); 23 } 24 try { 25 Thread.sleep(4000); 26 } catch (InterruptedException e) { 27 //fallthrough 28 } 29 } 30 31 byte[] bytes = intToByteArray(response.addr); 32 33 try { 34 InetAddress inetAddress = InetAddress.getByAddress(bytes); 35 System.out.println("Public address is " + inetAddress); 36 } catch (UnknownHostException e) { 37 throw new RuntimeException(e); 38 } 39 } 40 41 public static final byte[] intToByteArray(int value) { 42 return new byte[] { 43 (byte)value, 44 (byte)(value >>> 8), 45 (byte)(value >>> 16), 46 (byte)(value >>> 24)}; 47 } 48 }