广播

头文件sock.h

封装函数wrap.c

服务器:

#include "sock.h"

#define MAXSIZE 80

void usage(const char *info)
{
 printf("Usage: %s <srv PORT>\n", info);
 exit(0);
}

int main(int argc, char *argv[])
{
 if(argc != 2)
  usage(argv[0]);

 int sockfd;
 char buf[MAXSIZE];
 struct sockaddr_in myaddr, peeraddr;

 sockfd = Socket(PF_INET, SOCK_DGRAM, 0);

 bzero(&myaddr, sizeof(myaddr));
 myaddr.sin_family = PF_INET;
 myaddr.sin_port = htons(atoi(argv[1]));
 myaddr.sin_addr.s_addr = htonl(INADDR_ANY);

 Bind(sockfd, (struct sockaddr *)&myaddr, sizeof(myaddr));

 socklen_t len = sizeof(peeraddr);

 while(1){
  recvfrom(sockfd, buf, MAXSIZE,
    0, (struct sockaddr *)&peeraddr, &len);
  printf("recv from [%s:%d] : %s\n",
    inet_ntoa(peeraddr.sin_addr),
    ntohs(peeraddr.sin_port), buf);
 }

 return 0;
}

 

运行的时候是./cli 192.168.7.255 5201意思是发给所有本段的所有主机

./rcv 5201就可以接收到广播

客服端:

#include "sock.h"

#define MAXSIZE 80

void usage(const char *info)
{
 printf("Usage: %s <srv IP> <srv PORT>\n", info);
 exit(0);
}

int main(int argc, char *argv[])
{
 if(argc != 3)
  usage(argv[0]);

 int sockfd;
 char buf[MAXSIZE];
 struct sockaddr_in peeraddr;

 sockfd = Socket(PF_INET, SOCK_DGRAM, 0);

 // enable BROADCAST
 int on = 1;
 Setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST,
   &on, sizeof(on));

 bzero(&peeraddr, sizeof(peeraddr));
 peeraddr.sin_family = AF_INET;
 peeraddr.sin_port = htons(atoi(argv[2]));
 peeraddr.sin_addr.s_addr = inet_addr(argv[1]);

 strncpy(buf, "This is a broadcast message!\n", MAXSIZE);

 while(1){
  sendto(sockfd, buf, MAXSIZE, 0,
   (struct sockaddr *)&peeraddr, sizeof(peeraddr));
  sleep(1);
 }

 return 0;
}

posted on 2012-04-12 14:07  小风儿_xf  阅读(139)  评论(0编辑  收藏  举报

导航