微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法在我的c#应用程序中添加静态端口映射

我正在尝试在我的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

原文地址:https://www.jb51.cc/csharp/99562.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