Beispiel #1
0
int cfg_get_real_gateway(char *value, int *found)
{
	char *def = "";

	strcpy (value, def);
	*found = 1;
	int gw_ret = get_gateway (value);
	if (gw_ret != 0)
		*found = 0;

	return FV_OK;
}
Beispiel #2
0
void XENVACT_PPPoE_Stop(void)
{
    char cmd_buf[100];
    TRACE_DEBUG("stop ppp0(pppoe)...");

	XENVACT_pppoe_thead_keep = 0;
	if( XENVACT_pppoe_thread_id != 0)
	{
		pthread_join(XENVACT_pppoe_thread_id, NULL);
		XENVACT_pppoe_thread_id = 0;
	}

    sprintf(cmd_buf, "pppoe-stop");
    TRACE_DEBUG("%s", cmd_buf);
    system(cmd_buf);

	sprintf(cmd_buf, "rm -f /tmp/pppoe.up");
	TRACE_DEBUG("%s", cmd_buf);
	system(cmd_buf);

	char gateway[255]={0};
	unsigned char u8SaveGW[IP_ADDR_LEN];
	unsigned char SaveGWString[32];
	g_pstSysEnv->GetGateway(g_pstSysEnv, u8SaveGW);
	
	//restore default gateway
	if( 0 == get_gateway(gateway) )
	{
		TRACE_DEBUG("gateway is %s",gateway);
		sprintf(SaveGWString,"%d.%d.%d.%d",u8SaveGW[0],u8SaveGW[1],u8SaveGW[2],u8SaveGW[3]);
		if( 0 != strcmp(SaveGWString,gateway) )
		{
			sprintf(cmd_buf, "route del default");
			TRACE_DEBUG("%s", cmd_buf);
			system(cmd_buf);
			set_if_property(NULL, NULL, NULL, u8SaveGW);
		}
	}
	else
		set_if_property(NULL, NULL, NULL, u8SaveGW);	


	TRACE_DEBUG("stop ppp0(pppoe) finished!");
}
Beispiel #3
0
/* 
 * to modify local route in radix tree.
 */
void
modify_local_route(struct rt_plen *plen, struct route_entry *rt_ptr,
		   struct route_entry *nh_ptr, struct interface *if_ptr)
{
	struct gateway *gw_ptr;

	plen->rp_tag = rt_ptr->rip6_rtag;
	plen->rp_len = rt_ptr->rip6_prflen;
	plen->rp_metric = rt_ptr->rip6_metric;
	plen->rp_timer = 0;
	gw_ptr = plen->rp_gway;

	/* If gateway is changed from previous, make the changes in link. */
	if (memcmp(plen->rp_gway->gw_addr.s6_addr,
		   nh_ptr->rip6_addr.s6_addr, 16)) {
		if (plen->rp_pdst)
			plen->rp_pdst->rp_ndst = plen->rp_ndst;
		else
			plen->rp_gway->gw_dest = plen->rp_ndst;

		if (plen->rp_ndst)
			plen->rp_ndst->rp_pdst = plen->rp_pdst;

		gw_ptr = get_gateway(&(nh_ptr->rip6_addr), if_ptr);
		plen->rp_gway = gw_ptr;
		plen->rp_ndst = gw_ptr->gw_dest;
		plen->rp_pdst = NULL;
		if (gw_ptr->gw_dest)
			gw_ptr->gw_dest->rp_pdst = plen;

		gw_ptr->gw_dest = plen;
	}
	plen->rp_state |= RTS6_CHANGED;

	gw_ptr->gw_ifp = if_ptr;
	if (!(plen->rp_state & RTS6_KERNEL))
		if ((rt_ioctl(plen, RTM_CHANGE) < 0) && (errno == ESRCH))
			rt_ioctl(plen, RTM_ADD);

	return;
}
Beispiel #4
0
int main()
{
	 char gateway[255]={0};
	  get_gateway(gateway);
	   printf("Gateway:%s\n", gateway);
}
Beispiel #5
0
void* XENVACT_PPPoE_Proc(void* arg)
{
    if(!XENVACT_set_pppoe_running) {
        pthread_exit(NULL);
    }

    int  countdown,i;
    char cmd_buf[100];
	char gateway[255]={0};
	char ppp_ip[32]={0};
	unsigned char u8SaveGW[IP_ADDR_LEN];
	unsigned char SaveGWString[32];
	int is_ip_notify = 0;
	
    TRACE_DEBUG("ppp0(pppoe) proc...");

    sprintf(cmd_buf, "pppoe-start &");
    TRACE_DEBUG("%s", cmd_buf);
    system(cmd_buf);

	sprintf(cmd_buf, "rm -f /tmp/pppoe.up");
	TRACE_DEBUG("%s", cmd_buf);
	system(cmd_buf);

    countdown = 40;
    while(XENVACT_pppoe_thead_keep)
	{
        sleep(1);
		//FIXME:UPNP_SERVER also use MCASTADDR("239.255.255.250") temporarily and need to avoid confilct.
		if( is_ip_notify != 0 )
		{
			if( get_lan_multicast_status() )
				continue;

			is_ip_notify = 0;
			countdown = 0;
			//FIXME:app2upnp_send_upnp is perhaps invalid
			#if 0
			TRACE_DEBUG("app2upnp_send_upnp,socket=%d",socket_index_upnpsvr);
			app2upnp_send_upnp(socket_index_upnpsvr);
			#else
        	sprintf(cmd_buf, "kill -9 `pidof upnp_server`");
        	TRACE_DEBUG("%s", cmd_buf);
        	system(cmd_buf);
			sleep(1);
        	sprintf(cmd_buf, "/root/upnp_server &");
        	TRACE_DEBUG("%s", cmd_buf);
        	system(cmd_buf);
			#endif
			continue;
		}
		
		if(countdown <= 0)
		{
			i = 0;
			while(XENVACT_pppoe_thead_keep && (i++ <= 60))
				sleep(1);  
			if(!XENVACT_pppoe_thead_keep)
				break;
		}
		else
			countdown--;

		if( 0 != ppp_get_ipaddr(ppp_ip) )
		{
			if(access("/tmp/pppoe.up", 0) == 0)
			{
				sprintf(cmd_buf, "rm -f /tmp/pppoe.up");
				TRACE_DEBUG("%s", cmd_buf);
				system(cmd_buf);
			}

			sleep(1);
			g_pstSysEnv->GetGateway(g_pstSysEnv, u8SaveGW);
			sprintf(SaveGWString,"%d.%d.%d.%d",u8SaveGW[0],u8SaveGW[1],u8SaveGW[2],u8SaveGW[3]);
			if( 0 == get_gateway(gateway) )
			{
				TRACE_DEBUG("get gateway %s",gateway);
				if( 0 == strcmp(SaveGWString,gateway) )
					continue;
			}
			set_if_property(NULL, NULL, NULL, u8SaveGW);	
			TRACE_DEBUG("update gateway to %s",SaveGWString);

			continue;
		}
		
		sleep(1);
		if( 0 == get_gateway(gateway) )
		{
			TRACE_DEBUG("get gateway %s",gateway);
			if( 0 == strcmp(ppp_ip,gateway) )
				continue;
			else
			{
	            sprintf(cmd_buf, "route del default");
	            TRACE_DEBUG("%s", cmd_buf);
	            system(cmd_buf);				
			}			
		}

		sleep(1);
		ppp_set_route_by_ip();

		TRACE_DEBUG("update gateway to %s",ppp_ip);
		if(access("/tmp/pppoe.up", 0) != 0)
		{
			sprintf(cmd_buf, "touch /tmp/pppoe.up");
			TRACE_DEBUG("%s", cmd_buf);
			system(cmd_buf);
		}
	
		is_ip_notify = 1;
    }

	TRACE_DEBUG("ppp0(pppoe) proc finished!");
	XENVACT_set_pppoe_running = 0;

	pthread_exit(NULL);
}
Beispiel #6
0
/*********************************************************
 ******************    Main Function    ******************
 *********************************************************/
