We scoured the web for such a library and found little help. There were expensive commercial solutions, bits of concept code found on forums, and an especially complicated API from Microsoft. And none of these even seemed to know about NAT-PMP!
So we took another look at the MiniUPnP project. After all, this is what TCMPortMapper uses. And we discovered it's mission statement is exactly what we're looking for:
An open source library with a commercial friendly license, providing the simplest library possible, with the smallest footprint and no dependencies to other libraries such as XML parsers or HTTP implementations.
Sounds perfect! And it's in pure ANSI C. Does this mean it works on Windows???
Yes and no. The miniupnp part of the library was Windows compatible. But you had to compile it using MinGW. Basically, the MinGW project provides Windows implementations of common unix libraries so that many unix projects can be compiled into a single windows executable. So we toiled on that for a bit, and finally figured out how to compile the library into an exe and/or dll. Next was the libnatpmp part of the library. This wasn't Windows compatible yet, so we had to write a bit of code. (By the way, traversing the windows registry in pure C is a lot of fun. You should try it sometime when you're looking to ruin your day.) So now the official libnatpmp code is Windows compatible, and comes with instructions on compiling for Windows. I believe the miniupnpc download comes with the actual dll now too!
And with that out of the way, we could port TCMPortMapper to a .Net library. Which meant all kinds of fun P/Invoking and marshaling data back and forth from managed to unmanaged code. And now, a few weeks later, we're finally done. (Thank God)
So today, we're releasing the DotNetPortMapper. It retains pretty much the same API as it's Mac counter-part. And here's pretty much all you have to do to use it:
private void Form1_Load()
PortMapping pm = new PortMapping(localPort, publicPort,
private void Form1_FormClosing()
And that's it. If UPnP or NAT-PMP is available on your local network, the port mapping will be added, and also properly removed when your app terminates.
Also included in the project is a sample "Port Map" application. This app shows how to add/remove port mappings, and how to do other more advanced tasks such as obtaining your external IP address, and learning the router manufacturer. A picture is a thousand words:
DotNetPortMapper Google Code Page
Browse PortMapper Source Code
Download Project (using subversion)
If you're unfamiliar with subversion, it's really easy to use. (And as a developer it's very important to learn and use source control systems.) Windows users should have a look at Tortoise SVN. Mac users may want to look at Versions.