码迷,mamicode.com
首页 > Windows程序 > 详细

C# upnp

时间:2016-04-12 14:18:41      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

//获取Host Name
var name = Dns.GetHostName();
Console.WriteLine("用户:" + name);
//从当前Host Name解析IP地址,筛选IPv4地址是本机的内网IP地址。
var ipv4 = Dns.GetHostEntry(name).AddressList.Where(i => i.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault();
Console.WriteLine("内网IP:" + ipv4);
Console.WriteLine("设置UPnP");
//UPnP绑定信息
var eport = 8733;
var iport = 8733;
var description = "Mgen测试";
//创建COM类型
var upnpnat = new UPnPNAT();
var mappings = upnpnat.StaticPortMappingCollection;
//错误判断
if (mappings == null)
{
Console.WriteLine("没有检测到路由器,或者路由器不支持UPnP功能。");
return;
}
//添加之前的ipv4变量(内网IP),内部端口,和外部端口
mappings.Add(eport, "TCP", iport, ipv4.ToString(), true, description);

Console.WriteLine("外部端口:{0}", eport);
Console.WriteLine("内部端口:{0}", iport);

//外网IP变量
string eip;
//正则
var regex = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";
using (var webclient = new WebClient())
{
var rawRes = webclient.DownloadString("http://checkip.dyndns.org/");
eip = Regex.Match(rawRes, regex).Value;
}
Console.WriteLine("外网IP:" + eip);

C# upnp

标签:

原文地址:http://www.cnblogs.com/Logan626/p/5382413.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!