C语言socket UDP广播的收发

时间:2021-07-19 16:35:37   收藏:0   阅读:0

要在嵌入式系统里实现广播收发功能,server.c实现广播形式指定端口发送广播信息,client.c绑定指定端口,并阻塞接受广播内容然后打印,程序非常简单,不过有一点需要注意,那就是setsockopt()函数的使用。使用不当很可能会出问题。通过SO_REUSEADDR选项可以实现端口号的重用,SO_BROADCAST选项表示要发送的是广播信息,optval参数要给合理的初始值(这里是1),否则很可能会发送失败.

发送广播的程序server.c:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/wait.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<errno.h>
int main(){
	char msg[128] = "I am broadCast message from server!";
	int brdcFd;
	if((brdcFd = socket(PF_INET, SOCK_DGRAM, 0)) == -1){
		printf("socket fail\n");
		return -1;
	}
	int optval = 1;//这个值一定要设置,否则可能导致sendto()失败
	setsockopt(brdcFd, SOL_SOCKET, SO_BROADCAST | SO_REUSEADDR, &optval, sizeof(int));
	struct sockaddr_in theirAddr;
	memset(&theirAddr, 0, sizeof(struct sockaddr_in));
	theirAddr.sin_family = AF_INET;
	theirAddr.sin_addr.s_addr = inet_addr("255.255.255.255");
	theirAddr.sin_port = htons(4001);
	int sendBytes;
	if((sendBytes = sendto(brdcFd, msg, strlen(msg), 0,
			(struct sockaddr *)&theirAddr, sizeof(struct sockaddr))) == -1){
		printf("sendto fail, errno=%d\n", errno);
		return -1;
	}
	printf("msg=%s, msgLen=%d, sendBytes=%d\n", msg, strlen(msg), sendBytes);
	close(brdcFd);
	return 0;
}

接收广播的程序client.c:

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<netdb.h>
#include<sys/socket.h>
#include<sys/wait.h>
#include<arpa/inet.h>
int main(){
	int sockListen;
	if((sockListen = socket(AF_INET, SOCK_DGRAM, 0)) == -1){
		printf("socket fail\n");
		return -1;
	}
	int set = 1;
	setsockopt(sockListen, SOL_SOCKET, SO_REUSEADDR, &set, sizeof(int));
	struct sockaddr_in recvAddr;
	memset(&recvAddr, 0, sizeof(struct sockaddr_in));
	recvAddr.sin_family = AF_INET;
	recvAddr.sin_port = htons(4001);
	recvAddr.sin_addr.s_addr = INADDR_ANY;
	// 必须绑定,否则无法监听
	if(bind(sockListen, (struct sockaddr *)&recvAddr, sizeof(struct sockaddr)) == -1){
		printf("bind fail\n");
		return -1;
	}
	int recvbytes;
	char recvbuf[128];
	int addrLen = sizeof(struct sockaddr_in);
	if((recvbytes = recvfrom(sockListen, recvbuf, 128, 0,
		(struct sockaddr *)&recvAddr, &addrLen)) != -1){
		recvbuf[recvbytes] = ‘\0‘;
		printf("receive a broadCast messgse:%s\n", recvbuf);
	}else{
		printf("recvfrom fail\n");
	}
	close(sockListen);
	return 0;
}

编译在linux里编译调试,window编译会提示找不到对应头文件目录,

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!