udp广播代码,
private UdpClient m_udpClient;
private IPEndPoint endPoint;
private IPEndPoint m_ipEndPoint;
private IPAddress m_UpdReceiveDataIP;
创建UDP客户端:
public void CreatUDP()
{
m_udpClient = new UdpClient(7055);
endPoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 7055);
SendV();
}
发送消息:
byte[] sendV = Encoding.UTF8.GetBytes(“v”);
m_udpClient.Send(sendV, sendV.Length, endPoint);
接收消息:
字符串:
m_ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] vs = m_udpClient.Receive(ref m_ipEndPoint);
string ReceiveMessage = System.Text.Encoding.Default.GetString(vs);
接收数字:
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] NumArray = m_udpClient .Receive(ref ipEndPoint);
m_Num = (byte)(NumArray [0] & 0xFF);
原理:发送消息:用自己的端口发送给255,255,255,255,7055端口,接收消息:用自己的端口127.0.0.1,7055接收消息。
获取接收消息的ip地址:
m_UpdReceiveDataIP = m_ipEndPoint.Address;
获取自己ip地址接收到自己发送的消息就可以直接获取自己的IP地址。