source code - STUNUtility.java
Important Note - Rename the above download to STUNUtility.java, my blog tool lowercases all files when I upload them, and java will complain when you compile if uncorrected.
Here’s the long overdue part 2 of the nat traveral post. Crossing NAT’s souds much more difficult than it is in reality. After doing lot’s of research and testing different libraries, I discovered Stun4J. The library works really well, but It’s API was a little difficult for me to just jump straight into. So I did what any programmer should do, I read the source code =) !
I made a small wrapper class that makes using Stun4J Really Really Really Easy. Long story short you can jump a NAT in about 3 lines of code! I wish someone game me this !!!!! The class is called STUNUtility and there is a sample main function that will find your computers NAT mapping. After you find this NAT mapping, computers outside your LAN can connect to the returned public IP and public Port. This library only works on 2 of the 3 major types of NAT’s though. I’ve been unable to figure out how to traverse symmetric NAT’s and would appreciate any ideas for help if you know (other than proxy servers)!
Before you run STUNUtility, make sure you have Stun4J.jar in your java classpath. Unfortunately, Stun4J doesn’t let you download a jar file (please correct me if this is wrong), so in order to get this to work I checked out their cvs code and compiled it with ant. You can find the Stun4J cvs and compile it yourself or download pre-compiled Stun4J.jar that I created for myself.
Here’s the main function, and the comments should pretty much explain everything.
/**
* Demo class to find your NAT routing information.
*/
public static void main(String[] args) {
try {
//this is apublic stun server. It might go down after posting this, so you should really setup your own.
String stunServerAddress = new String("stun.xten.net");
//this is the port that most stun services run on
int stunServerPort = 3478;
//this is the port your program wants to be able to use.
//The stun program will find the NAT mapping of this port,
//and find the public IP address and port number that internet users
//can connect to you with.
int aLocalPortYouWantToUse = 2525;
//create a stun utility tool (makes stun4j a little easier)
STUNUtility stun = new STUNUtility(stunServerAddress, stunServerPort, aLocalPortYouWantToUse);
//talk to the stun server and figure out the NAT information
stun.performSTUNLookup();
//now print out the info that users outside the internet can use to connect to you.
logger.info("Internet users can connect to my IP address " + stun.getPublicIP() + " and port " + stun.getPublicPort());
} catch (Exception e) {
logger.severe("Failed to lookup NAT information via STUN: " + e.getMessage());
}
}