首選引用以下兩個:
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(); //發送方端口
}
}