发送方代码如下:
#include
#include
#include
#include
#include
#include
#include
#include
#define N 64
typedef struct sockaddr SA;
int main(int argc, char *argv[])
{
int sockfd;
socklen_t addr_len;
char buf[N];
struct sockaddr_in multiaddr;
if (argc < 3)
{
printf("input format is : %s \n", argv[0]);
return -1;
}
if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("sock fail");
return -1;
}
multiaddr.sin_family = PF_INET;
multiaddr.sin_port = htons(atoi(argv[2]));
multiaddr.sin_addr.s_addr = inet_addr(argv[1]);
strcpy(buf, "nobody nobody but you\n");
while (1)
{
addr_len = sizeof(multiaddr);
sendto(sockfd, buf, N, 0, (SA *)&multiaddr, addr_len);
sleep(1);
}
return 0;
}
接收方代码如下:
#include
#include
#include
#include
#include
#include
#include
#define N 64
typedef struct sockaddr SA;
int main(int argc, char *argv[])
{
int sockfd;
socklen_t addr_len;
char buf[N];
struct sockaddr_in recvaddr, sendaddr;
struct ip_mreq mreq;
if (argc < 2)
{
printf("input format is : %s \n", argv[0]);
return -1;
}
if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("sock fail");
return -1;
}
bzero(&mreq, sizeof(mreq));
mreq.imr_multiaddr.s_addr = inet_addr("224.10.10.1");
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) == -1)
{
perror("setsockopt fail\n");
exit(1);
}
recvaddr.sin_family = PF_INET;
recvaddr.sin_port = htons(atoi(argv[2]));
recvaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockfd, (SA *)&recvaddr, sizeof(recvaddr)) == -1)
{
perror("bind fail");
return -1;
}
while (1)
{
addr_len = sizeof(sendaddr);
recvfrom(sockfd, buf, N, 0, (SA *)&sendaddr, &addr_len);
printf("recv from %s[%d]:%s\n", inet_ntoa(sendaddr.sin_addr),
ntohs(sendaddr.sin_port), buf);
}
return 0;
}
阅读(1077) | 评论(0) | 转发(1) |