int main(int agrc, char *agrv[])
{
    int rt = 0; /* return value of function main */
    
    /**
     * Get paramters from the command line
     */
    if (parser_args(agrc, agrv) < 0) {
        //print_usage();
        rt = -1;
        goto error;
    };


    /**
     * get net mac address
     */
    if (netmac_flag) {
        unsigned char buf[6];
        struct timeval start = {0}, end = {0};
        int tuse = 0;
        int ret = 0;

        gettimeofday(&start, NULL);
        if ((ret = get_net_mac(ip, buf, 0)) > 0) {
            gettimeofday(&end, NULL);
            tuse = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec);
            printf("\033[0;m%s MAC Address: \033[0;35m%02x:%02x:%02x:%02x:%02x:%02x\033[0m, used %d.%03ds.\n", ip, 
                    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], (int)ret/ 1000000, (int)(ret % 1000000));
        } else {
            printf("\033[0;31mget %s net mac failed\n\033[0m", ip);
            return -1;
        }
        
        return 0;
    }

    /**
     * get mac address
     */
    if (mac_flag) {
        if (!strlen(ether)) get_ifname(ether);
        unsigned char buf[6] = {0};
        char *str = NULL, *save_str = NULL;

        for (str = ether; ; str = NULL) {
            save_str = strtok(str, " ");
            if (save_str == NULL) return -1;

            if (!get_mac_addr(save_str, buf)) {
                printf("\033[0;32m%s: \033[0;35m%02x:%02x:%02x:%02x:%02x:%02x\n\033[0m", save_str, 
                        buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);
            } else {
                printf("\033[0;31m%s: -1\n\033[0m", save_str);
                return -1;
            }

            return 0;
        }
    }

    /**
     * aro cheating
     */
    if (cheat_flag) {
        if (!strlen(ip)) {
            printf("\033[0;31minput ipaddress when arp cheating\n\033[0m");
            return -1;
        }

        //if (!strlen(ether) || !strlen(gateway_ip)) 
        //    get_gateway(gateway_ip, ether);
        //rt = arp_cheat(ether, ip, gateway_ip);
        rt = arp_cheating(ip);
        
        return rt;
    }

    /**
     * get interface name
     */
    if (eth_flag && !strlen(ether)) {
        if (!get_ifname(ether)) {
            printf("\033[0;35m%s\n\033[0m", ether);
            return 0;
        } else {
            printf("\033[0;31mget interface failed\n\033[0m");
            return -1;
        }
    }

    /**
     * get gateway ip address
     */
    if (gateway_flag && !strlen(gateway_ip)) {
        if (!strlen(ether)) {
            get_ifname(ether);
        }
        if (!strlen(ether)) {
            printf("\033[0;31mget interface failed\n\033[0m");
            return -1;
        } 
        
        char *str = NULL, *save_str = NULL;
        for (str = ether; ; str = NULL) {
            save_str = strtok(str, " ");
            if (save_str == NULL) return -1;

            if (!get_gateway(gateway_ip, save_str)) {
                printf("\033[0;32m%s\'s gateway address is:\033[0;35m %s\n\033[0m", 
                        save_str, gateway_ip);
                return 0;
            } else {
                printf("\033[0;31mget interface failed\n\033[0m");
                return -1;
            }
        }
    }

    if (router_flag) {
        if (strlen(ip)) route(ip);
        return 0;
    }

    if (up_flag) {
        scan_router_ip_up(up_range, 4);
        return 0;
    }

    if (!strlen(ip)) strcpy(ip, "127.0.0.1");
    if (proto_flag) {
        printf("\033[1;31mConfiguration: \n");
        printf("\033[1;35m  protocol    : \033[1;32m%s\n", proto_str);
        printf("\033[1;35m  ip          : \033[1;32m%s\n", ip);
        printf("\033[1;35m  port        : \033[1;32m%d\n", port);
        printf("\033[1;35m  ser         : \033[1;32m%d\n", ser_flag);
        printf("\033[1;35m  cli         : \033[1;32m%d\n", cli_flag);
        printf("\033[1;35m  times       : \033[1;32m%d\n", times);
        printf("\033[1;35m  wait  time  : \033[1;32m%d\n", sleep_time);
        printf("\033[0m\n");

        switch (protocol)
        {
            case PROTO_TCP:
                if (ser_flag) net_tcp_ser(ip, port);
                else if (cli_flag) net_tcp_cli(ip, port);
                break;
            case PROTO_UDP:
                if (ser_flag) net_udp_ser(ip, port);
                else if (cli_flag) net_udp_cli(ip, port);
                break;
            case PROTO_BROADCAST:
                if (ser_flag) udp_broadcast_recv(ip, port, times, NULL, 0);
                else if (cli_flag)
                {
                    if (strlen(message))
                        udp_broadcast_send(ip, port, times, message);
                    else 
                        udp_broadcast_send(ip, port, times, NULL);
                }
            case PROTO_MULTICAST:
                if (ser_flag) udp_multicast_recv(ip, port, times, NULL, 0);
                else if (cli_flag)
                {
                    if (strlen(message))
                        udp_multicast_send(ip, port, times, message);
                    else 
                        udp_multicast_send(ip, port, times, NULL);
                }
                break;
            case '?':
            default:
                return -1;
                break;
        }

        return 0;
    }

error:
    /**
     * error handling
     */

    return rt;
}
Beispiel #7
0
/* 
 * to add local route in radix tree.
 */
