unsigned int str_to_ip(const char * const ip_str) { struct in_addr ip; if ( NULL == ip_str ) return 0; if ( 0 != inet_aton(ip_str, &ip) ) { return (unsigned int)(ntohl(ip.s_addr)); } else { return 0; } } int str_to_mac(const char * mac_str, char * mac) { int i; char str[3] = {0}; char *endptr; if ( NULL == mac_str || NULL == mac ) return -1; errno = 0; for ( i = 0; i < 6 && NULL != mac_str ; i++ ) { strncpy(str, mac_str, 2); mac[i] = strtol(str, &endptr, 16); if ( (errno == ERANGE && (mac[i] == LONG_MAX || mac[i] == LONG_MIN)) || (errno != 0 && mac[i] == 0) || (endptr == str) ) // error { mac[i] = 0; break; } mac_str = strstr(mac_str, ":") + 1; } if ( i != 6 ) return -1; else return NVD_OK; } unsigned int get_local_ip(const char * const name) { int sock; struct ifreq ifr; struct in_addr ip; if ((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0) { return 0; } memset(&ifr, 0, sizeof(struct ifreq)); sprintf(ifr.ifr_name, name); if (ioctl(sock, SIOCGIFADDR, (char*)&ifr)) { close(sock); return 0; } ip.s_addr = *(unsigned int*)&ifr.ifr_addr.sa_data[2]; close(sock); return (unsigned int)ip.s_addr; } int get_net_status(const char * const name) { int sock; struct ifreq ifr; if ((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0) { return NVD_ERR_NET; } memset(&ifr, 0, sizeof(struct ifreq)); sprintf(ifr.ifr_name, name); if (ioctl(sock, SIOCGIFFLAGS, (char*)&ifr)) { close(sock); return NVD_ERR_NET; } if ((ifr.ifr_flags & IFF_UP) && (ifr.ifr_flags & IFF_RUNNING)) { close(sock); return NVD_OK; } else { close(sock); return NVD_ERR_NET; } } unsigned int get_ip_by_domain(const char * const domain) { struct hostent *he; struct in_addr ip; he = gethostbyname(domain); if (NULL == he) { return 0; } ip.s_addr = *((unsigned int*)(he->h_addr)); return (unsigned int)ip.s_addr; }
#define IP_ARRAY(addr) \ ((unsigned char *)&addr)[3], \ ((unsigned char *)&addr)[2], \ ((unsigned char *)&addr)[1], \ ((unsigned char *)&addr)[0] #define IP_STRING "%u.%u.%u.%u"
#define MAC_ARRAY(addr) \ ((unsigned char *)addr)[0], \ ((unsigned char *)addr)[1], \ ((unsigned char *)addr)[2], \ ((unsigned char *)addr)[3], \ ((unsigned char *)addr)[4], \ ((unsigned char *)addr)[5] #define MAC_STRING "%02x:%02x:%02x:%02x:%02x:%02x"