代码拉取完成,页面将自动刷新
#include "MulticastSender.h"
MulticastSender::MulticastSender(char *localIp, int sendPort, int recvPort, char *multiIpAddr)
{
int ret;
int ifnameLen = -1;
char ifname[64];
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd == -1)
{
printf("socket error\r\n");
return;
}
// 绑定server的iP和端口
struct sockaddr_in serv;
memset(&serv, 0, sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_port = htons(sendPort); // server端口
serv.sin_addr.s_addr = htonl(INADDR_ANY);
ret = bind(sockfd, (struct sockaddr*)&serv, sizeof(serv));
if(ret == -1)
{
printf("bind error\r\n");
close(sockfd);
return;
}
// 初始化客户端地址信息
memset(&client, 0, sizeof(client));
client.sin_family = AF_INET;
client.sin_port = htons(recvPort); // 客户端要绑定的端口
// 使用组播地址给客户端发数据
inet_pton(AF_INET, multiIpAddr, &client.sin_addr.s_addr);
memset(ifname, 0, sizeof(ifname));
ifnameLen = GetIfnameByIp(localIp, ifname, sizeof(ifname));
if(ifnameLen == -1)
{
printf("can not get ifname %s\r\n", localIp);
close(sockfd);
return;
}
// 给服务器开放组播权限
struct ip_mreqn flag;
// init flag
inet_pton(AF_INET, multiIpAddr, &flag.imr_multiaddr.s_addr); // 组播地址
inet_pton(AF_INET, "0.0.0.0", &flag.imr_address.s_addr); // 本地IP
flag.imr_ifindex = if_nametoindex(ifname);
ret = setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_IF, &flag, sizeof(flag));
if(ret < 0)
{
printf("set IP_MULTICAST_IF failed\r\n");
close(sockfd);
return;
}
isNormal = true;
}
MulticastSender::~MulticastSender()
{
if(sockfd != -1)
close(sockfd);
}
int MulticastSender::SendTo(char *buffer, int len)
{
int ret = -1;
if(isNormal)
{
ret = sendto(sockfd, buffer, len, 0, (struct sockaddr*)&client, sizeof(client));
}
else
{
printf("init failed\r\n");
}
return ret;
}
int MulticastSender::GetIfnameByIp(char *ip, char *ifname, int ifnameLen)
{
int ret = -1;
struct ifconf ifconf;
struct ifreq *ifreq;
char buf[512];//缓冲区
if(sockfd == -1)
{
return -1;
}
//初始化ifconf
ifconf.ifc_len =512;
ifconf.ifc_buf = buf;
ioctl(sockfd, SIOCGIFCONF, &ifconf); //获取全部接口信息
//接下来一个一个的获取IP地址
ifreq = (struct ifreq*)ifconf.ifc_buf;
//printf("ifconf.ifc_len:%d\n",ifconf.ifc_len);
//printf("sizeof (struct ifreq):%d\n",sizeof (struct ifreq));
for (int i=(ifconf.ifc_len/sizeof (struct ifreq)); i>0; i--)
{
if(ifreq->ifr_flags == AF_INET)//for ipv4
{
//printf("name =[%s]\n" , ifreq->ifr_name);
//printf("local addr = [%s]\n" ,inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr));
if(strncmp(inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr), ip, strlen(ip)) == 0)
{
strncpy(ifname, ifreq->ifr_name, ifnameLen);
ret = strlen(ifreq->ifr_name);
printf("use ifname = %s, ip = %s\r\n", ifname, ip);
break;
}
ifreq++;
}
}
return ret;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。