host.c:
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
struct sockaddr_in peeraddr;
struct in_addr ia;
int sockfd;
char msg[100];
unsigned socklen, n;
struct hostent *group;
struct ip_mreq mreq;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&mreq, sizeof(struct ip_mreq));
mreq.imr_multiaddr.s_addr = inet_addr("230.1.1.78");
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(struct ip_mreq)) == -1) {
perror("setsockopt");
exit(-1);
}
socklen = sizeof(struct sockaddr_in);
memset(&peeraddr, 0, socklen);
peeraddr.sin_family = AF_INET;
peeraddr.sin_port = htons(7838);
peeraddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind (sockfd, (struct sockaddr *) &peeraddr, sizeof(struct sockaddr_in)) == -1) {
printf("Bind error\n");
exit(0);
}
bzero(msg, sizeof(msg));
n = recvfrom(sockfd, msg, 100, 0,(struct sockaddr *) &peeraddr, &socklen);
printf("host recv:%s(%d)\n", msg, n);
}
cli.c:
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
struct sockaddr_in peeraddr, myaddr;
int sockfd;
char msg[100]="i am toy";
unsigned int socklen;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
socklen = sizeof(struct sockaddr_in);
bzero(&peeraddr, socklen);
peeraddr.sin_family = AF_INET;
peeraddr.sin_port = htons(7838);
peeraddr.sin_addr.s_addr = inet_addr("230.1.1.78");
if (sendto(sockfd, msg, strlen(msg), 0,(struct sockaddr *) &peeraddr, socklen) < 0) {
printf("sendto error!\n");
exit(3);
}
printf("'%s' send ok\n", msg);
}
makefile见其他udp程序。
组播和广播,从发送端来看就是IP地址不同,广播是最后一个为255,而组播是在239.0.0.0~239.255.255.255范围内的IP。从性能来说,广播要求所有节点都接受和处理,如果不需要则舍弃;而组播可以使部分主机进行处理。而接收端相对广播多了上面红色部分。
阅读(732) | 评论(0) | 转发(0) |