概述
在测试多时先确定测试的接口(网卡)是否已经开启多播功能,如下:
图.1
其中RUNNING MULTICAST表示开启了多播功能,可用ifconfig命令开启
多播数据发送端:
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
if (argc != 3)
{
printf("Usage:./exec [multicast_ip] [port]n");
exit(-1);
}
struct sockaddr_in servsend;
socklen_t len = sizeof(struct sockaddr_in);
int ret;
int sendfd = socket(AF_INET, SOCK_DGRAM, 0);
/* 目的地址为多播地址 */
servsend.sin_addr.s_addr = inet_addr(argv[1]);
servsend.sin_port = htons(atoi(argv[2]));
servsend.sin_family = AF_INET;
u_char off = 1;
/*开启外出数据包的回馈*/
setsockopt(sendfd, IPPROTO_IP, IP_MULTICAST_LOOP, &off, sizeof(off));
/* 选择多播外出接口 */
char buf[256];
struct in_addr in;
in.s_addr = inet_addr("192.168.1.115");
setsockopt(sendfd, IPPROTO_IP, IP_MULTICAST_IF, &in, sizeof(in));
while (1)
{
sprintf(buf, "I am random [%d]", (int)random()%100);
ret = sendto(sendfd, buf, strlen(buf), 0, (struct sockaddr *)&servsend, len);
if (ret < 0)
{
printf("sendto errorn");
exit(-1);
}
sleep(2);
}
return 0;
}
多播数据接受端:
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
if (argc != 3)
{
printf("Usage:./exec [multicast_ip] [port]n");
exit(-1);
}
int ret;
struct sockaddr_in servrecv;
int len = sizeof(servrecv);
int recvfd = socket(AF_INET, SOCK_DGRAM, 0);
const int on = 1;
ret = setsockopt(recvfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if (ret < 0)
{
printf("setsockopt errorn");
exit(-1);
}
servrecv.sin_port = htons(atoi(argv[2]));
servrecv.sin_addr.s_addr = htonl(INADDR_ANY);
servrecv.sin_family = AF_INET;
ret = bind(recvfd, (struct sockaddr *)&servrecv, len);
if (ret < 0)
{
printf("bind errorn");
exit(-1);
}
/* 加入多播组 */
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr = inet_addr(argv[1]);
mreq.imr_interface.s_addr = inet_addr("192.168.1.115");
ret = setsockopt(recvfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
if (ret < 0)
{
printf("setsockopt error(2)n");
exit(-1);
}
struct sockaddr_in in;
while (1)
{
char buf[256];
memset(buf, 0, 256);
len = sizeof(in);
ret = recvfrom(recvfd, buf, 256, 0, (struct sockaddr *)&in, &len);
if (ret < 0)
{
printf("recvfrom errorn");
exit(-1);
}
printf("%sn", buf);
}
return 0;
}
最后
以上就是整齐芝麻为你收集整理的linux网络编程实现,【网络编程】Linux多播简单实现的全部内容,希望文章能够帮你解决linux网络编程实现,【网络编程】Linux多播简单实现所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复