linux广播实现

#include
#include
#include
#include
#include
#include
#include
#include
#define port 8000
#define client_port 9000
#define buflen 1500
#define ip "192.168.211.255"

int main(void){
	int sockfd;
	struct sockaddr_in serveraddr,clientaddr;
	char buf[buflen] =" xing wen peng";

	sockfd = socket(AF_INET,SOCK_DGRAM,0);
	bzero(&serveraddr,sizeof(serveraddr));
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(port);
	serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);

	bind(sockfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));

	int flag =1 ;
	setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,&flag,sizeof(flag));
	//设置socket选项的一个函数,参数众多,参看unix网络编程卷1,让sockfd具有广播能力。
	
	bzero(&clientaddr,sizeof(clientaddr));
	clientaddr.sin_family = AF_INET;
	clientaddr.sin_port = htons(client_port);
	inet_pton(AF_INET,ip,&clientaddr.sin_addr.s_addr);

	int i = 0;
	while(1){
		bzero(&buf,buflen);
		fgets(buf,buflen,stdin);
		sendto(sockfd,buf,strlen(buf),0,(struct sockaddr*)&clientaddr,sizeof(clientaddr));
		sleep(1);
	}
	close(sockfd);
	return 0;
}

  server端

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

#define port 9000
#define buflen 1024

int main(void){
	struct sockaddr_in localaddr;
	struct sockaddr_in serveraddr;
	int connfd;
	ssize_t len;
	char buf[buflen];
	
	connfd = socket(AF_INET,SOCK_DGRAM,0);

	bzero(&localaddr,sizeof(localaddr));

	inet_pton(AF_INET,"0.0.0.0",&localaddr.sin_addr.s_addr);
	localaddr.sin_port = htons(port);
	localaddr.sin_family = AF_INET;

	bind(connfd,(struct sockaddr*)&localaddr,sizeof(localaddr));

	socklen_t slen;

	while(1){
		slen = sizeof(serveraddr);
		len  = recvfrom(connfd,buf,sizeof(buf),0,(struct sockaddr*)&serveraddr,&slen);

		printf("%s \n",buf);
	}
	close(connfd);
	return 0;

}

  客户端

转载于:https://www.cnblogs.com/yjds/p/9088025.html

你可能感兴趣的:(linux广播实现)