Broadcast and multicast implementation under the socket

Source: Internet
Author: User
Tags htons

First, broadcast:Broadcast refers to sending information to all network nodes in a local area network. This is one of the UDP connections.
1. Initialization: WSAStartup (Makeword (2,2), &wsad);
2. Create a UDP socket:s=socket (af_inet,sock_dgram,0);
3.If the socket wants to receive information, it needs to bind the address and the port number of this set of broadcasts, you don't need this step if you just want to send a broadcast message
Sockaddr_in Udpadress,sender;
int senferaddsize=sizeof (sender);
Udpadress.sin_family=af_inet;
Udpadress.sin_port=htons (11114);
UDPADRESS.SIN_ADDR.S_ADDR=INET_ADDR ("10.11.131.32");
Bind (S, (sockaddr*) &udpadress,sizeof (udpadress)); //only receive IP data destined for this socket
This node can receive all broadcast messages destined for Port 11114 in the LAN.

4. Set the socket's properties to broadcast
BOOL Optval=true;
SetSockOpt (S,sol_socket,so_broadcast, (char*) &optval,sizeof (bool));
5. You can use Recvfrom or sendto to send and receive broadcast messages.
Here is accepted, this is a blocking operation
Ret=recvfrom (s,data,1000,0, (sockaddr*) &sender,&senferaddsize);
Here is a message like this broadcast Group, note that the address sent is the broadcast address Inaddr_broadcast, the port number is the port number of the reorganization broadcast 11114
Sockaddr_in Dstadd;
Dstadd.sin_family=af_inet;
Dstadd.sin_port=htons (11114);
Dstadd.sin_addr.s_addr=inaddr_broadcast;
SendTo (S,data (), totalbyte,0, (sockaddr*) &dstadd,sizeof (sockaddr));

Second, multicast
1. Initialization
WSAStartup (Makeword (2,2), &wsad);
2. Create a socket for multicast communication, note that the socket parameter is set to multicast
S=wsasocket (af_inet,sock_dgram,0,null,0,wsa_flag_multipoint_c_leaf| Wsa_flag_multipoint_d_leaf| wsa_flag_overlapped);
3. Bind the socket to a local address, port, and broadcast different,In multicast, both the sending and receiving end must bind to a local address, which is the port on which the information is processed when multicast traffic
Udpadress.sin_family=af_inet;
Udpadress.sin_port=htons (22222);
UDPADRESS.SIN_ADDR.S_ADDR=INET_ADDR ("10.11.131.32");
Bind (S, (sockaddr*) &udpadress,sizeof (udpadress));
4. Define the address of the multicast group
Multicastgroup.sin_family=af_inet;
Multicastgroup.sin_port=htons (1111); Here the port is arbitrary, each node can be set to a different
MULTICASTGROUP.SIN_ADDR.S_ADDR=INET_ADDR ("224.0.0.3"); Use the multicast address in the address section specified above
5. Join the multicast group. Note that the function here returns a socket, which is not responsible for communication, but only when it is detached from the multicast group.
SOCKET Sockm=wsajoinleaf (S, (sockaddr*) &multicastgroup,sizeof (Multicastgroup), null,null,null,null,jl_both);
6. Use Recvfrom to accept multicast information, or use SendTo to send multicast information
Ret=recvfrom (s,data,1000,0, (sockaddr*) &sender,&senferaddsize);
SendTo (S,data (), totalbyte,0, (sockaddr*) &multicastgroup,sizeof (Multicastgroup));
7. Finally close the cleanup
Closesocket (SOCKM);
Closesocket (s);
WSACleanup ();


7. Other:
1) In a multicast group, by default, a node that emits multicast information receives the information it sends itself, called a multicast loopback, which can turn off multicast loopback:
BOOL Val=false;
Setsocket (S,ipproto_ip,ip_multicast_loop, (char*) val,sizeof (Val));
2) in multicast, usually to set the appropriate TTL (the value of the TTL is how much, then the multicast information can go through how many routers, each through a router, the value of TTL automatically minus 1):
int val=3;
Setsocket (S,ipproto_ip,ip_multicast_ttl, (char*) val,sizeof (int));

Iii. usage of sendto and recvfrom

int SendTo (SOCKET s, const char far* buf, int len, int flags,
const struct SOCKADDR far* to, int tolen);
S: A descriptive word that identifies the socket interface.
BUF: The buffer that contains the data to be sent.
Len:buf the length of the data in the buffer.
Flags: The call way flag bit.
To: Pointer to the address of the destination socket interface, populated by the author
Tolen:to the length of the address referred to.

int Recvfrom (SOCKET s, char far* buf, int len, int flags,
struct sockaddr far* from, int far* fromlen);
S: Identifies a description word for a connected socket interface.
BUF: Receives the data buffer.
Len: buffer length.
Flags: Invoke operation mode.
From: Pointer to the buffer containing the source address, which is automatically populated when the data is received, and the source sock address is saved
Fromlen: pointer, pointing to the from buffer length value.