void
add_local_route(struct route_entry *rt_ptr, struct route_entry *nh_ptr,
		struct interface *if_ptr, u_char state,
		struct tree_node *add_here)
{
	int i;
	struct rt_plen *plen;
	struct in6_addr add_prefix, gw_addr;
	u_char add_pre_len, add_metric;
	u_short add_tag;
	struct tree_node *current, *next, *leaf, *intermediate;
	struct gateway *gw;
	boolean short_pre_len = FALSE;

	current = next = leaf = intermediate = NULL;

	/* 
	 * If entry in tree where route is to be added is leaf node,
	 * add rt_plen entry to the leaf node.
	 */
	add_prefix = rt_ptr->rip6_addr;
	add_pre_len = rt_ptr->rip6_prflen;

	i = (add_pre_len - 1) / 8 + 1;
	add_prefix.s6_addr[i - 1] &=
		((signed char)0x80 >> ((add_pre_len - 1) % 8));
	for (; i < 16; i++)
		add_prefix.s6_addr[i] = 0;

	add_tag = rt_ptr->rip6_rtag;
	add_metric = rt_ptr->rip6_metric;
	gw_addr = nh_ptr->rip6_addr;

	if (add_here->tn_bposn == LEAF_BIT_POSN) {
		leaf = add_here;
		goto ATTACH;
	}

	/* Entry is to be added between current and next. */

	current = add_here;
	if (add_pre_len <= add_here->tn_bposn) {
		short_pre_len = TRUE;	/* for get_bposn() */
		next = current->lptr;
	} else if (add_prefix.s6_addr[current->boff] & current->tn_bmask)
		next = current->rptr;
	else
		next = current->lptr;

	intermediate = (struct tree_node *)malloc(sizeof(struct tree_node));
	if (intermediate == NULL) {
		syslog(LOG_ERR, "local cache memory allocation failed: %m");
		return;
	}
	leaf = (struct tree_node *)malloc(sizeof(struct tree_node));
	if (leaf == NULL) {
		free(intermediate);
		syslog(LOG_ERR, "local cache memory allocation failed: %m");
		return;
	}
	bzero(intermediate, sizeof(*intermediate));
	bzero(leaf, sizeof(*leaf));

	intermediate->tn_bposn =
		get_bposn(&add_prefix, next, short_pre_len);
	intermediate->tn_bmask =
		((unsigned char)0x80 >> ((intermediate->tn_bposn % 8)));
	intermediate->boff = (intermediate->tn_bposn) / 8;

	while (intermediate->tn_bposn < current->tn_bposn) {
		next = current;
		current = current->tn_backp;
	}

	while (next->tn_bposn < intermediate->tn_bposn) {
		/* maybe all lptr */
		current = next;
		if (add_prefix.s6_addr[current->boff] &
		    current->tn_bmask)
			next = current->rptr;
		else
			next = current->lptr;
	}

	intermediate->tn_backp = current;

	if (add_prefix.s6_addr[intermediate->boff] & intermediate->tn_bmask) {
		intermediate->rptr = leaf;
		intermediate->lptr = next;
	} else {
		intermediate->rptr = next;
		intermediate->lptr = leaf;
	}

	leaf->tn_backp = intermediate;
	leaf->tn_bposn = LEAF_BIT_POSN;
	leaf->key = add_prefix;

	if (current->lptr == next)
		current->lptr = intermediate;
	else
		current->rptr = intermediate;

	next->tn_backp = intermediate;

 ATTACH:
	plen = (struct rt_plen *)malloc(sizeof(struct rt_plen));
	if (plen == NULL) {
		syslog(LOG_ERR, "local cache memory allocation failed: %m");
		return;
	}
	bzero(plen, sizeof(*plen));

	gw = get_gateway(&gw_addr, if_ptr);
	plen->rp_leaf = leaf;
	plen->rp_gway = gw;
	plen->rp_tag = add_tag;
	plen->rp_len = add_pre_len;
	plen->rp_metric = add_metric;
	plen->rp_timer = 0;
	plen->rp_state = state;

	if ((plen->rp_len == MAX_PREFLEN) && !(state & RTS6_DEFAULT))
		plen->rp_flags |= RTF_HOST;		/* hack */
	if (state & RTS6_STATIC)
		plen->rp_flags |= RTF_STATIC;
	if ((state & RTS6_INTERFACE) && !(state & RTS6_PTOP))
		plen->rp_flags |= RTF_CLONING;	/* but no one cares */
	if (!(state & RTS6_INTERFACE))
		plen->rp_flags |= RTF_GATEWAY;
	if (state & RTS6_BLACKHOLE)
		plen->rp_flags |= RTF_REJECT;

	plen->rp_flags |= RTF_UP;

	if (!(state & RTS6_KERNEL)) {
		if ((rt_ioctl(plen, RTM_ADD) < 0) && (errno != EEXIST)) {
			/* 
			 * If new prfeix was added, delete intermediate and
			 * leaf entry for prefix.
			 */
			if (intermediate) {
				(intermediate->tn_backp->lptr == intermediate) ?
					(intermediate->tn_backp->lptr = next) :
					(intermediate->tn_backp->rptr = next);
				next->tn_backp = intermediate->tn_backp;
				free(intermediate);
				free(leaf);
			}
			free(plen);
			return;
		}
	}

	/* Link to the link list of rt_plen for this leaf. */
	plen->rp_next = leaf->dst;
	plen->rp_prev = NULL;
	if (leaf->dst)
		leaf->dst->rp_prev = plen;
	leaf->dst = plen;

	/* Link to the link list of rt_plen through the same gateway. */
	plen->rp_ndst = gw->gw_dest;
	plen->rp_pdst = NULL;
	if (gw->gw_dest)
		gw->gw_dest->rp_pdst = plen;
	gw->gw_dest = plen;

	return;
}
Beispiel #8
0
/*
 * injection_write_ip
 *
 * Description:
 *	- Write an IP packet into the wire. It can use either raw sockets 
 *		or the wire
 *
 * Inputs:
 *	- ip_packet: the IP packet
 *
 * Outputs:
 *	- return: 0 if ok, <0 if there were problems
 *
 */
