Socket uses UDP to broadcast and send data

Source: Internet
Author: User
Tags get ip

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.