设为首页 加入收藏

TOP

linux 广播和组播(二)
2019-07-02 14:12:31 】 浏览:182
Tags:linux 广播
ot;, &client.sin_addr.s_addr); int cnt = 0; while(1){ char buf[64] = {0}; sprintf(buf, "count=%d", cnt++); int ret = sendto(fd, buf, sizeof buf, 0, (struct sockaddr*)&client, sizeof(client)); if(ret == -1){ perror("sendto -1"); } sleep(1); } }

注意点:

  • 必须用setsockopt函数开通套接字的组播权限。发送端使用IPPROTO_IP和IP_MULTICAST_IF

  • 函数if_nametoindex的作用是通过网卡的名字,取得网卡的mac地址。

组播接收端例子

#include <sys/types.h> 
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <net/if.h>

int main(int agrc, char** argv){

  int fd = socket(AF_INET, SOCK_DGRAM, 0);

  struct sockaddr_in addr;
  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  addr.sin_port = htons(6666);
  //addr.sin_addr.s_addr = htons(INADDR_ANY);
  inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr.s_addr);
  socklen_t len = sizeof(addr);

  bind(fd, (struct sockaddr*)&addr, sizeof(addr));

  struct ip_mreqn n;
  inet_pton(AF_INET, "239.0.0.10", &n.imr_multiaddr.s_addr);
  inet_pton(AF_INET, "0.0.0.0", &n.imr_address.s_addr);
  n.imr_ifindex = if_nametoindex("enp0s3");
  
  int ret =  setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
            &n, sizeof(n));
  
  
  while(1){
    char buf[64] = {0};
    int ret = recvfrom(fd, buf, sizeof(buf), 0, NULL, NULL);
    write(STDOUT_FILENO, buf, ret);
    sleep(1);
  }
}

注意点:

  • 必须用setsockopt函数把接收端的套接字加入到组播的组里。接收端使用IPPROTO_IP和IP_ADD_MEMBERSHIP

  • 由于组播的时候,必须指定接收端的端口号,所以接收端必须调用bind函数,显示的指定自己用的端口号

c/c++ 学习互助QQ群:877684253

本人微信:xiaoshitou5854

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇leadcode的Hot100系列--104. 二叉.. 下一篇leadcode的Hot100系列--206. 反转..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目