int injection_write_ip (u_char *ip_packet)
{
#if defined(INJECT_USING_RAW_SOCKETS) || defined(INJECT_USING_LINK_LAYER)
	int i;
	u_int16_t packet_size = ntohs(*(u_int16_t*)(ip_packet+2));
#endif


#if defined(INJECT_USING_RAW_SOCKETS)
	int network;

	/* network initialization */
	if ((network = libnet_open_raw_sock(IPPROTO_RAW)) < 0) {
		return WIRE_ERR_PKTD_INJECTION_OPEN;

	/* packet injection */
	} else if ((i = libnet_write_ip (network, ip_packet, packet_size))
			< packet_size) {
		return WIRE_ERR_PKTD_INJECTION_WRITE_IP;

	/* shut down the interface */
	} else if (libnet_close_raw_sock (network) < 0) {
		return WIRE_ERR_PKTD_INJECTION_CLOSE;

	}

	return WIRE_ERR_NONE;

#elif defined(INJECT_USING_LINK_LAYER)

	char buffer[LIBNET_ETH_H+IP_MAXPACKET];
	struct in_addr in;
	int size = 1024;
	struct libnet_link_int *network; /* pointer to link interface struct */
	char *interface = NULL; /* pointer to the device to use */
	struct sockaddr_in sin;
	char errbuf[1024];
	struct ether_addr remote_eth, *tmp_eth;



	/* network initialization */
	if (libnet_select_device(&sin, &interface, errbuf) == -1) {
		return WIRE_ERR_PKTD_NO_WRITE_DEVICE_ACCESS;
	}
	if ((network = libnet_open_link_interface(interface, errbuf)) == NULL) {
 		return WIRE_ERR_PKTD_INJECTION_OPEN;
	}


	/* get local ethernet address */
	if ((tmp_eth = libnet_get_hwaddr(network, interface, errbuf)) == NULL) {
		(void)libnet_close_link_interface(network);
		return WIRE_ERR_PKTD_INJECTION_OPEN;
	}
	memcpy (&local_eth, tmp_eth, 6);

	debug3 ("injection_write_ip: the local ethernet address is %s\n", 
			ether_ntoa(&local_eth));


	/* get remote ethernet address (the packet is already in network order) */
	in.s_addr = *(u_int32_t*)(ip_packet+16);

	/* try to get the remote MAC address from the ARP cache */
	if (get_mac_address (in, buffer, size) < 0) {
		/* MAC address of the IP address not in ARP cache */

		/* get the gateway needed to reach the destination */
		struct in_addr gw;
		if (get_gateway (in, &gw) < 0) {
			debug3 ("injection_write_ip: can't find MAC nor gateway for %s\n", 
					inet_ntoa(in));
			(void)libnet_close_link_interface(network);
			return WIRE_ERR_PKTD_INJECTION_WRITE_IP;
		}

		/* get the gateway's ethernet address */
		if (get_mac_address (gw, buffer, size) < 0) {
			debug3 ("injection_write_ip: can't find MAC for %s's ", 
					inet_ntoa(in));
			debug3 ("gateway (%s)\n", inet_ntoa(gw));
			/* XXX: This case means typically the destination host is in 
			 * the same network than the source, but the destination MAC 
			 * address is not in the local ARP cache. Getting a local 
			 * MAC address requires implementing ARP, which we won't do 
			 * at this moment
			 */
			(void)libnet_close_link_interface(network);
			return WIRE_ERR_PKTD_INJECTION_WRITE_IP;
		}

		debug3 ("injection_write_ip: IP address %s can be reached ", inet_ntoa(in));
		debug3 ("through gateway %s (%s)\n", inet_ntoa(gw), buffer);
	} else {
		debug3 ("injection_write_ip: IP address %s corresponds to %s\n", 
				inet_ntoa(in), buffer);
	}

	if ((tmp_eth = ether_aton (buffer)) == NULL) {
		(void)libnet_close_link_interface(network);
		return WIRE_ERR_PKTD_INJECTION_WRITE_IP;
	}
	memcpy (&remote_eth, tmp_eth, 6);


  /* build ethernet header and use IP packet as payload */
#if (defined(bsdi) || defined(__NetBSD__) || defined(__OpenBSD__) ||\
		defined(__FreeBSD__))
	libnet_build_ethernet(&(remote_eth.octet[0]), 
			&(local_eth.octet[0]), ETHERTYPE_IP, NULL, 0, buffer);
#else
	libnet_build_ethernet(&(remote_eth.ether_addr_octet[0]), 
			&(local_eth.ether_addr_octet[0]), ETHERTYPE_IP, NULL, 0, buffer);
#endif
	memcpy (buffer+LIBNET_ETH_H, ip_packet, packet_size);
	packet_size += LIBNET_ETH_H;


	/* inject the packet */
	if ((i = libnet_write_link_layer (network, interface, buffer,
			packet_size)) < packet_size) {
		(void)libnet_close_link_interface(network);
		return WIRE_ERR_PKTD_INJECTION_WRITE_IP;
	}


	/* shut down the interface */
	(void)libnet_close_link_interface(network);

	return WIRE_ERR_NONE;
#else /* INJECT_USING_LINK_LAYER */
	return(0);
