C语言UDP通信

C语言UDP广播发送信息并接受单播回复

/***************client.c**********************/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

void* pt(void *arg){
	
	int sockListen;
	if((sockListen = socket(AF_INET, SOCK_DGRAM, 0)) == -1){
		printf("socket fail\n");
		return NULL;
	}
	int set = 1;
    /*设置套接口选项
    *	SO_REUSEADDR BOOL 允许套接口和一个已在使用中的地址捆绑
    *	SO_BROADCAST BOOL 允许套接口传送广播信息
    *	SO_BINDTODEV char * 将套接字绑定到指定端口(指网卡接口eth0,eth1等,并不是指端口)
    */
	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;//IPV4
	recvAddr.sin_port = htons(1999);//监听的本地端口
	recvAddr.sin_addr.s_addr = htonl(INADDR_ANY);//本地ip
	// 必须绑定,否则无法监听
	if(bind(sockListen, (struct sockaddr *)&recvAddr, sizeof(struct sockaddr)) == -1){
		printf("bind fail\n");
		return NULL;
	}
	int recvbytes;
	char recvbuf[1024];
	int addrLen = sizeof(struct sockaddr_in);
	printf("--------\n");
	if((recvbytes = recvfrom(sockListen, recvbuf, sizeof(recvbuf), 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 NULL;
}

int main(){
	pthread_t t1;
	pthread_create(&t1,NULL,pt,NULL);
	char msg[256] = 
        "M-SEARCH * HTTP/1.1 \r\n"
        "HOST: 192.168.10.180:1999 \r\n"
        "ST: nsdp:all \r\n"
        "MAN: nsdp:discover \r\n"
        "MODEL: sn=D820020934D84D371 \r\n"
        "USN: 80e6f61f5869453b8f8c3212a50ed667 \r\n"
        "SN:1 \r\n\r\n"; 
	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 sendAddr;
	memset(&sendAddr, 0, sizeof(struct sockaddr_in));
	sendAddr.sin_family = AF_INET;
	sendAddr.sin_addr.s_addr = htonl(INADDR_ANY);//本地ip
	sendAddr.sin_port = htons(1999);//指定的端口
	if(bind(brdcFd, (struct sockaddr *)&sendAddr, sizeof(struct sockaddr)) == -1){
		printf("bind fail\n");
		return -1;
	}
	//设置要发送的目的地址
	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(1912);//目标端口
	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);
	sleep(5);
	return 0;
}

你可能感兴趣的:(c语言,网络,udp)