#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/ethernet.h>
#include <netinet/if_ether.h>
#include <linux/if_packet.h>
#include <linux/if.h>
#include <net/if_arp.h>
#include <arpa/inet.h>
#include "api.h"



// size_t strlcpy(char *dest, const char *src, size_t dest_size)
// {
//     register char *d = dest;
//     register const char *s = src;
//     register size_t n = dest_size;

//     /* Copy as many bytes as will fit */
//     if (n != 0 && --n != 0) {
//         do {
//             if ((*d++ = *s++) == 0)
//                 break;
//         } while (--n != 0);
//     }

//     /* Not enough room in dest, add NUL and traverse rest of src */
//     if (n == 0) {
//         if (dest_size != 0)
//             *d = '\0'; /* NUL-terminate dest */
//         while (*s++)
//             ;
//     }

//     return (s - src - 1); /* count does not include NUL */
// }
int mac_hex2mac_string(char *mac_hex, char *mac_str)
{
	if (!mac_hex || !mac_str)
	{
		return ERROR;
	}

	snprintf(mac_str, STR_MAC_LEN, "%02x-%02x-%02x-%02x-%02x-%02x",
			(unsigned char)mac_hex[0], (unsigned char)mac_hex[1], (unsigned char)mac_hex[2],
			(unsigned char)mac_hex[3], (unsigned char)mac_hex[4], (unsigned char)mac_hex[5]);

	return OK;
}
int mac_string2mac_hex(char *mac_str, char *mac_hex)
{
	int tmp[MAC_HEX_LEN] = {0};

	int i;

	if (!mac_str || !mac_hex)
	{
		return ERROR;
	}

	if (!strchr(mac_str,':') && !strchr(mac_str,'-'))
	{
		sscanf(mac_str, "%2x%2x%2x%2x%2x%2x",
			&tmp[0], &tmp[1], &tmp[2], &tmp[3], &tmp[4], &tmp[5]);
	}
	else
	{
		sscanf(mac_str, "%x%*[:-]%x%*[:-]%x%*[:-]%x%*[:-]%x%*[:-]%x",
			&tmp[0], &tmp[1], &tmp[2], &tmp[3], &tmp[4], &tmp[5]);
	}
	for (i = 0; i < MAC_HEX_LEN; i++)
	{
		mac_hex[i] = tmp[i];
	}

	return OK;
}
int get_local_macaddr(char *dev_name, char *mac_str)
{
	int sock;
	struct ifreq ifr_mac;

	if (!dev_name || !mac_str)
	{
		return ERROR;
	}

	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock < 0)
	{
		perror("socket");
		return ERROR;
	}

	memset(&ifr_mac, 0, sizeof(struct ifreq));

	strlcpy(ifr_mac.ifr_name, dev_name, sizeof(ifr_mac.ifr_name));

	if (ioctl(sock, SIOCGIFHWADDR, &ifr_mac) < 0)
	{
		perror("ioctl");
		close(sock);
		return ERROR;
	}

	close(sock);

	mac_hex2mac_string(ifr_mac.ifr_hwaddr.sa_data, mac_str);

	return OK;
}


unsigned char csum(unsigned char *addr, int count)
{
	unsigned int sum = 0;

	if (!addr)
	{
		return 0;
	}

	while (count > 0)
	{
		sum   += *addr;
		addr  += 1;
		count -= 1;
	}
	return sum;
}

