广播的发送程序如下:其程序流程非常简单,使用的是用户数据报协议,只要用函数setsockopt()将其修改为发送广播其余的与编写UDP服务器差不多!
Send.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
typedef struct sockaddr ADDR;
int main(int argc, char *argv[])
{
ssize_t n;
char buf[] = "this isbroadcast packet";
int serverfd,port ;
struct sockaddr_inmyaddr,peeraddr;
if(argc < 3)
{
printf("the usage :%s ipport",argv[0]);
exit(-1);
}
if((serverfd =socket(PF_INET,SOCK_DGRAM,0)) < 0)
{
perror("fail tsocket");
exit(-1);
}
port = atoi(argv[2]);
myaddr.sin_family = PF_INET;
myaddr.sin_port = htons(port);
myaddr.sin_addr.s_addr =inet_addr(argv[1]);
int on = 1;
setsockopt(serverfd,SOL_SOCKET,SO_BROADCAST,&on,sizeof(on));
socklen_t peerlen =sizeof(peeraddr);
while(1)
{
sendto(serverfd,buf,sizeof(buf),0,(ADDR*)&myaddr,sizeof(myaddr));
sleep(1);
}
return 0;
}
receive.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
typedef struct sockaddr ADDR;
int main(int argc, char *argv[])
{
ssize_t n;
char buf[256];
int serverfd,port ;
struct sockaddr_inmyaddr,peeraddr;
if(argc < 3)
{
printf("the usage :%s ipport",argv[0]);
exit(-1);
}
if((serverfd =socket(PF_INET,SOCK_DGRAM,0)) < 0)
{
perror("fail tsocket");
exit(-1);
}
port = atoi(argv[2]);
myaddr.sin_family = PF_INET;
myaddr.sin_port = htons(port);
myaddr.sin_addr.s_addr =inet_addr(argv[1]);
if(bind(serverfd,(ADDR*)&myaddr ,sizeof(myaddr)) < 0)
{
perror("failto bind");
exit(-1);
}
socklen_t peerlen =sizeof(peeraddr);
while(1)
{
recvfrom(serverfd,buf,256,0,(ADDR*)&peeraddr,&peerlen);
printf("[%s %d]%s\n",inet_ntoa(peeraddr.sin_addr),ntohs(peeraddr.sin_port),buf);
}
return 0;
}