无法在我的C#应用​​程序中添加静态端口映射 [英] Can't add a static port mapping in my c# application

查看:157
本文介绍了无法在我的C#应用​​程序中添加静态端口映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的C#应用​​程序中添加新的静态端口映射。因为我的应用程序是作为服务器运行的,所以我希望它在端口8000上侦听。

I'm trying to add new static port mapping in my c# application. Because my application runs as a server and i want its to listen on the port 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");

但它不起作用!,以下是例外:

but it doesn't work!, The exception was the following :


对象引用未设置为对象的实例。

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

推荐答案

您需要将映射设置为新实例:

You need to set mappings to a new instance:

例如:

var mappings = new List<Mapping>();

然后您可以致电:

mappings.Add(8000, "TCP", 8000, "192.168.1.100", true, "Local Web Server");

来自您的编辑:

upnpnat.StaticPortMappingCollection; // this is your problem.  

该集合返回为空。因此,您不能添加到集合中。

The collection is coming back as null. Therefore you cannot add to the collection.

您可能需要做:

NATUPNPLib.IStaticPortMappingCollection mappings = new StaticPortMappingCollection();

摘自Codesleuth的评论:


我相信答案是他的路由器未配置为UPnP网关,或者他没有权限。如果这些情况中的任何一种为true,则StaticPortMappingCollection为null。建议您将其编辑为答案,因为无论如何您都有正确的错误原因。首先检查null是处理错误的唯一方法

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

这篇关于无法在我的C#应用​​程序中添加静态端口映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