multicast 的问题
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <net/if.h>
#include <netinet/in.h>
#include <string.h>
void mcast_join(int sockfd)
{
struct ip_mreq req;
req.imr_interface.s_addr=INADDR_ANY;
inet_aton("224.2.2.2",&req.imr_multiaddr);
setsockopt(sockfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&req,sizeof(req));
}
char *sock_ntop(const struct sockaddr *sa,socklen_t len)
{
char portstr[8];
static char str[128];
struct sockaddr_in *sin = (struct sockaddr_in *) sa;
if (inet_ntop(AF_INET, &sin->sin_addr, str, sizeof(str)) == NULL)
return (NULL);
if (ntohs(sin->sin_port) != 0)
{
snprintf(portstr, sizeof(portstr), ":%d",ntohs(sin->sin_port));
strcat(str, portstr);
}
return (str);
}
int main()
{
int recvfd;
int opt;
socklen_t len;
struct sockaddr_in sockclient,sockrecv;
int ret;
char line[100];
bzero(&sockrecv,sizeof(struct sockaddr_in));
sockrecv.sin_family=AF_INET;
sockrecv.sin_port = htons(888;
sockrecv.sin_addr.s_addr=htonl(INADDR_ANY);
// inet_pton(AF_INET, "0.0.0.15", &sockrecv.sin_addr);
recvfd = socket(AF_INET , SOCK_DGRAM, 0);
opt=1;
setsockopt(recvfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
len=sizeof(struct sockaddr_in);
bind(recvfd,(struct sockaddr*)&sockrecv,len);
printf("%dn",recvfd);
mcast_join(recvfd);
// setsockopt(recvfd,IPPROTO_IP,IP_MULTICAST_LOOP,&opt,sizeof(opt));
while((ret=recvfrom(recvfd,line,100,0,(struct sockaddr *)&sockclient,&len))>0)
{
line[ret]='';
printf("from %s : %sn",sock_ntop((struct sockaddr *)&sockclient,len),line);
}
close(recvfd);
}
int main()
{
int ret;
char line[100]="multicast send";
struct sockaddr_in socksend;
int sockfd;
bzero(&socksend,sizeof(struct sockaddr_in));
socksend.sin_family=AF_INET;
socksend.sin_port = htons(888;
inet_pton(AF_INET, "224.2.2.2", &socksend.sin_addr);
sockfd=socket(AF_INET,SOCK_DGRAM,0);
printf("%dn",sockfd);
ret=sendto(sockfd,line,strlen(line),0,(struct sockaddr *)&socksend,sizeof(struct sockaddr_in));
printf("%dn"
}
以上是服务端和客户端,可是客户端运行,无法将数据send出去,return -1.
请高手指教
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
怎么没人理啊,顶