Use UDP to bind the machine to accept data, while allowing the UDP client to send data, so that it can be different from the server to allow the polymorphic host to communicate
1, create socket, protocol type set to UDP
Socket socket = new socket (addressfamily.internetwork, Sockettype.dgram, PROTOCOLTYPE.UDP);
2. Binding host (address set to Ipaddress.any)
int port = 8888;
IPEndPoint IEP = new IPEndPoint (Ipaddress.any, Port);
EndPoint EP = IEP as EndPoint;
Socket. Bind (EP);
3. Accept Data
while (true)
{
byte[] buffer = new byte[1024];
Socket. ReceiveFrom (buffer, ref EP);
IEP = EP as IPEndPoint;
Get IP for local IPv4
ipaddress[] HostIP = dns.gethostaddresses (Dns.gethostname ());
Myinfomation.hostipv4 = Hostip[hostip.length-1];
Hostipv4 = Hostip[hostip.length-1];
if (IEP. address.tostring () = = Hostipv4. ToString ())
{
Continue
}
//...
}
4, send the data (send address for broadcast address ipaddress.broadcast)
IPEndPoint IEP = new IPEndPoint (Ipaddress.broadcast, Port)
Sock. SetSocketOption (Socketoptionlevel.socket, Socketoptionname.broadcast, 1);
Set the Send form for the Scoket instance
string request = "Hello, TEST send!";
Initialize send data that needs to be sent
byte[] buffer = System.Text.Encoding.Unicode.GetBytes (request);
Socket. SendTo (buffer, IEP);
Close Socket Last
Socket. Close ();
Problem:
Through the above code, although you can achieve the function of broadcasting (LAN all open Listening program can receive information), but when sending messages, they will receive their own information
In the information received when the IP can be judged, if it is their own IP to filter out their own information
Red Code above