I have a windows service application that runs as Local System, and I want to be able to use NATUPNPLib to create port forwards for the (multiple and dynamic) ports it needs. I have been experimenting with various other UPnP Libraries that all fail, which is why when I tested NATUPNPLib and it worked in my test application I was pretty excited.
The problem comes when putting the same code into my service that is running under the local system account. I always get the error The owner of the PerUser subscription is not logged on to the system specified (Exception from HRESULT: 0x80040210)
. There is next to no documentation for this library or these errors (in fact, you need to generate the interops in VS2008 for .NET 3.5 as VS2010 always does them wrong). What I have gathered from the error itself is that the Local System user doesn't have the rights to access UPnP.
Changing the user account the service runs as is non-trivial, aside from the fact that the app is auto-updating and designed to need very little configuration.
Has anyone got NATUPNPLib to work under Local System or found a decent UPnP library that I can use in C#?
Here is the code I am using, couldn't really be much simpler!
/// <summary>
/// Use NATUPNPLib to try and open a port forward
/// </summary>
/// <param name="intPortNumber">The port to open</param>
/// <param name="strFriendlyName">Friendly name for the service</param>
/// <returns>Boolean indicating whether the forward worked</returns>
public static bool OpenUPnP(int intPortNumber, string strFriendlyName)
{
try {
NATUPNPLib.UPnPNATClass upnpnat = new NATUPNPLib.UPnPNATClass();
upnpnat.StaticPortMappingCollection.Add(intPortNumber, "TCP", intPortNumber, GetListenIP().ToString(), true, strFriendlyName);
Database.AddLog("Opened port " + intPortNumber + " for " + strFriendlyName, "networking");
return true;
}
catch(Exception e) {
Database.AddLog("Unable foward port " + intPortNumber + " for " + strFriendlyName + ": Exception - " + e.Message, "networking", "warn");
return false;
}
}
Which is part of Networking.cs
Turns out, this is more a problem of implementation of UPnP on BT's Home Hub 3. With extended security on it returns this spurious error code to NATUPnPLib and without it on it still errors on certain ports.
You can run UPnP commands under local system, as long as your router isn't a pile of poo.
User contributions licensed under CC BY-SA 3.0