我正在尝试在我的c#应用程序中添加新的静态端口映射.因为我的应用程序作为服务器运行,我希望它在端口8000上监听.
NATUPNPLib.UPnPNATClass upnpnat = new NATUPNPLib.UPnPNATClass(); NATUPNPLib.IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection; mappings.Add(8000,"TCP",8000,"192.168.1.100",true,"Local Web Server");
但它不起作用!,例外情况如下:
Object reference not set to an instance of an object.
有人可以帮我吗?
这就是我正在做的事:http://pietschsoft.com/post/2009/02/05/NET-Framework-Communicate-through-NAT-Router-via-UPnP.aspx
解决方法
您需要将映射设置为新实例:
例如:
var mappings = new List<Mapping>();
然后你可以打电话:
mappings.Add(8000,"Local Web Server");
从你的编辑:
upnpnat.StaticPortMappingCollection; // this is your problem.
该集合将返回null.因此您无法添加到集合中.
你可能必须这样做:
NATUPNPLib.IStaticPortMappingCollection mappings = new StaticPortMappingCollection();
来自Codesleuth的评论:
I believe the answer is that his router isn’t configured as a UPnP gateway,or that he has no permissions. The StaticPortMappingCollection is null if either of those cases are true. I suggest you edit this into your answer as you’ve got the right reason for the error anyway. Checking for null first is the only way to deal with the error