UDP Multicast/Multicast Implementation steps

Source: Internet
Author: User
Tags htons

UDP Multicast

Implement the server to group the client to play (send data).

Implementation steps:

server.c

1. Create a server socket

#include <sys/types.h>

#include <sys/socket.h>

int socket (int domain, int type, int protocol); return Socket

2. Building the server address structure

struct sockaddr_in serveraddr;

#include <strings.h>

Bzero (&serveraddr, sizeof (SERVERADDR));

serveraddr.sin_family = af_inet;

SERVERADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any); Ip

Serveraddr.sin_port = htons (server_port);// Port

3. Binding Address

int bind (int sockfd, const struct SOCKADDR *addr,

Socklen_t Addrlen);

4. Construct the multicast attribute structure

struct IP_MREQN Group;

#include <arpa/inet.h>

Inet_pton (AF_INET,GROUP,&GROUP.IMR_MULTIADDR);// Set multicast address

Net_pton (Af_inet, "0.0.0.0", &group.imr_address);// set Local address

Group.imr_ifindex=if_nametoindex ("ent0");// set NIC interface

5. Set Multicast permissions and properties

SetSockOpt (Sockfd,ipproto_ip,ip_multicast_if,&group,

sizeof (group);// Set multicast permissions and Options

6. Set Client multicast address

struct sockaddr_in cliaddr;

Bzero (&cliaddr,sizeof (CLIADDR));

Cliaddr.sin_family=af_inet;

Inet_pton (AF_INET,GROUP,&CLIADDR.SIN_ADDR.S_ADDR);

Cliaddr.sin_port=htons (Client_port);

7. Send Data

SendTo (Sockfd,buf,strlen (BUF), 0, (structsockaddr*) &cliaddr,

sizeof (CLIADDR));// Send message to multicast address, return data size

Client.c

1. Create a client socket

2. Building the client address structure

3. Binding Address

4. Construct the multicast structure

5. Set Multicast permissions and properties

6. Receive Data

#include <sys/types.h>

#include <sys/socket.h>

Len=recvfrom (Confd,buf,sizeof (BUF), 0,null,0);// Receive data

UDP Multicast/Multicast Implementation steps

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.