|
我在ubuntu里使用虚拟机安装了一个ubuntu来做多播的实验,配置完ip和dns,使用桥接的方式连接,可以ping通,广播也可以做好,但是多播就是不同,请教一下,是我的源码有问题,还是我的实验环境不对?
server端的源代码:
#include<time.h>
#include<sys/socket.h>
#include<string.h>
#include<arpa/inet.h>
#include<sys/ioctl.h>
#include<stdio.h>
#include<stdlib.h>
#define BUFLEN 255
void getcurtime(char * curtime)
{
time_t tm;
time(&tm);
snprintf(curtime,BUFLEN,"%s\n",ctime(&tm));
}
int main(int argc , char * argv[])
{
struct sockaddr_in peeraddr;
int sockfd,on=1;
int num,i;
char msg[BUFLEN + 1];
if(argc!=3){
printf("usage: %s <ip address><port>\n",argv[0]);
exit(0);
}
sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(sockfd<0){
fprintf(stderr,"Socket creating error \n");
exit(1);
}
memset(&peeraddr,0,sizeof(struct sockaddr_in));
peeraddr.sin_family=AF_INET;
if(inet_pton(AF_INET,argv[1],&peeraddr.sin_addr)<=0){
printf("Wrong dest IP address\n");
exit(0);
}
peeraddr.sin_port=htons(atoi(argv[2]));
printf("IP: %s\n",inet_ntoa(peeraddr.sin_addr));
while(1){
getcurtime(msg);
int a;
a=sendto(sockfd,msg,strlen(msg),0,(struct sockaddr *)&peeraddr,sizeof(struct sockaddr_in));
printf("%d",a);
fflush(stdout);
sleep(3);
}
}
client端的源代码:
#include<string.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#define MAX 255
int main(int argc, char * argv[])
{
struct sockaddr_in server;
int sockfd,n;
struct ip_mreq mreq;
char msg[MAX+1];
if(argc<3){
printf("Usage: %s<multicast><port>",argv[0]);
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0){
perror("socket error\n");
exit(1);
}
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(atoi(argv[2]));
server.sin_addr.s_addr=htonl(INADDR_ANY);
inet_pton(AF_INET,argv[1],&mreq.imr_multiaddr);
//"192.168.1.15"是eth0的ip
if(inet_pton(AF_INET,"192.168.1.15",&mreq.imr_interface)<=0){
perror("fail");
exit(1);
}
printf("ip %s\n",inet_ntoa(mreq.imr_multiaddr));
fflush(stdout);
if(setsockopt(sockfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(struct ip_mreq))<0){
perror("setsockopt error\n");
exit(2);
}
if(bind(sockfd,(struct sockaddr *)&server,sizeof(server))<0){
fprintf(stderr,"bind error");
exit(3);
}
n=read(sockfd,msg,MAX);
if(n==-1){
fprintf(stderr,"read error");
exit(4);
}else{
msg[n]='\0';
printf("%s",msg);
}
} |
|