#include "mnic.h"
#define IP4STRSIZE 16

int
main(int argc, char **argv)
{
	int ret, value;
	int sock_sd, sock_port = 15000;
	D5000_NIC_ALARM mesg;
	struct sockaddr_in myend, hisend;
	socklen_t hisend_len;
	fd_set rset;
	char ip4str[IP4STRSIZE];

	if(argc > 1){
		sock_port = atoi(argv[1]);
		if(sock_port <= 1024 || sock_port > 65535){
			fprintf(stderr, "Invalid socket port!\n");
			exit(1);
		}
	}

	sock_sd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (sock_sd==-1) {
		perror("socket()");
		exit(1);
	}

        value=1;
        ret = setsockopt(sock_sd, SOL_SOCKET, SO_BROADCAST, &value, sizeof(value));
        if (ret==-1) {
                perror("setsockopt()");
                exit(1);
        }

	myend.sin_family = AF_INET;
	myend.sin_port = htons(sock_port);
	inet_pton(AF_INET, "0.0.0.0", &myend.sin_addr);

	ret = bind(sock_sd, (struct sockaddr*)&myend, sizeof(myend));
	if (ret==-1) {
		perror("bind()");
		exit(1);
	}

	hisend_len = sizeof(hisend);
	while (1) {
		FD_ZERO(&rset);
		FD_SET(sock_sd, &rset);
		ret = select(sock_sd+1, &rset, NULL, NULL, NULL);
		if (ret==-1) {
			perror("select()");
			continue;
		}
		ret = recvfrom(sock_sd, &mesg, sizeof(mesg), 0, (struct sockaddr*)&hisend, &hisend_len);
		inet_ntop(AF_INET, &hisend.sin_addr, ip4str, IP4STRSIZE);
		fprintf(stdout, "===========Recieved from %s============\n", ip4str);
		fprintf(stdout, "message length : %d\nsend sequence : %d\nservices ID : %d\nenevt ID : %d\ndomain ID : %d\n", mesg.tMsgFrame.len, mesg.tMsgFrame.seqno, mesg.tMsgFrame.serv, mesg.tMsgFrame.event, mesg.tMsgFrame.domain);
		if(mesg.tSysNetcardAlarm.flags == NETCARD_ALARM_SWITCH)
		fprintf(stdout, "切换网卡名: %s\n", mesg.tSysNetcardAlarm.switch_devname);
		else if(mesg.tSysNetcardAlarm.flags == NETCARD_ALARM_RESUME)
		fprintf(stdout, "恢复网卡名: %s\n", mesg.tSysNetcardAlarm.fault_devname);
		else	
		fprintf(stdout, "故障网卡名: %s\n", mesg.tSysNetcardAlarm.fault_devname);
		fprintf(stdout, "状态标记: %d\n", mesg.tSysNetcardAlarm.flags);
		fprintf(stdout, "重发次数: %d\n", mesg.tSysNetcardAlarm.retrytimes);
	}
	close(sock_sd);

	exit(0);
}

