【写给自己的开发知识树】——常用函数封装

记录一些经常用到的功能函数的封装,以后遇到类似的功能直接用。

hutil.c

#include "hutil.h"

void util_random_uuid(char *buf)
{
	if(NULL == buf)return;
	
    const char *c = "89ab";
    char *p = buf;
    int n;
    for( n = 0; n < 16; ++n )
    {
        int b = rand()%255;
        switch( n )
        {
            case 6:
                sprintf(p, "4%x", b%15 );
            break;
            case 8:
                sprintf(p, "%c%x", c[rand()%strlen(c)], b%15 );
            break;
            default:
                sprintf(p, "%02x", b);
            break;
        }
 
        p += 2;
        switch( n )
        {
            case 3:
            case 5:
            case 7:
            case 9:
                *p++ = '-';
                break;
        }
    }
    *p = 0;
    return ;
}

int util_split( char *dest[], char *src, const char *separator)
{
    char *curr = NULL;
    int count = -1;

    if(NULL == dest || NULL == src || NULL == separator)
        return count;

    // 获取第一个字符串
    curr = strtok(src, separator);
    count++;

    // 继续获取其他的子字符串
    while(NULL != curr)
    {
        count++;
        *dest++ = curr;
        curr = strtok(NULL, separator);
    }

    return count;
}

void util_print_time(const char *fun, int line)
{
	struct timeval tv;
	
	gettimeofday(&tv, NULL);
	
	time_t now = time(NULL);
	struct tm ltm = {0};
	localtime_r(&now, &ltm);

	printf("[%s:%d][%04d-%02d-%02d %02d:%02d:%02d.%03ld] ",fun, line, ltm.tm_year + 1900, 
		ltm.tm_mon+1, ltm.tm_mday,ltm.tm_hour, ltm.tm_min, ltm.tm_sec,tv.tv_usec/1000);
}

int util_get_file_size(const char *FileName)
{
	int filesize = -1;      
    struct stat statbuff;  
    if(stat(FileName, &statbuff) < 0)
	{  
        return filesize;  
    }
	else
	{  
        filesize = statbuff.st_size;  
    }  
    return filesize;  
}

int util_block_until_readable(int socket, struct timeval* timeout) 
{
  int result = -1;
  do {
    fd_set rd_set;
    FD_ZERO(&rd_set);
    if (socket < 0) break;
    FD_SET((unsigned) socket, &rd_set);
    const unsigned numFds = socket+1;

    result = select(numFds, &rd_set, NULL, NULL, timeout);
    if (timeout != NULL && result == 0) 
	{
      break; // this is OK - timeout occurred
    } 
	else if (result < 0) 
	{
      int err = errno;
      if (err == EINTR || err == EAGAIN || err == EWOULDBLOCK) continue;
      printf("select() error: %s\n", strerror(errno));
      break;
    }

    if (!FD_ISSET(socket, &rd_set)) 
	{
      printf("select() error - !FD_ISSET");
      break;
    }
	
  } while (0);

  return result;
}
int util_block_until_writeable(int socket, struct timeval* timeout) 
{
  int result = -1;
  do {
    fd_set wt_set;
    FD_ZERO(&wt_set);
    if (socket < 0) break;
    FD_SET((unsigned) socket, &wt_set);
    const unsigned numFds = socket+1;

    result = select(numFds, NULL, &wt_set, NULL, timeout);
    if (timeout != NULL && result == 0) 
	{
      break; // this is OK - timeout occurred
    } 
	else if (result < 0) 
	{
      int err = errno;
      if (err == EINTR || err == EAGAIN || err == EWOULDBLOCK) continue;
      printf("select() error: %s\n", strerror(errno));
      break;
    }

    if (!FD_ISSET(socket, &wt_set)) 
	{
      printf("select() error - !FD_ISSET");
      break;
    }
	
  } while (0);

  return result;
}

