LocalIP = GetAllAdaptersIPAddress(); Task.Run(() => { try { //接收广播 UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, 6789)); 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 { using (UdpClient udpClient = new UdpClient(new IPEndPoint(LocalIP, 6789)) { }) { IPEndPoint broadcastEP = new IPEndPoint(IPAddress.Broadcast, 6789); 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;
}
标签:通讯,udpClient,ip,虚拟机,网卡,IPEndPoint,new,IPAddress From: https://www.cnblogs.com/QJZY/p/18419526