首选引用以下两个:
using System.Net;
using System.Net.Sockets;
//获取机机IP地址:
IPHostEntry ihe = Dns.GetHostByName(Dns.GetHostName());
IPAddress myself = ihe.AddressList[0];
//发送消息
UdpClient udpClient = new UdpClient(Ip地址,端口);
Byte[] sendBytes = Encoding.UTF8.GetBytes("信息内容" );
udpClient.Send(sendBytes, sendBytes.Length); //发送消息
//侦听消息
UdpClient receivingUdpClient = new UdpClient(侦听端口);
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
while (true) //循环扫描
{
try
{
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint); //获取接受到的信息,传的时候是以Byte[]来传的,所以接受时也要用Byte
string stripaddress = RemoteIpEndPoint.Address.ToString(); //发送方IP地址
string strPort=RemoteIpEndPoint.Port.ToString(); //发送方端口
}
}