/****************************获取本地ip mac开始*******************************/
//struct ifaddrs
//{
//    struct ifaddrs  *ifa_next;    /* Next item in list */
//    char            *ifa_name;    /* Name of interface */
//    unsigned int     ifa_flags;   /* Flags from SIOCGIFFLAGS */
//    struct sockaddr *ifa_addr;    /* Address of interface */
//    struct sockaddr *ifa_netmask; /* Netmask of interface */
//    union
//    {
//        struct sockaddr *ifu_broadaddr; /* Broadcast address of interface */
//        struct sockaddr *ifu_dstaddr; /* Point-to-point destination address */
//    } ifa_ifu;
//    #define              ifa_broadaddr ifa_ifu.ifu_broadaddr
//    #define              ifa_dstaddr   ifa_ifu.ifu_dstaddr
//    void            *ifa_data;    /* Address-specific data */
//}; 
int util_show_all_eth_ip(int enable_ipv6,char ips[][16],int maxIpsNum,char hosts[][16])
{

	struct ifaddrs *ifaddr, *ifa;
    int family, s;
	char host_ip[64] = {0};
	int i = 0;

    if(-1 == getifaddrs(&ifaddr))
    {
        perror("getifaddrs");
        return 1;
    }

    for(ifa = ifaddr; (ifa != NULL) && (i<maxIpsNum) ; ifa = ifa->ifa_next)
    {
        if(NULL == ifa->ifa_addr)
            continue;
		
        family = ifa->ifa_addr->sa_family;//printf("======%s,%d\n", ifa->ifa_name,family);
        if(!strcmp(ifa->ifa_name, "lo"))
            continue;

		if(!enable_ipv6)
		{
			if(family == AF_INET6)
				continue;
		}
		memset(host_ip, 0, sizeof(host_ip));
		s = getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), host_ip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
		if(0 != s)
		{
			
            //printf("getnameinfo: %s\n", gai_strerror(s));
			continue;
		}
		if(hosts != NULL)
		{
			snprintf(hosts[i], sizeof(hosts[i]), "%s", ifa->ifa_name);
		}
		snprintf(ips[i], sizeof(ips[i]), "%s", host_ip);i++;
		//printf("%s=%s\n", ifa->ifa_name, host_ip);
    }
	freeifaddrs(ifaddr);

    return 1;
	
}
int util_get_local_ip(const char* ethName, char* ip)
{
	int newSocket = socket(AF_INET, SOCK_STREAM, 0);
	if (newSocket < 0) {
	  //printf("unable to create stream socket: %d\n", errno);
	  return 1;
	}

	fcntl(newSocket, F_SETFD, FD_CLOEXEC);	
	
	struct sockaddr_in *server_sin;
	struct ifreq ifr_ip;

	memset(&ifr_ip, 0, sizeof(ifr_ip));
	strncpy(ifr_ip.ifr_name, ethName, sizeof(ifr_ip.ifr_name) - 1);

	if( ioctl( newSocket, SIOCGIFADDR, &ifr_ip) < 0 )
	{
		//printf("[getLocalIP]unable get ip, ethName %s\n", ethName); 
		close(newSocket);
		return 1;
	}
	server_sin = (struct sockaddr_in *)&ifr_ip.ifr_addr;
	strcpy(ip, inet_ntoa(server_sin->sin_addr));

	close(newSocket);
	return 0;
}
int util_get_local_MAC(const char* ethName, char* pMAC)
{
	int  s = -1;   
	struct   ifreq   ifr;   
	
	s = socket(AF_INET,SOCK_STREAM, 0); //SOCK_DGRAM  
	if (s < 0) {
	  printf("ERROR: CommFun::getLocalMAC unable to create SOCK_DGRAM socket: %d\n", errno);
	  return 1;
	}

	fcntl(s, F_SETFD, FD_CLOEXEC);	
	
	strncpy(ifr.ifr_name, ethName, sizeof(ifr.ifr_name) - 1);
	ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0';
	if(ioctl(s, SIOCGIFHWADDR, &ifr) < 0)
	{
		perror("ERROR:CommFun::getLocalMAC unable get MAC\n"); 
		close(s);
		return 1;
	}
		
	sprintf(pMAC,"%02x:%02x:%02x:%02x:%02x:%02x",
		(unsigned char)ifr.ifr_hwaddr.sa_data[0],
		(unsigned char)ifr.ifr_hwaddr.sa_data[1],
		(unsigned char)ifr.ifr_hwaddr.sa_data[2],
		(unsigned char)ifr.ifr_hwaddr.sa_data[3],
		(unsigned char)ifr.ifr_hwaddr.sa_data[4],
		(unsigned char)ifr.ifr_hwaddr.sa_data[5]);  
	
	close(s);
	return 0; 
}
/****************************获取本地ip 结束*******************************/
/****************************获取时间 开始*******************************/
/*1970年1月1日0时0分0秒到该时间点所经过的秒数,long	
time_t now;	

struct tm {
	int tm_sec;       秒 – 取值区间为[0,59]
	int tm_min;       分 - 取值区间为[0,59]
	int tm_hour;      时 - 取值区间为[0,23]
	int tm_mday;      一个月中的日期 - 取值区间为[1,31] 
	int tm_mon;       月份(从一月开始,0代表一月) - 取值区间为[0,11]
	int tm_year;      年份,其值等于实际年份减去1900 
	int tm_wday;      星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 
	int tm_yday;      从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 
	int tm_isdst;     夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。
}
struct tm now_tm;

struct timeval
{
	__time_t tv_sec;        Seconds. 
	__suseconds_t tv_usec;  Microseconds.微秒
}
struct timeval now_tv;
*/

