背景:服务端获取未知客户端IP
误区:
服务端往组播地址发送消息,然后以接收组播的方式接收组播成员的回复无法接到。通过Wireshark抓包可以抓到来自目标客户端的包。发现目标客户端采用UDP单播方式发送 因而服务端接收不到此包。
解决方法:
目标客户端接收到来自服务端的组播信息之后同样以组播的方式回复信息。信息包含客户端IP和其他校验信息
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Client
{
class Program
{
static void Main(string[] args)
{
UdpClient client = new UdpClient();
client.JoinMulticastGroup(IPAddress.Parse("239.255.255.250"));
IPEndPoint multicast = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 37020);
string mess = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Probe><Uuid>0414E4C1-1B08-408F-9442-BC2B6834D29D</Uuid><Types>inquiry</Types></Probe>";
byte[] buf = Encoding.Default.GetBytes(mess);
Thread t = new Thread(new ThreadStart(RecvThread));
t.IsBackground = true;
t.Start();
while (true)
{
client.Send(buf, buf.Length, multicast);
Thread.Sleep(1000);
}
}
static void RecvThread()
{
UdpClient client = new UdpClient(37020);
client.JoinMulticastGroup(IPAddress.Parse("239.255.255.250"));
IPEndPoint multicast = new IPEndPoint(IPAddress.Parse("239.255.255.250"),0);
while (true)
{
byte[] buf = client.Receive(ref multicast);
string msg = Encoding.Default.GetString(buf);
Console.WriteLine(msg);
Console.WriteLine(multicast);
}
}
}
}
|
请发表评论