
#define MSG_BROADCAST_SEARCH 0x4000
#define MSG_DATA_LEN (100*1024)
#define ACK_SUCCESS 0x00

#define  SEARCH_PORT			23451
#define PC_SEARCH_PORT	 23452

typedef struct __msg_head_t
{
	unsigned	int	msg_type;	//消息类型
	unsigned	int	msg_subtype;	//消息子类型
	unsigned	int		msg_size;
	unsigned	char	ack_flag;	//确认标志
	unsigned	char	unres[3];
}msg_head_t;
typedef struct __net_msg_t
{
	msg_head_t	msg_head;		//消息头
	char	msg_data[MSG_DATA_LEN];		//消息数据
}net_msg_t;


typedef struct _msg_broadcast_t
{
	int port_no; //监听端口
	int net_type; //网络类型
	int rtspport; //rtst端口
	int web_port; //web 端口
	char password[32];
	char username[32];
	int channelnum;
	char mac_addr[24];
	char ip_addr[16];
	char host_name[24]; //设备名
	char version[24];    //版本号
	char device_type[24];//产品型号	
}msg_broadcast_t;



int searchDevice(msg_broadcast_t *msg_broadcast, int iMaxCount)
{
	int opt_val = 1;
	char ip_addr[16];
	SOCKET sockfd;
	net_msg_t send_net_msg;
	net_msg_t rev_net_msg;
	struct sockaddr_in RemoteAddr;
	struct sockaddr_in LocalAddr;
	int device_num = 0;	

	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	memset(&RemoteAddr,0,sizeof(RemoteAddr));
	strcpy(ip_addr,"255.255.255.255");
	RemoteAddr.sin_family      = AF_INET;
	RemoteAddr.sin_addr.s_addr = inet_addr(ip_addr);
	RemoteAddr.sin_port        = htons(SEARCH_PORT);
	
	LocalAddr.sin_family		= AF_INET;
	LocalAddr.sin_addr.s_addr	= htonl(INADDR_ANY);
	LocalAddr.sin_port			= htons(PC_SEARCH_PORT);
	
	if (bind(sockfd, (struct sockaddr *)&LocalAddr, sizeof(LocalAddr)) < 0)
	{
		printf("recv bind fail\n");
		perror("bind fail");
		//AfxMessageBox("");
		return -1;
	}

	setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,(const char*)&opt_val,sizeof(opt_val));

	send_net_msg.msg_head.msg_type = MSG_BROADCAST_SEARCH;
	send_net_msg.msg_head.msg_subtype = 0;
	send_net_msg.msg_head.ack_flag = ACK_SUCCESS;
	send_net_msg.msg_head.msg_size = 0;

	for (int i=0;i<3;i++)
	{	
		sendto(sockfd,(char*)&send_net_msg,sizeof(msg_head_t),0,(struct sockaddr*)&RemoteAddr,sizeof(RemoteAddr));
	}
	//end 
	while(1)
	{	
		struct timeval tval;
		fd_set rset;
		FD_ZERO(&rset);
		FD_SET(sockfd,&rset);
		tval.tv_sec = 3;
		tval.tv_usec = 0;
		if(select(sockfd+1,&rset,0,0,&tval) <= 0)
		{
			break;
		}
		unsigned int len = recvfrom(sockfd,(char *)&rev_net_msg,sizeof(net_msg_t),0,NULL,NULL);
		if (len != sizeof(msg_head_t)+rev_net_msg.msg_head.msg_size)
			break;
		memcpy(msg_broadcast+device_num, (char *)rev_net_msg.msg_data, sizeof(msg_broadcast_t));
		msg_broadcast_t *buff = (msg_broadcast_t*)rev_net_msg.msg_data;
		device_num++;
		if (device_num >= iMaxCount)
		{
			break;
		}
	}
	
	closesocket(sockfd);
	return device_num;
}