void  util_convert_time_str_long2(char *str_time, char *l_time)
{
	if((NULL == l_time)
		|| (NULL == str_time)
		|| (20 > strlen(str_time)))
	{
		return;
	}
	
	//通行时间2020-04-27T00:00:00Z
	int iYear = 0;
	int iMonth = 0;
	int iDay = 0;
	int iHour = 0;
	int iMinute = 0;
	int iSecond = 0;

	sscanf(str_time,"%04d-%02d-%02dT%02d:%02d:%02dZ", &iYear, &iMonth,&iDay,&iHour,&iMinute,&iSecond);	
	sprintf(l_time, "%04d%02d%02d%02d%02d%02d", iYear, iMonth,iDay,iHour,iMinute,iSecond);

	return;
}
void  util_convert_time_str_long(char *str_time, char *l_time)
{
	if((NULL == l_time)
		|| (NULL == str_time)
		|| (23 > strlen(str_time)))
	{
		return;
	}
	
	//通行时间
	int iYear = 0;
	int iMonth = 0;
	int iDay = 0;
	int iHour = 0;
	int iMinute = 0;
	int iSecond = 0;
	int iMSec = 0;

	sscanf(str_time,"%04d-%02d-%02d %02d:%02d:%02d.%03d", &iYear, &iMonth,&iDay,&iHour,&iMinute,&iSecond,&iMSec);	
	sprintf(l_time, "%04d%02d%02d%02d%02d%02d%03d", iYear, iMonth,iDay,iHour,iMinute,iSecond,iMSec);

	return;
}
void  util_convert_time_long_str(char *l_time, char *str_time)
{
	if((NULL == l_time)
		|| (NULL == str_time)
		|| (17 > strlen(l_time)))
	{
		return;
	}
	
	//通行时间
	int iYear = 0;
	int iMonth = 0;
	int iDay = 0;
	int iHour = 0;
	int iMinute = 0;
	int iSecond = 0;
	int iMSec = 0;

	sscanf(l_time, "%04d%02d%02d%02d%02d%02d%03d", &iYear, &iMonth,&iDay,&iHour,&iMinute,&iSecond,&iMSec);
	sprintf(str_time,"%04d-%02d-%02d %02d:%02d:%02d.%03d", iYear, iMonth,iDay,iHour,iMinute,iSecond,iMSec);	

	return;
}
void util_get_now_msec(long *now_msec)
{
	if(NULL == now_msec)return;
	
	struct timeval now_tv;
	gettimeofday(&now_tv, NULL);
	*now_msec = now_tv.tv_usec;

	return;
}

void util_get_now_time_str_YYmmddHHMMSS(char *now)
{
	if(NULL == now)return;

	time_t now_time = time(NULL);
	struct tm now_tm;
	localtime_r(&now_time, &(now_tm));
	
	sprintf(now, "%04d%02d%02d%02d%02d%02d",
				now_tm.tm_year + 1900,
				now_tm.tm_mon+1,
				now_tm.tm_mday,
				now_tm.tm_hour,
				now_tm.tm_min,
				now_tm.tm_sec);

	return;
}