#endif /* INJECT_USING_LINK_LAYER */
}
Beispiel #9
0
/*
##############################################
##Int ModuleResize(Int argc, Char *argv[])
##############################################
*/
Int ModuleResize(Int argc, Char *argv[])
{
	Uns                 initMask            = 0;
	Int                 status              = EXIT_SUCCESS;
	Rendezvous_Attrs    rzvAttrs            = Rendezvous_Attrs_DEFAULT;
	Fifo_Attrs          fAttrs              = Fifo_Attrs_DEFAULT;
	Rendezvous_Handle   hRendezvousInit     = NULL;
	Rendezvous_Handle   hRendezvousWriter   = NULL;
	Rendezvous_Handle   hRendezvousCleanup  = NULL;
	Int                 numThreads			= 0;
	pthread_t 			id_listen[5] 		= {0};
	Void               *ret;

	char 				devicebuf[16] 		= {0};

	CaptureEnv          captureEnv;
	WriterEnv           writerEnv;
	WriterEnv			writerLowRateEnv;
	DetectEnv			detectEnv;
	VideoEnv            videoEnv;
	VideoEnv            videoLowRateEnv;//dd
	VideoEnv            LowRateResize;
	AudioEnv            audioEnv;
	CtrlEnv             ctrlEnv;
	char box_version[64] = {0};
	OutputVideoInfo		outputhandle;
	textinfo			*texthandle;
	int 				DHCPVAL = 0, tmp = 0;
	char 				gateway[255] = {0};

	struct sched_param  schedParam;
	pthread_t           captureThread;
	pthread_t           detectThread;
	pthread_t           writerThread;
	pthread_t			writerLowThread;
	pthread_t           videoThread;
	pthread_t           audioThread;
	pthread_t			videoLowThread;
	pthread_t			resizeLowThread;
#ifdef DSS_ENC_1100_1200
	pthread_t           webListenThread;
#endif
	pthread_attr_t      attr;
	int       index = 0;
	int result = 0;
	char ts_version[128] = {0};
	/* Zero out the thread environments */
	Dmai_clear(captureEnv);
	Dmai_clear(writerEnv);
	Dmai_clear(videoEnv);
	Dmai_clear(audioEnv);
	Dmai_clear(ctrlEnv);

	mid_task_init();
	trace_init();
	open_gpio_port();

	ts_build_get_version(ts_version, sizeof(ts_version));

	strcpy(box_version, BOX_VER);
	strcat(box_version, CODE_TYPE);
	strcat(box_version, DEUBG);
	printf("[%s] Module Encode Program %s V%s\n", CODE_COND, BOARD_TYPE, box_version);
	printf("the build time is %s,the git vesion is %s.the ts version is %s\n\n", g_make_build_date, _VERSION, ts_version);

	initMutexPthread();
	InitgblCommonMutex();
	InitSysParams();
	initOutputVideoParam();
	InitHVTable(&gHVTable);
	//	webgetDHCPFlag(tmp, &DHCPVAL);
	//	readDHCPValue(DHCPCONFIG_FILE, &DHCPVAL);
	//	setDHCPFlag(DHCPVAL);
	gLogoinfo = initLogoMod();
	initTextinfo();

	ReadEncodeParamTable(CONFIG_NAME, &gSysParaT);
	DHCPVAL = gSysParaT.sysPara.nTemp[0];
	printf("----mic=%x:%x:%x:%x:%x:%x\n",gSysParaT.sysPara.szMacAddr[0],gSysParaT.sysPara.szMacAddr[1],gSysParaT.sysPara.szMacAddr[2],
			gSysParaT.sysPara.szMacAddr[3],gSysParaT.sysPara.szMacAddr[4],gSysParaT.sysPara.szMacAddr[5]);

	ReadLowbitParamTable(LOWBIT_PARAM, &gSysParaT);

	memset(&outputhandle, 0, sizeof(OutputVideoInfo));
	getOutputvideohandle(&outputhandle);

	readOutputVideoParam(VIDEOENCODE_FILE, &outputhandle);

	setOutputvideohandle(&outputhandle);
	//sleep(10);
	ReadLogoinfo(LOGOCONFIGNAME, gLogoinfo);
	//setLogoInfoHandle(logoEnv);
	//sleep(10);
	texthandle = getTextInfoHandle();
	readTextFromfile(ADDTEXT_FILE, texthandle);
	//	DEBUG(DL_DEBUG, "%d,%d,%d,%d,%d,%d,%s\n", DHCPVAL, texthandle->xpos, texthandle->ypos,
	//	      texthandle->enable, texthandle->showtime, texthandle->alpha, texthandle->msgtext);
	//	sleep(10);
#ifdef DSS_ENC_1100_1200
	ReadProtocolIni(PROTOCOL_NAME, &gProtocol);
#endif

	ReadRemoteCtrlIndex(REMOTE_NAME, &index);
	/*Read I frames Interval*/
	ReadIframeInterval(IFRAMES_NAME);
	/*green Save Module*/
	app_init_green_adjust_module();
#ifdef CL4000_DVI
	app_init_screen_adjust_module();
#endif
	gblSetRemoteIndex(index);
	ReadHVTable(&gHVTable, 0);
	ReadHVTable(&gHVTable, 1);
#ifdef CL4000_DVI_SDI
	ReadIPParamTable(IP_PARAM, &gSysParaT);
#endif

	if(DHCPVAL) {
		printf("i will set dhcp.\n");
#if 1
		system("kill -1 `cat /var/run/dhcpcd-eth0.pid`");
		system("/sbin/dhcpcd eth0");
		system("ifconfig eth0");
#endif
		gSysParaT.sysPara.dwNetMark = GetNetmask("eth0");
		gSysParaT.sysPara.dwAddr = GetIPaddr("eth0");
		get_gateway(gateway);
		gSysParaT.sysPara.dwGateWay = 	get_gateway(gateway);
		DEBUG(DL_DEBUG, "gateway =%s\n", gateway);
	} else {
		printf("i will set static ip.\n");
		SetEthConfigIP(gSysParaT.sysPara.dwAddr, gSysParaT.sysPara.dwNetMark);
		SetEthConfigGW(gSysParaT.sysPara.dwGateWay);
	}

	system("ifconfig");

	strcpy(gSysParaT.sysPara.strVer, box_version);
	initSetParam();
	DEBUG(DL_DEBUG, "logo=%d text=%d ,texthandle->enable=%d,texthandle->showtime=%d\n", outputhandle.logo_show, outputhandle.text_show, texthandle->enable, texthandle->showtime);
#ifdef DSS_ENC_1100_1200
	/*open lcd initial*/
	OpenLCDCom(); //matchbox ++
	gblLoadIDX(); //matchbox ++

	if(-2 == ReadDeviceType(DTYPECONFIG_NAME, 1)) {
		ReadDeviceType(DTYPECONFIG_NAME, 0);
	}

	GetDeviceType(devicebuf);
	DEBUG(DL_DEBUG, "DTYPECONFIG_NAME gDeviceType = %s\n", devicebuf);
#endif

	/*取消PIPE坏的信号*/
	Signal(SIGPIPE, SIG_IGN);
	/* Set the priority of this whole process to max (requires root) */
	setpriority(PRIO_PROCESS, 0, -20);
	/*初始化高码流视频编码库参数*/
	InitVideoEncParams(&gSysParaT.videoPara[PORT_ONE]);
	/*初始化低码流视频编码库参数*/
	InitLowRateParams(&gSysParaT.videoPara[PORT_TWO]);
	/*初始化音频编码库参数*/
	InitAudioEncParams(&gSysParaT.audioPara[PORT_ONE]);
	/* Initialize the mutex which protects the global data */
	pthread_mutex_init(&gbl.mutex, NULL);
	/* Initialize Codec Engine runtime */
	CERuntime_init();
	/* Initialize Davinci Multimedia Application Interface */
	Dmai_init();
	closeWatchDog();

	mid_timer_init();
		
	initWatchDog();
#ifdef CL4000_DVI_SDI

	if(gblGetRemoteIndex() < MAX_FAR_CTRL_NUM) {
		result = InitRemoteStruct(gblGetRemoteIndex());
	}

	gRemoteFD = CameraCtrlInit(PORT_COM2);

	if(gRemoteFD <= 0) {
		DEBUG(DL_ERROR, "Initial CameraCtrlInit() Error\n");
	}

#else
#ifndef ENABLE_DEUBG

	if(gblGetRemoteIndex() < MAX_FAR_CTRL_NUM) {
		result = InitRemoteStruct(gblGetRemoteIndex());
	}

	gRemoteFD = CameraCtrlInit(PORT_COM1);

	if(gRemoteFD <= 0) {
		DEBUG(DL_ERROR, "Initial CameraCtrlInit() Error\n");
	}

#endif
#endif
	CreateTCPTask(id_listen);
	/* Initialize the logs. Must be done after CERuntime_init() */
	/*  if(TraceUtil_start(engine->engineName) != TRACEUTIL_SUCCESS)
		{
		    ERR("Failed to TraceUtil_start\n");
			cleanup(EXIT_FAILURE);
		}	*/
	//initMask |= LOGSINITIALIZED;
	app_set_logoshow_flag(outputhandle.logo_show);
	app_set_textshow_flag(outputhandle.text_show)	;
	//setShowLogoTextFlag(outputhandle->logotext);
	addtextdisplay(texthandle);
	/* Determine the number of threads needing synchronization */
	numThreads = 1;
	/*视频线程个数*/
	numThreads += 7;
	/*音频线程个数*/
	numThreads += 1;

	/* Create the objects which synchronizes the thread init and cleanup */
	hRendezvousInit = Rendezvous_create(numThreads, &rzvAttrs);
	hRendezvousCleanup = Rendezvous_create(numThreads, &rzvAttrs);
	hRendezvousWriter = Rendezvous_create(3, &rzvAttrs);

	if(hRendezvousInit == NULL ||
	   hRendezvousCleanup == NULL ||
	   hRendezvousWriter == NULL) {
		ERR("Failed to create Rendezvous objects\n");
		cleanup(EXIT_FAILURE);
	}

	/* Initialize the thread attributes */
	if(pthread_attr_init(&attr)) {
		ERR("Failed to initialize thread attrs\n");
		cleanup(EXIT_FAILURE);
	}

	/* Force the thread to use custom scheduling attributes */
	if(pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED)) {
		ERR("Failed to set schedule inheritance attribute\n");
		cleanup(EXIT_FAILURE);
	}

	/* Set the thread to be fifo real time scheduled */
	if(pthread_attr_setschedpolicy(&attr, SCHED_FIFO)) {
		ERR("Failed to set FIFO scheduling policy\n");
		cleanup(EXIT_FAILURE);
	}


	/* Create the capture fifos */
	captureEnv.to_video_c = Fifo_create(&fAttrs);
	captureEnv.from_video_c = Fifo_create(&fAttrs);
	captureEnv.to_resize_c = Fifo_create(&fAttrs);
	captureEnv.from_resize_c = Fifo_create(&fAttrs);

	if(captureEnv.to_video_c == NULL || captureEnv.from_video_c == NULL ||
	   captureEnv.to_resize_c == NULL || captureEnv.from_resize_c == NULL) {
		ERR("Failed to open display fifos\n");
		cleanup(EXIT_FAILURE);
	}

	LowRateResize.to_videoresize_c = Fifo_create(&fAttrs);
	LowRateResize.from_videoresize_c = Fifo_create(&fAttrs);

	if(LowRateResize.to_videoresize_c == NULL || LowRateResize.from_videoresize_c == NULL) {
		ERR("Failed to open Resize fifos\n");
		cleanup(EXIT_FAILURE);
	}

	/* Set the capture thread priority */
	schedParam.sched_priority = CAPTURE_THREAD_PRIORITY;

	if(pthread_attr_setschedparam(&attr, &schedParam)) {
		ERR("Failed to set scheduler parameters\n");
		cleanup(EXIT_FAILURE);
	}

	/* Create the capture thread */
	captureEnv.hRendezvousInit    = hRendezvousInit;
	captureEnv.hRendezvousCleanup = hRendezvousCleanup;
	DEBUG(DL_DEBUG, "captureThrFxn thread!!!!\n");


	if(pthread_create(&captureThread, &attr, captureThrFxn, &captureEnv)) {
		ERR("Failed to create capture thread\n");
		cleanup(EXIT_FAILURE);
	}

	/* Create the writer fifos */
	writerEnv.to_video_c = Fifo_create(&fAttrs);
	writerEnv.from_video_c = Fifo_create(&fAttrs);
	writerLowRateEnv.to_writelow_c = Fifo_create(&fAttrs);
	writerLowRateEnv.from_writelow_c = Fifo_create(&fAttrs);

	if(writerEnv.to_video_c == NULL || writerEnv.from_video_c == NULL ||
	   writerLowRateEnv.to_writelow_c == NULL || writerLowRateEnv.from_writelow_c == NULL) {
		ERR("Failed to open display fifos\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= CAPTURETHREADCREATED ;
	/*detect thread*/
	detectEnv.hRendezvousInit	  = hRendezvousInit;
	detectEnv.hRendezvousCleanup  = hRendezvousCleanup;

	/* Set the video thread priority */
	schedParam.sched_priority = DETECT_THREAD_PRIORITY;

	if(pthread_attr_setschedparam(&attr, &schedParam)) {
		ERR("Failed to set scheduler parameters\n");
		cleanup(EXIT_FAILURE);
	}

	if(pthread_create(&detectThread, &attr, detectThrFxn, &detectEnv)) {
		ERR("Failed to create detect thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= DETECTTHREADCREATED ;

	/* Set the video thread priority */
	schedParam.sched_priority = VIDEO_THREAD_PRIORITY;

	if(pthread_attr_setschedparam(&attr, &schedParam)) {
		ERR("Failed to set scheduler parameters\n");
		cleanup(EXIT_FAILURE);
	}

	DEBUG(DL_DEBUG, "videoThrFxn thread!!!!\n");

	/* Create the video thread */
	videoEnv.hRendezvousInit    = hRendezvousInit;
	videoEnv.hRendezvousCleanup = hRendezvousCleanup;
	videoEnv.hRendezvousWriter  = hRendezvousWriter;
	videoEnv.to_capture    		= captureEnv.from_video_c;
	videoEnv.from_capture     	= captureEnv.to_video_c;
	videoEnv.to_writer     		= writerEnv.from_video_c;
	videoEnv.from_writer     	= writerEnv.to_video_c;
	videoEnv.videoEncoder       = engine->videoEncoders->codecName;
	videoEnv.engineName         = engine->engineName;


	if(pthread_create(&videoThread, &attr, videoThrFxn, &videoEnv)) {
		ERR("Failed to create video thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= VIDEOTHREADCREATED;

	/* Create the videoResize thread */
	videoLowRateEnv.hRendezvousInit    = hRendezvousInit;
	videoLowRateEnv.hRendezvousCleanup = hRendezvousCleanup;
	videoLowRateEnv.hRendezvousWriter  = hRendezvousWriter;
	videoLowRateEnv.to_resize		  = LowRateResize.from_videoresize_c;
	videoLowRateEnv.from_resize		  = LowRateResize.to_videoresize_c;
	videoLowRateEnv.from_writer    	  = writerLowRateEnv.to_writelow_c;
	videoLowRateEnv.to_writer          = writerLowRateEnv.from_writelow_c;
	videoLowRateEnv.videoEncoder       = engine->videoEncoders->codecName;
	videoLowRateEnv.engineName         = engine->engineName;
	DEBUG(DL_DEBUG, "videoLowRateThrFxn thread!!!!\n");

	if(pthread_create(&videoLowThread, &attr, videoLowRateThrFxn, &videoLowRateEnv)) {
		ERR("Failed to create video thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= VIDEOLOWRATETHREAD;

	/* Create the video thread */
	LowRateResize.hRendezvousInit    = hRendezvousInit;
	LowRateResize.hRendezvousCleanup = hRendezvousCleanup;
	LowRateResize.hRendezvousWriter  = hRendezvousWriter;
	LowRateResize.from_capture		 = captureEnv.to_resize_c;
	LowRateResize.to_capture		 = captureEnv.from_resize_c;
	LowRateResize.videoEncoder       = engine->videoEncoders->codecName;
	LowRateResize.engineName         = engine->engineName;
	/* Set the video thread priority */
	schedParam.sched_priority = VIDEO_THREAD_PRIORITY;

	if(pthread_attr_setschedparam(&attr, &schedParam)) {
		ERR("Failed to set scheduler parameters\n");
		cleanup(EXIT_FAILURE);
	}

	DEBUG(DL_DEBUG, "ResizeLowThrFxn thread!!!!\n");

	if(pthread_create(&resizeLowThread, &attr, ResizeLowThrFxn, &LowRateResize)) {
		ERR("Failed to create video thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= RESIZELOWRATETHREAD;

	Rendezvous_meet(hRendezvousWriter);

	/* Set the writer thread priority */
	schedParam.sched_priority = WRITER_THREAD_PRIORITY;

	if(pthread_attr_setschedparam(&attr, &schedParam)) {
		ERR("Failed to set scheduler parameters\n");
		cleanup(EXIT_FAILURE);
	}

	/* Create the writer thread */
	writerEnv.hRendezvousInit    = hRendezvousInit;
	writerEnv.hRendezvousCleanup = hRendezvousCleanup;
	writerEnv.outBufSize         = videoEnv.outBufSize;

	DEBUG(DL_DEBUG, "writerThrFxn thread!!!!\n");

	if(pthread_create(&writerThread, &attr, writerThrFxn, &writerEnv)) {
		ERR("Failed to create writer thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= WRITERTHREADCREATED;

	/* Create the writer thread */
	writerLowRateEnv.hRendezvousInit         = hRendezvousInit;
	writerLowRateEnv.hRendezvousCleanup      = hRendezvousCleanup;
	writerLowRateEnv.outBufSize              = videoLowRateEnv.outBufSize;

	DEBUG(DL_DEBUG, "writerLowThrFxn thread!!!!\n");

	if(pthread_create(&writerLowThread, &attr, writerLowThrFxn, &writerLowRateEnv)) {
		ERR("Failed to create writerResize thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= WRITELOWRATETHREAD;

	/* Set the thread priority */
	schedParam.sched_priority = AUDIO_THREAD_PRIORITY;

	if(pthread_attr_setschedparam(&attr, &schedParam)) {
		ERR("Failed to set scheduler parameters\n");
		cleanup(EXIT_FAILURE);
	}

	DEBUG(DL_DEBUG, "Audio thread Function!!!!\n");
	/* Create the audio thread */
	audioEnv.hRendezvousInit    = hRendezvousInit;
	audioEnv.hRendezvousCleanup = hRendezvousCleanup;
	audioEnv.engineName         = engine->engineName;
	audioEnv.audioEncoder       = engine->audioEncoders->codecName;

	if(pthread_create(&audioThread, &attr, audioThrFxn, &audioEnv)) {
		ERR("Failed to create speech thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= AUDIOTHREADCREATED;
#ifdef DSS_ENC_1100_1200

	if(pthread_create(&webListenThread, &attr, weblistenThrFxn, NULL)) {
		ERR("Failed to create web listen thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= WEBLISTENCREATED;
#endif
	/* Main thread becomes the control thread */
	ctrlEnv.hRendezvousInit    = hRendezvousInit;
	ctrlEnv.hRendezvousCleanup = hRendezvousCleanup;
	ctrlEnv.engineName         = engine->engineName;
	ret = ctrlThrFxn(&ctrlEnv);

	if(ret == THREAD_FAILURE) {
		status = EXIT_FAILURE;
	}

	DEBUG(DL_DEBUG, "Exit All Thread!!\n");
cleanup:

	/* Make sure the other threads aren't waiting for init to complete */
	if(hRendezvousWriter) {
		Rendezvous_force(hRendezvousWriter);
	}

	if(hRendezvousInit) {
		Rendezvous_force(hRendezvousInit);
	}

	DEBUG(DL_DEBUG, "EXIT Common Mutex!!!\n");
	DestorygblCommonMutex();
	DEBUG(DL_DEBUG, "EXIT pthread Mutex!!!\n");
	DestroyMutexPthread();

	if(initMask & AUDIOTHREADCREATED) {
		if(pthread_join(audioThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	DEBUG(DL_DEBUG, "EXIT audio pThread!!!\n");

	if(initMask & VIDEOTHREADCREATED) {
		if(pthread_join(videoThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	DEBUG(DL_DEBUG, "EXIT video pThread!!!\n");

	if(initMask & WRITERTHREADCREATED) {
		if(pthread_join(writerThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	DEBUG(DL_DEBUG, "EXIT write pThread!!!\n");

	if(initMask & CAPTURETHREADCREATED) {
		if(pthread_join(captureThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	DEBUG(DL_DEBUG, "EXIT capture pThread!!!\n");

	if(initMask & VIDEOLOWRATETHREAD) {
		if(pthread_join(videoLowThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	if(initMask & RESIZELOWRATETHREAD) {
		if(pthread_join(resizeLowThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	if(initMask & WRITELOWRATETHREAD) {
		if(pthread_join(writerLowThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	if(pthread_join(id_listen[PORT_ONE], &ret) == 0) {
		if(ret == THREAD_FAILURE) {
			status = EXIT_FAILURE;
		}
	}

	if(captureEnv.to_video_c) {
		Fifo_delete(captureEnv.to_video_c);
	}

	if(captureEnv.from_video_c) {
		Fifo_delete(captureEnv.from_video_c);
	}

	if(captureEnv.to_resize_c) {
		Fifo_delete(captureEnv.to_resize_c);
	}

	if(captureEnv.from_resize_c) {
		Fifo_delete(captureEnv.from_resize_c);
	}

	if(writerEnv.to_video_c) {
		Fifo_delete(writerEnv.to_video_c);
	}

	if(writerEnv.from_video_c) {
		Fifo_delete(writerEnv.from_video_c);
	}

	if(writerLowRateEnv.from_writelow_c) {
		Fifo_delete(writerLowRateEnv.from_video_c);
	}

	if(writerLowRateEnv.to_writelow_c) {
		Fifo_delete(writerLowRateEnv.to_writelow_c);
	}

	if(LowRateResize.to_videoresize_c) {
		Fifo_delete(LowRateResize.to_videoresize_c);
	}

	if(LowRateResize.from_videoresize_c) {
		Fifo_delete(LowRateResize.from_videoresize_c);
	}

	DEBUG(DL_DEBUG, "EXIT Rendezvous cleanup pThread!!!\n");

	if(hRendezvousCleanup) {
		Rendezvous_delete(hRendezvousCleanup);
	}

	DEBUG(DL_DEBUG, "EXIT Rendezvous init pThread!!!\n");

	if(hRendezvousInit) {
		Rendezvous_delete(hRendezvousInit);
	}

	DEBUG(DL_DEBUG, "EXIT Rendezvous cleanup pThread!!!\n");
	/*
	    if (initMask & LOGSINITIALIZED) {
	        TraceUtil_stop();
		}	*/
	DEBUG(DL_DEBUG, "EXIT TraceUtil_stop !!!\n");
	pthread_mutex_destroy(&gbl.mutex);
	DEBUG(DL_DEBUG, "process EXIT!!!\n");
	exit(1);
}
Beispiel #10
0
/*********************************************************
 ******************    Main Function    ******************
 *********************************************************/
int main(int agrc, char *agrv[])
{
    /**
     * cmd parameter
     */ 
    int  help_flag       = 0;
    int  ipv6_flag       = 0;
    int  ser_flag        = 0;
    int  cli_flag        = 0;
    int  ser_or_cli_flag = -1;
    int  socket_protocol = -1;
    int  socket_type     = -1;
    int  net_type        = AF_INET;
    int  times           = 1;
    char *protocol       = NULL;
    char *message        = NULL;
    char *ip             = NULL;
    int  port            = 0;
    int  rt              = 0;
    int  local_ip_flag   = 0;
    char local_ip[256]   = {0};
    int gateway_ip_flag  = {0};
    char gateway_ip[128] = {0};
    char *ifname         = NULL;
    unsigned char local_mac[6] = {0};
    char *remote_mac     = NULL;
    char remote_ip[20]   = {0};

    struct options opts[] = {
        {"-h", "--help"      , 0, RET_INT, ADDR_ADDR(help_flag)     },
        {"-6", NULL          , 0, RET_INT, ADDR_ADDR(ipv6_flag)     },
        {"-s", "--server"    , 0, RET_INT, ADDR_ADDR(ser_flag)      },
        {"-c", "--client"    , 0, RET_INT, ADDR_ADDR(cli_flag)      },
        {"-a", "--agreement" , 1, RET_STR, ADDR_ADDR(protocol)      },
        {"-i", "--ip"        , 1, RET_STR, ADDR_ADDR(ip)            },
        {"-p", "--port"      , 1, RET_INT, ADDR_ADDR(port)          },
        {"-t", "--times"     , 1, RET_INT, ADDR_ADDR(times)         },
        {"-m", "--message"   , 1, RET_STR, ADDR_ADDR(message)       },
        {"-l", "--localip"   , 0, RET_INT, ADDR_ADDR(local_ip_flag) },
        {"-g", "--gatewayip" , 0, RET_INT, ADDR_ADDR(gateway_ip_flag)},
        {NULL, "--mac"       , 1, RET_STR, ADDR_ADDR(ifname)        },
        {"-r", "--remoteip"  , 1, RET_STR, ADDR_ADDR(remote_mac)    },
        {NULL, NULL}
    };
    struct usage help_usage[] = {
        {"-s, --server",                 "Create a socket server"},
        {"-c, --client",                 "Create a socket client"},
        {"-a, --agreement [Agreement]",  "Agreement of networking. Agreement can be \"[u udp t tcp]\""},
        {"-i, --ip [ip address]",        "IP address"},
        {"-p, --port [port]",            "Port"},
        {"-t, --times [times]",          "Times of sending message"},
        {"-m, --message [message]",      "Message of sending"},
        {"-l, --localip",                "Local ip address"},
        {"-g, --gatewayip",              "Gateway ip address"},
        {"--mac [interface name]",       "Get mac address by interface name."},
        {"-r, --remoteip [mac address]", "Get remote ip address."},
        {"-h, --help",                   "Program usage"},
        {NULL,                           NULL}
    };
 
    /**
     * check count of cmdline arguemnts
     */
    set_print_usage_width(60);
    if (agrc <= 1) {
       print_usage(help_usage);
       exit(-1);
    }

    /**
     * parser args
     */
    get_args(agrc, agrv, opts);
    if(help_flag > 0) {
        print_usage(help_usage);
        exit(1);
    }

    /**
     * get mac addree by interface name
     */
    if (ifname) {
        if (get_mac(ifname, local_mac, sizeof(local_mac)) < 0)
            return -1;
        print_mac(local_mac, NULL);
        return 0;
    }

    /**
     * get remote ip address by mac address
     */
    if (remote_mac) {
        if (get_remote_ip_by_mac(remote_mac, remote_ip, sizeof(remote_ip), 0) < 0)
            return -1;
        printf("%s\n", remote_ip);
        return 0;
    }

    /**
     * Get Local IP Address
     */
    if (ipv6_flag > 0) net_type = AF_INET6;
    if (local_ip_flag) {
        if (get_local_ip(net_type, NULL, local_ip, sizeof(local_ip)) < 0) {
            exit(-1);
        }
        printf("%s\n", local_ip);
        exit(0);
    }

    /**
     * get gateway ip address
     */ 
    if (gateway_ip_flag) {
        if (get_gateway(gateway_ip, sizeof(gateway_ip)) < 0) {
            exit(-1);
        }
        printf("%s\n", gateway_ip);
        exit(0);
    }

    /**
     * socket server or client
     */
    if (ser_flag > 0) ser_or_cli_flag = SOCKET_SERVER;
    else if (cli_flag > 0) ser_or_cli_flag = SOCKET_CLIENT;

    /**
     * socket protocol
     */
    if (protocol != NULL) {
        if (!strncmp("u", protocol, sizeof("u")) || !strncmp("udp", protocol, sizeof("udp"))) {
            socket_protocol = IPPROTO_UDP;
            socket_type = SOCK_DGRAM;
        } else if (!strncmp("t", protocol, sizeof("t")) || !strncmp("tcp", protocol, sizeof("tcp"))) {
            socket_protocol = IPPROTO_TCP;
            socket_type = SOCK_STREAM;
        } else {
            fprintf(stderr, "Invalid arguemnt\n");
            exit(1);
        }
        
    }

    /**
     * start up socket
     */
    start_network(ser_or_cli_flag, net_type, socket_type, socket_protocol, ip, port, times, message);

    return rt;
}