//获取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);