void util_get_now_time_str_YYmmddHHMMSS_en(char *now)
{
	if(NULL == now)return;

	char now_str[64] = {0};
	time_t now_time = time(NULL);
	struct tm now_tm;
	localtime_r(&now_time, &(now_tm));
	
	sprintf(now_str, "%04d-%02d-%02d %02d:%02d:%02d",
				now_tm.tm_year + 1900,
				now_tm.tm_mon+1,
				now_tm.tm_mday,
				now_tm.tm_hour,
				now_tm.tm_min,
				now_tm.tm_sec);

	return;
}
void util_get_now_time_str_YYmmddHHMMSS_cn(char *now)
{
	if(NULL == now)return;

	char now_str[128] = {0};
	time_t now_time = time(NULL);
	struct tm now_tm;
	localtime_r(&now_time, &(now_tm));
	
	sprintf(now_str, "%04d年%02d月%02d日 %02d时%02d分%02d秒",
				now_tm.tm_year + 1900,
				now_tm.tm_mon+1,
				now_tm.tm_mday,
				now_tm.tm_hour,
				now_tm.tm_min,
				now_tm.tm_sec);

	return;
}
/****************************获取时间 开始*******************************/

/****************************执行shell脚本 开始*******************************/
int util_get_shell_cmd_return(const char *cmd, char * ret, unsigned int retLen)
{
	if((NULL == cmd) || (NULL == ret))
	{
		return 1;
	}
	
	FILE *fs = NULL;
	char buff[512] = {0}; 
	unsigned int buffLen = 0;

	memset(ret, 0, retLen);
	
	if(NULL == (fs = popen(cmd,"r")))      
    {     
        fprintf(stderr,"execute command failed: %s",strerror(errno));      
        return 1;      
    }  
	
	while(NULL != fgets(buff, sizeof(buff), fs)) 
    {  
		buffLen = strlen(buff);
		if(buffLen < retLen)
		{
			strcat(ret, buff);
			retLen -= buffLen;
		}
		else
		{
			strncat(ret, buff, retLen-1);
			break;
		}
			
    }  
	
    pclose(fs);  
	
	return 0;
}
/****************************执行shell脚本 结束*******************************/

