关于UDP多播的演示,当我想测试代码是否正确时,我发现失败了,但我认为不是代码的问题。我的虚拟机是离线的,所以我想是否udp不能多播时机器离线了吗?
这是我的代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3 col-sm-4 offcanvas-xs" id="navMenu">
<div class="sidebar-nav">
<div class="navbar navbar-default" role="navigation">
<ul class="nav navbar-nav mainNav">
<img id="logo" class="img-responsive hidden-xs" src="assets/img/logo2.jpg" />
<li class="link">
<a href="#home">Home</a>
</li>
<li class="link">
<a href="#aboutSection">About</a>
</li>
<li class="filter" data-filter=".category-1">
<a href="#">Animation</a>
</li>
<li class="filter" data-filter=".category-2">
<a href="#">Commercial</a>
</li>
<li class="filter" data-filter=".category-3"><a href="#">Documentary</a>
</li>
<li class="filter" data-filter=".category-4">
<a href="#">Film</a>
</li>
<li class="filter" data-filter=".category-5">
<a href="#">Music</a>
</li>
<li class="filter" data-filter=".category-6">
<a href="#">Video Games</a>
</li>
<li class="link">
<a href="#services">Services</a>
</li>
</ul>
</div>
</div>
</div>
<div class="contentWrap">
//content
</div>
<div id="portfolio">
</div>
//this is for receive
int main(int argc,char **argv) //My Multicast address is 224.0.0.88
{
int udpsocket;
int res;
char buf[50];
struct sockaddr_in saddr;
struct sockaddr_in raddr;
bzero(&saddr,sizeof(saddr));
bzero(&raddr,sizeof(raddr));
// 初始化地址结构体变量
saddr.sin_family = AF_INET;
saddr.sin_port = htons(5001);
saddr.sin_addr.s_addr = htonl(INADDR_ANY);
// 定义并初始化组播的结构体
struct ip_mreq mreq;
bzero(&mreq, sizeof mreq);
mreq.imr_multiaddr.s_addr = inet_addr(argv[1]); //组播地址,D类型
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
// 创建udp套接字
udpsocket = socket(AF_INET,SOCK_DGRAM,0);
if(udpsocket == -1)
{
perror("create udp socket failed!\n");
return -1;
}
// 设置可以组播
setsockopt(udpsocket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
&mreq, sizeof mreq);
int ret = sizeof(struct sockaddr);
// 绑定
res = bind(udpsocket,(struct sockaddr *)&saddr,ret);
if(res == -1)
{
perror("bind udp socket failed!\n");
return -1;
}
while(1)
{
puts("111");
bzero(buf,50);
recvfrom(udpsocket,buf,50,0,(struct sockaddr *)&raddr,&ret);
printf("message recv from %s\n",buf);
}
close(udpsocket);
return 0;
}