| by SuperBonBon |
|
UPNP NAT mappings
UPNPLib and automatic NAT mappings > IGD explained
UPNPLib and automatic NAT mappings
The library provides an implementation of an Internet Gateway Device. With this class you can easily, open/close/check status of NAT ports mappings for all IGD UPNP devices on your network.
IGD explained
The class to use is net.sbbi.upnp.impls.InternetGatewayDevice. Here is a small code snipet (maps port 9090 for TCP on first IGD found and close immediatly the port) to see it in action :
int discoveryTimeout = 5000; // 5 secs to receive a response from devices
try {
InternetGatewayDevice[] IGDs = InternetGatewayDevice.getDevices( discoveryTimeout );
if ( IGDs != null ) {
// let's the the first device found
InternetGatewayDevice testIGD = IGDs[0];
System.out.println( "Found device " + testIGD.getIGDRootDevice().getModelName() );
// now let's open the port
String localHostIP = InetAddress.getLocalHost().getHostAddress();
// we assume that localHostIP is something else than 127.0.0.1
boolean mapped = testIGD.addPortMapping( "Some mapping description",
null, 9090, 9090,
localHostIP, 0, "TCP" );
if ( mapped ) {
System.out.println( "Port 9090 mapped to " + localHostIP );
// and now close it
boolean unmapped = testIGD.deletePortMapping( null, 9090, "TCP" );
if ( unmapped ) {
System.out.println( "Port 9090 unmapped" );
}
}
}
} catch ( IOException ex ) {
// some IO Exception occured during communication with device
} catch( UPNPResponseException respEx ) {
// oups the IGD did not like something !!
}
As you can see the code is quite easy to write.