/****************************判断连接 开始*******************************/
static int check_connection_ping(const char *strIpAddr, int *connState)
{
	char ret[512] = {0};
	char cmd[32] = {0};
	snprintf(cmd, sizeof(cmd), "ping %s -c 1", strIpAddr);
	util_get_shell_cmd_return(cmd, ret, sizeof(ret));
	
	if(strstr(ret, "1 received, 0% packet loss") != NULL)
	{
		*connState = 1;
	}
	return 0;
}
int util_check_connection(const char *strIpAddr, int port, int *connState)
{
	if(strIpAddr == NULL || connState == NULL)
	{
		return 1;
	}
	
	*connState = 0;
	
	if(port == 0)
	{
		return check_connection_ping(strIpAddr, connState);
	}

	int newSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (newSocket < 0) {
		//printf("unable to create stream socket: %d\n", errno);
		return 1;
	}

	int curFlags = fcntl(newSocket, F_GETFL, 0);
	if(fcntl(newSocket, F_SETFL, curFlags|O_NONBLOCK) < 0)
	{
		//printf("failed to make non-blocking: %d\n", errno);
		close(newSocket);
		return 1;
	}
	
	struct sockaddr_in remoteAddr;
	remoteAddr.sin_family = AF_INET;
	remoteAddr.sin_addr.s_addr = inet_addr(strIpAddr);
	remoteAddr.sin_port = htons(port);

	if(connect(newSocket, (struct sockaddr*)&remoteAddr, sizeof(remoteAddr)) < 0) 
	{
		if(errno != EINPROGRESS && errno != EWOULDBLOCK)
		{
			//printf("connect(%d) error: %s\n", newSocket, strerror(errno));
			close(newSocket);
			return 1;
		}
	}
	else
	{
		//printf("connect completed immediately\n");
		close(newSocket);
		*connState = 1;
		return 0;
	}
	
	fd_set wr_set;
	FD_ZERO(&wr_set);
	//FD_ZERO(&rd_set);
	FD_SET((unsigned) newSocket, &wr_set);
	//FD_SET((unsigned) newSocket, &rd_set);
	const unsigned numFds = newSocket + 1;

	struct timeval timeout;
	timeout.tv_sec = 2;
	timeout.tv_usec = 0;

	int result = 0;
	while(((result=select(numFds+1, NULL, &wr_set,	NULL, &timeout))==-1)&&errno==EINTR);
	if(result==0)
	{
		//printf("timeout occured, %s, %d\n", strIpAddr, port);
		close(newSocket);
		newSocket=-1;
		return 1;
	}
	else if(result < 0)
	{
		//printf("select error: %s, %s, %d\n", strerror(errno), strIpAddr, port);
		close(newSocket);
		return 1;
	}
	else if(FD_ISSET(newSocket, &wr_set)) 
	{
		//printf("connection ip %s, port %d, result %d\n"	, strIpAddr, port, result);

		int error = 0;
		socklen_t len = sizeof (error);
		if(getsockopt(newSocket, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
		{
			//printf ("getsockopt fail,connected fail\n");
			close(newSocket);
			newSocket=-1;
			return 1;
		}

		//printf("error %d, ip %s, port %d\n", error, strIpAddr, port);
		
		if (error == ETIMEDOUT)
		{
			//printf("connected timeout\n");
			close(newSocket);
			newSocket=-1;
			return 1;
		}
		else if(error == ECONNREFUSED)
		{
			//printf("No one listening on the remote address.\n");
			close(newSocket);
			newSocket=-1;
			return 1;
		}
		else if(error)
		{
			//printf("%s\n", strerror(error));
			close(newSocket);
			newSocket=-1;
			return 1;
		}
		
		close(newSocket);
		*connState = 1;
		
		return 0;
	}

	close(newSocket);
	newSocket = -1;
	
	return 0;
}
/****************************判断连接 结束*******************************/

/****************************日志 开始*******************************/
#define PRINT_COLOR_GREEN_STR  	"\033[0;32m"
#define PRINT_COLOR_YELLOW_STR  	"\033[0;33m"
#define PRINT_COLOR_RED_STR  		"\033[0;31m"
#define PRINT_COLOR_TAIL_STR  	"\033[0;39m"
#define PRINT_COLOR_HEAD_STR_LEN (10)
#define PRINT_COLOR_TAIL_STR_LEN (10)

static int g_logLevel = LOG_LEVEL_TOTAL;
static char g_logFilePath[128] = {0};

static void print_color_head(LOG_LEVEL_EM lv)
{
	switch (lv)
	{
		case LOG_LEVEL_INFO:
			break;
		case LOG_LEVEL_KEY:
			fprintf(stdout, PRINT_COLOR_GREEN_STR);
			break;
		case LOG_LEVEL_WARN:
			fprintf(stdout, PRINT_COLOR_YELLOW_STR);
			break;
		case LOG_LEVEL_ERROR:
			fprintf(stdout, PRINT_COLOR_RED_STR);
			break;
		case LOG_LEVEL_FATAL:
			fprintf(stdout, PRINT_COLOR_RED_STR);
			//exit(1);
			break;
		default:
			break;
	}
}

static void print_content_head(const char *fun, long line, FILE *out)
{
	char printBuffHead[256] = {0};
	struct tm stTm = {0};
	time_t now = time(NULL);
	
	localtime_r(&now, &stTm);
	snprintf(printBuffHead, sizeof(printBuffHead), "[%04d-%02d-%02d %02d:%02d:%02d][%s][%05ld]",
							stTm.tm_year+1900,
							stTm.tm_mon+1,
							stTm.tm_mday,
							stTm.tm_hour, 
							stTm.tm_min, 
							stTm.tm_sec,
							fun,
							line);


	fprintf(out, "%s", printBuffHead);
}

static int print_content(char* fmt, va_list *args, FILE *out)
{
	vfprintf(out, fmt, *args);	
	fflush(stdout);
	return 0;
}

static void print_color_tail()
{
	fprintf(stdout, PRINT_COLOR_TAIL_STR);
}

int util_log(LOG_LEVEL_EM lv, const char *fun, long line, char* fmt, ...)
{
	if(lv > g_logLevel)
	{
		return 1;
	}
	
	if(NULL == fun)
	{
		fun = " ";
	}
	
	va_list args;
	va_start(args, fmt);
	char logFile[256] = {0};
	char fileName[32] = {0};
	int logFilePathLen = strlen(g_logFilePath);
	
	if(0 == logFilePathLen)
	{
		print_color_head(lv);
		print_content_head(fun, line, stdout);
		print_content(fmt, &args, stdout);
		print_color_tail();
	}
	else
	{
		if('/' == g_logFilePath[logFilePathLen-1])
		{
			snprintf(logFile, sizeof(logFile),"%s%s", g_logFilePath, fileName);
		}
		else
		{
			snprintf(logFile, sizeof(logFile),"%s/%s", g_logFilePath, fileName);
		}
		
		//打开文件然后写入
	}

	va_end(args);
	return 0;
}

static int set_log_file_path(const char *logFilePath)
{
	if(NULL == logFilePath)
	{
		memset(g_logFilePath, 0, sizeof(g_logFilePath));
		return 0;
	}
	
	snprintf(g_logFilePath, sizeof(g_logFilePath), "%s", logFilePath);
	
	return 0;
}

static int SetLogLevel(LOG_LEVEL_EM lv)
{
	g_logLevel = lv;
	
	return 0;
}

LOG_LEVEL_EM util_get_log_level()
{
	return (LOG_LEVEL_EM)g_logLevel;
}

char * util_get_log_file_path()
{
	return g_logFilePath;
}

int util_log_init(LOG_LEVEL_EM lv, const char *logFilePath)
{
	SetLogLevel(lv);
	logFilePath = NULL;
	return 0;
}
/****************************日志 结束*******************************/

hutil.h

#ifndef __H_UTIL_H__
#define __H_UTIL_H__

#include <dirent.h>  
#include <stdio.h>   
#include <stdlib.h>
#include <stdarg.h>  
#include <string.h>  
#include <time.h> 
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <ifaddrs.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sys/time.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/socket.h> 
#include <netdb.h> 
#include <net/if.h>
#include <sys/ioctl.h>

#ifdef __cplusplus
extern "C" 
{
#endif

//内存
#define UTIL_P_FREE(p) if(p){free(p);p = NULL;}
#define UTIL_ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

#ifndef UTIL_NUM_MIN
#define UTIL_NUM_MIN(a,b) ((a) < (b) ? (a) : (b))
#endif

#ifndef UTIL_NUM_MAX
#define UTIL_NUM_MAX(a,b) ((a) > (b) ? (a) : (b))
#endif

//知识点##__VA_ARGS__ 宏前面加上##的作用在于,当可变参数的个数为0时,这里的##起到把前面多余的","去掉的作用,否则会编译出错
#ifndef DISABLE_PRINTF
	#define HPRINT(...)		printf(##__VA_ARGS__);
	#define HINFO(...) 		util_log(LOG_LEVEL_INFO, __FUNCTION__, __LINE__, ##__VA_ARGS__);
	#define HKEY(...) 		util_log(LOG_LEVEL_KEY, __FUNCTION__, __LINE__, ##__VA_ARGS__);
	#define HWARN(...) 		util_log(LOG_LEVEL_WARN, __FUNCTION__, __LINE__, ##__VA_ARGS__);
	#define HERROR(...) 	util_log(LOG_LEVEL_ERROR, __FUNCTION__, __LINE__, ##__VA_ARGS__);
	#define HFATAL(...) 	util_log(LOG_LEVEL_FATAL, __FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
	#define HPRINT(...)
	#define HINFO(...)
	#define HKEY(...)
	#define HWARN(...)
	#define HERROR(...)
	#define HFATAL(...)
#endif

typedef enum
{
	LOG_LEVEL_NULL,
	LOG_LEVEL_INFO,
	LOG_LEVEL_KEY,
	LOG_LEVEL_WARN,
	LOG_LEVEL_ERROR,
	LOG_LEVEL_FATAL,
	LOG_LEVEL_TOTAL
}LOG_LEVEL_EM;

extern int util_get_file_size(const char *FileName);
extern void util_random_uuid(char *buf);
extern int util_block_until_writeable(int socket, struct timeval* timeout) ;
extern int util_block_until_readable(int socket, struct timeval* timeout) ;

/*
**描述:将src字符串按照separator进行分解,进dest,
**参数:	dest:char*dest[]
**返回值:返回字符串个数
** 注意,此函数会破环src原字符串,所以不希望被破环的话,最好提前拷贝一份
*/
extern int util_split( char *dest[], char *src, const char *separator);

extern void util_print_time(const char *fun, int line);
#define UTIL_PRINT_TIME() util_print_time(__FUNCTION__, __LINE__);


/*
**描述:	显示本系统上所有网络设备及其ip地址
**参数:	enable_ipv6----是否显示ipv6:0---不显示,非0---显示
**返回值:0-执行成功,>0-执行出错
*/
int util_show_all_eth_ip(int enable_ipv6,char ips[][16],int maxIpsNum,char hosts[][16]);
	
/*
**描述:	转换时间格式
**参数:	l_time----出参,形如:20200101010101123
		str_time----入参  ,形如:2020-01-01 01:01:01.123
**返回值:
*/
void util_convert_time_str_long(char *str_time, char *l_time);
void  util_convert_time_str_long2(char *str_time, char *l_time);
/*
**描述:	转换时间格式
**参数:	l_time----入参,形如:20200101010101123
		str_time----出参  ,形如:2020-01-01 01:01:01.123
**返回值:
*/
void  util_convert_time_long_str(char *l_time, char *str_time);
/*
**描述:	获取现在的毫秒数
**参数:	now_msec----出参
**返回值:
*/
void util_get_now_msec(long *now_msec);
/*
**描述:	获取现在时间的年月日时分秒字符串20200101121212
**参数:	now----出参
**返回值:
*/
void util_get_now_time_str_YYmmddHHMMSS(char *now);
/*
**描述:	通过现在时间的年月日时分秒字符串,2020-01-01 12:12:12
**参数:	now----出参
**返回值:
*/
void util_get_now_time_str_YYmmddHHMMSS_en(char *now);
/*
**描述:	通过现在时间的年月日时分秒字符串,2020年01月01日 12时12分12秒
**参数:	now----出参
**返回值:
*/
void util_get_now_time_str_YYmmddHHMMSS_cn(char *now);
/*
**描述:	通过网络设备名称获取mac
**参数:	ethName----设备名称
**			pMAC----获取到的mac
**返回值:0-执行成功,>0-执行出错
*/
extern int util_get_local_MAC(const char* ethName, char* pMAC);

/*
**描述:	通过网络设备名称获取ip
**参数:	ethName----设备名称
**		ip----获取到的ip
**返回值:0-执行成功,>0-执行出错
*/
int util_get_local_ip(const char* ethName, char* ip);

/*
**描述:	通过ip和port判断连接状态
**参数:	strIpAddr----入参
**		nPort----入参
**		ConnState----出参,0-未连接,1-连接
**		若无指定端口,将nPort赋值为0
**返回值:0-执行成功,>0-执行出错
*/
extern int util_check_connection(const char *strIpAddr, int nPort, int *ConnState);

/*
**描述:	执行shell命令,并返回命令回显
**参数:	cmd----入参,要执行的命令
**		ret----出参,用于保存回显字符串
**		retLen----入参,ret的大小
**返回值:0-执行成功,>0-执行出错
*/
extern int util_get_shell_cmd_return(const char *cmd, char * ret, unsigned int retLen);

extern int util_log(LOG_LEVEL_EM lv, const char *pFun, long lLine, char* fmt, ...);

/*
lv:	<= lv的日志等级会进行打印
logFilePath:日志的保存目录
			设置为NULL时表示日志不输出至文件
*/
extern int util_log_init(LOG_LEVEL_EM lv, const char *logFilePath);

extern LOG_LEVEL_EM util_get_log_level();

#if 0
enum
{ 
    DT_UNKNOWN = 0, 
 # define DT_UNKNOWN DT_UNKNOWN 
     DT_FIFO = 1, 
 # define DT_FIFO DT_FIFO 
     DT_CHR = 2, 
 # define DT_CHR DT_CHR 
     DT_DIR = 4, 
 # define DT_DIR DT_DIR 
     DT_BLK = 6, 
 # define DT_BLK DT_BLK 
     DT_REG = 8, 
 # define DT_REG DT_REG 
     DT_LNK = 10, 
 # define DT_LNK DT_LNK 
     DT_SOCK = 12, 
 # define DT_SOCK DT_SOCK 
     DT_WHT = 14 
 # define DT_WHT DT_WHT 
}; 

struct dirent
{
   long d_ino; /* inode number 索引节点号 */
   off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
   unsigned short d_reclen; /* length of this d_name 文件名长 */
   unsigned char d_type; /* the type of d_name 文件类型 */
   char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长255字符 */
}
struct __dirstream
{
void *__fd; /* `struct hurd_fd' pointer for descriptor.   */
char *__data; /* Directory block.   */
int __entry_data; /* Entry number `__data' corresponds to.   */
char *__ptr; /* Current pointer into the block.   */
int __entry_ptr; /* Entry number `__ptr' corresponds to.   */
size_t __allocation; /* Space allocated for the block.   */
size_t __size; /* Total valid data in the block.   */
__libc_lock_define (, __lock) /* Mutex lock for this structure.   */
};

typedef struct __dirstream DIR;

#endif

#ifdef __cplusplus
}
#endif

#endif

坚持积累

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值