C# udp通讯 多网卡/虚拟机指定某个网卡通讯

LocalIP = GetAllAdaptersIPAddress();
if (udpClient == null) { udpClient = new UdpClient(new IPEndPoint(LocalIP, 5687)); } Task.Run(()
=> { try { //接收广播while (true) { IPEndPoint AnyIP = new IPEndPoint(IPAddress.Any, 0); byte[] data = udpClient.Receive(ref AnyIP); } } catch (Exception e) { ShowMsg(e.Message); LogError(e.Message); } Thread.Sleep(10000); }); Task.Run(() => { try {
IPEndPoint broadcastEP = new IPEndPoint(IPAddress.Broadcast, 5687);
while (true) // 无限循环发送
{
// 发送广播
udpClient.SendAsync(sendBytes1, sendBytes1.Length, broadcastEP);

Thread.Sleep(2000);
}
} catch (Exception e) { ShowMsg(e.Message); LogError(e.Message); } Thread.Sleep(10000); });
//获取本机IP

public static IPAddress GetAllAdaptersIPAddress()
{
foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
{
if (adapter.Description.Contains("Loopback")) continue;//跳过 环回地址127.0.0.1


if (adapter.OperationalStatus == OperationalStatus.Up) //连接上的网口
{
var addresses = adapter.GetIPProperties().UnicastAddresses;


foreach (var ip in addresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
if(ip.Address.ToString().Contains("192.168.8"))
{
return ip.Address;
}

}
}
}
}
return null;

}

 

 

if (udpClient == null){    udpClient = new UdpClient(new IPEndPoint(LocalIP, 5687));}
posted @ 2024-09-18 23:02  奇迹之耀  阅读(111)  评论(0编辑  收藏  举报