server:
/*
// 设置广播属性的函数
int setsockopt(int sockfd, int level, int optname,const void *optval, socklen_t
optlen);
- sockfd : 文件描述符
- level : SOL_SOCKET
- optname : SO_BROADCAST
- optval : int类型的值,为1表示允许广播
- optlen : optval的大小
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<arpa/inet.h>
int main(){
//1.创建一个通信的socket
int fd = socket(PF_INET,SOCK_DGRAM,0);
if(fd==-1){
perror("socket");
exit(-1);
}
//2.设置广播属性
int op = 1;
setsockopt(fd,SOL_SOCKET,SO_BROADCAST,&op,sizeof(op));
//3.创建一个广播的地址
struct sockaddr_in cliaddr;
cliaddr.sin_family = AF_INET;
cliaddr.sin_port = htons(9999);
inet_pton(AF_INET,"192.168.108.255",&cliaddr.sin_addr.s_addr);
//4.通信
int num = 0;
while(1){
char sendBuf[128];
sprintf(sendBuf,"hello,client....%d\n",num++);
//发送数据
sendto(fd,sendBuf,strlen(sendBuf)+1,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
printf("广播的数据: %s\n",sendBuf);
sleep(1);
}
close(fd);
return 0;
}
client:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<arpa/inet.h>
int main(){
//1.创建一个通信的socket
int fd = socket(PF_INET,SOCK_DGRAM,0);
if(fd==-1){
perror("socket");
exit(-1);
}
//2.客户端绑定本地的ip和端口
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9999);
addr.sin_addr.s_addr = INADDR_ANY;
int ret = bind(fd,(struct sockaddr*)&addr,sizeof(addr));
if(ret == -1){
perror("bind");
exit(-1);
}
//3.通信
while(1){
char buf[128];
//接受数据
int num = recvfrom(fd,buf,sizeof(buf),0,NULL,NULL);
printf("server say:%s\n",buf);
}
close(fd);
return 0;
}