不绑定IP只要一个网段就可以

This commit is contained in:
xu 2020-03-27 17:01:24 +08:00
parent ebf81ea8a1
commit 717e77f6be

View File

@ -5,6 +5,9 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
@ -20,7 +23,7 @@ namespace Plane.CommunicationManagement
public TcpConnection Connection = null;
public bool CommOK = false;
private const string MODULE_IP = "192.168.199.51"; // "192.168.199.51";
private const string LOCAL_IP = "192.168.199.50"; //"192.168.199.50";
// private const string LOCAL_IP = "192.168.199.50"; //"192.168.199.50";
private const int PORT = 9551;
private bool _disposed;
public int CommModuleCopterCount = 0;
@ -55,11 +58,94 @@ namespace Plane.CommunicationManagement
Connection?.Close();
}
/*
//获取内网IP
private IPAddress GetInternalIP()
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
foreach (var uni in adapter.GetIPProperties().UnicastAddresses)
{
if (uni.Address.AddressFamily == AddressFamily.InterNetwork)
{
return uni.Address;
}
}
}
return null;
}
/// <summary>
/// 获取本地连接IP地址、无线连接IP地址
/// </summary>
/// <param name="k">0:本地连接1:本地连接12:无线网络连接</param>
/// <returns></returns>
public static IPAddress GetIP(int k)
{
NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
int len = interfaces.Length;
IPAddress[] mip = { IPAddress.Parse("0.0.0.0"), IPAddress.Parse("0.0.0.0"), IPAddress.Parse("0.0.0.0") };
for (int i = 0; i < len; i++)
{
NetworkInterface ni = interfaces[i];
if (ni.Name == "本地连接")
{
IPInterfaceProperties property = ni.GetIPProperties();
foreach (UnicastIPAddressInformation ip in property.UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
mip[0] = ip.Address;
}
}
}
else if (ni.Name == "本地连接2")
{
IPInterfaceProperties property = ni.GetIPProperties();
foreach (UnicastIPAddressInformation ip in property.UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
mip[1] = ip.Address;
}
}
}
else if (ni.Name == "无线网络连接")
{
IPInterfaceProperties property = ni.GetIPProperties();
foreach (UnicastIPAddressInformation ip in property.UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
mip[2] = ip.Address;
}
}
}
}
return mip[k];
}
*/
private async Task ConnectOpenAsync()
{
CommOK = true;
bool bind = await Connection.BindIP(LOCAL_IP);
if (bind)
//不绑定IP也可以通讯有线网络需要设置192.168.199.X网段地址
// string locip = GetIP(0).ToString();
// bool bind = await Connection.BindIP(locip);
// if (bind)
{
try
{