Note: The client and server use named Port method: Specify a sock address (including the port), and then bind the address to the sock handle, then the sock is named Sock; the party that needs to receive the message needs to specify a named sock handle using bind. Otherwise, the network layer does not know which ports the received IP packets are posted to, and the corresponding socket handles.

Iv. examples

Example 1, broadcast
Server-side
Server.cpp:Defines the entry point for the console application.//

#include "stdafx.h"
#include <WinSock2.h>
#include <stdio.h>
#include <iostream>
using namespace Std;
#pragma comment (lib, "Ws2_32.lib")
const int Max_buf_len = 255;
int _tmain (int argc, _tchar* argv[])
{
WORD wversionrequested;
Wsadata Wsadata;
int err;

Start the Socket API
wversionrequested = Makeword (2, 2);
Err = WSAStartup (wversionrequested, &wsadata);
if (err! = 0) {return-1;}
if (Lobyte (wsadata.wversion)! = 2 | | Hibyte (wsadata.wversion)! = 2)
{WSACleanup (); return-1;}
Create socket
SOCKET Connect_socket;
Connect_socket = socket (af_inet, SOCK_DGRAM, IPPROTO_UDP);
if (Invalid_socket = = Connect_socket)
{err = WSAGetLastError ();p rintf ("/" socket/"error! error code is%d/n", err); return-1;}

Sockaddr_in sin;
sin.sin_family = af_inet;
Sin.sin_port = htons (3779);
SIN.SIN_ADDR.S_ADDR = Inaddr_broadcast;

bool bopt = true;
Set the socket to broadcast type
SetSockOpt (Connect_socket, Sol_socket, So_broadcast, (char*) &bopt, sizeof (bopt));
int naddrlen = sizeof (SOCKADDR);
Char Buff[max_buf_len] = "";
int nloop = 0;
while (1)
{nloop++;
sprintf (Buff, "%8d", Nloop);
Send data
int nsendsize = sendto (connect_socket, Buff, strlen (buff), 0, (sockaddr*) &sin, Naddrlen);
if (Socket_error = = nsendsize)
{err = WSAGetLastError ();p rintf ("/" sendto/"error!, error code is%d/n", err); return-1;}
printf ("Send:%s/n", buff);
Sleep (500);
}
return 0;
}

Client
Client.cpp:Defines the entry point for the console application.//
#include "stdafx.h"
#include <WinSock2.h>
#include <stdio.h>
#pragma comment (lib, "Ws2_32.lib")
const int Max_buf_len = 255;
int _tmain (int argc, _tchar* argv[])
{
WORD wversionrequested;
Wsadata Wsadata;
int err;
Start the Socket API
wversionrequested = Makeword (2, 2);
Err = WSAStartup (wversionrequested, &wsadata);
if (err! = 0) {return-1;}
if (Lobyte (wsadata.wversion)! = 2 | | Hibyte (wsadata.wversion)! = 2)
{WSACleanup (); return-1;}

Create socket
SOCKET Connect_socket;
Connect_socket = socket (af_inet, SOCK_DGRAM, IPPROTO_UDP);
if (Invalid_socket = = Connect_socket)
{
Err = WSAGetLastError ();
printf ("/" socket/"error! error code is%d/n", err);
return-1;
}

Used to bind sockets
Sockaddr_in sin;
sin.sin_family = af_inet;
Sin.sin_port = htons (3779);
sin.sin_addr.s_addr = 0;
Used to receive data from a broadcast address on the network
Sockaddr_in Sin_from;
sin_from.sin_family = af_inet;
Sin_from.sin_port = htons (3779);
SIN_FROM.SIN_ADDR.S_ADDR = Inaddr_broadcast;
Set the socket as the broadcast type,
bool bopt = true;
SetSockOpt (Connect_socket, Sol_socket, So_broadcast, (char*) &bopt, sizeof (bopt));

Binding sockets
Err = Bind (Connect_socket, (sockaddr*) &sin, sizeof (SOCKADDR));
if (Socket_error = = err)
{
Err = WSAGetLastError ();
printf ("/" bind/"error! error code is%d/n", err);
return-1;
}

int naddrlen = sizeof (SOCKADDR);
Char Buff[max_buf_len] = "";
int nloop = 0;
while (1)
{
Receive data
int nsendsize = recvfrom (connect_socket, Buff, Max_buf_len, 0, (sockaddr*) &sin_from, &naddrlen);
if (Socket_error = = nsendsize)
{
Err = WSAGetLastError ();
printf ("/" recvfrom/"error! error code is%d/n", err);
return-1;
}
Buff[nsendsize] = '/0 ';
printf ("Recv:%s/n", buff);
}
return 0;
}


This article from "Tech record" blog, declined reprint!

Broadcast and multicast implementation under the socket

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.