#include "basicFunctionality.h" #include "../../alg/generic/md5.h" #include //#include #ifdef DEBUG #include "basicLogCollection.h" #define URGENT_LOG(X) basicLogCollection::getInstance()->Log("basic Functionality", NULL, X ) #endif #ifdef __linux__ int chown( const char *file_path, const char *user_name, const char *group_name){ uid_t uid; gid_t gid; struct passwd *pwd; struct group *grp; pwd = getpwnam(user_name); if (pwd == NULL) { #ifdef DEBUG URGENT_LOG("Failed to get uid!"); #endif return -1; }; uid = pwd->pw_uid; grp = getgrnam(group_name); if (grp == NULL){ #ifdef DEBUG URGENT_LOG("Failed to get gid!"); #endif return -1; }; gid = grp->gr_gid; return chown(file_path, uid, gid); }; #endif int checkCmdExists( CSTR cmd ){ FILE * fd = popen( cmd, "r" ); char tB[1024]; int rVal = -1; if( fd!= NULL ){ while ( !feof(fd)) { fgets((CSTR)tB, 1024, fd ); trim( tB ); if( strstr(tB, "command not found" ) != NULL){ rVal = 0; break; }; }; if( rVal < 1 ) rVal = 1; fclose(fd); }; return rVal; } #ifdef __linux__ int fileCopy( const char* source, const char* destination ){ int input, output; if ((input = open(source, O_RDONLY)) == -1) return -1; if ((output = creat(destination, 0660)) == -1){ close(input); return -1; }; //Here we use kernel-space copying for performance reasons #if defined(__APPLE__) || defined(__FreeBSD__) //fcopyfile works on FreeBSD and OS X 10.5+ int result = fcopyfile(input, output, 0, COPYFILE_ALL); #else //sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+ off_t bytesCopied = 0; struct stat fileinfo = {0}; fstat(input, &fileinfo); int result = sendfile(output, input, &bytesCopied, fileinfo.st_size); #endif close(input); close(output); return result; }; #endif bool fileExist(const char *strFilename) { struct stat stFileInfo; int intStat; intStat = stat( strFilename ,&stFileInfo); if( intStat == 0 ){ return true; }; return false; }; bool dirEmpty( const char *dirname ){ int n = 0; struct dirent *d; DIR *dir = opendir(dirname); if( dir == NULL) return true; while( (d = readdir(dir)) != NULL )if( ++n > 2 ) break; closedir( dir ); if( n <= 2 ) return true; return false; }; #ifndef __linux__ #else #include #include #include #include pid_t gettid( void ){ return syscall(SYS_gettid); }; #endif const char *__BuildDate = (__DATE__); const char *__BuildTime = (__TIME__); const char *__BuildTS = (__TIMESTAMP__); CSTR getBuildID( void ){ return NULL; }; /* Global Time Diff Value to correct Timestamps */ static int g_iTimeDiff = 0; /** * number of seconds from 1 Jan. 1601 00:00 to 1 Jan 1970 00:00 UTC */ // Defined in Header File //#define EPOCH_DIFF 11644473600LL //#define UNIX_TimeStamp_2_WINDOWS_FileTime_SHIFT 116444736000000000 bool correctSysTime( int diff ){ #ifdef __linux__ struct timeval tData; struct timezone tTZ; tTZ.tz_minuteswest = 0; tTZ.tz_dsttime = 0; if( gettimeofday( &tData, &tTZ ) == -1 ){ return false; } else { tData.tv_sec += diff / 1000; tData.tv_usec += ( diff * 1000 ) % 1000000; }; if( settimeofday( &tData, &tTZ ) == -1 ){ return false; }; #else unsigned __int64 tMilliseconds; SYSTEMTIME Ztime; GetSystemTime(&Ztime); SystemTimeToFileTime( &Ztime, (FILETIME*) &tMilliseconds ); tMilliseconds += diff * 10000; FileTimeToSystemTime( (FILETIME*) &tMilliseconds, &Ztime ); if( 0 == SetSystemTime(&Ztime) ) return false; #endif return true; }; bool correctSoftTime( int diff ){ g_iTimeDiff = diff; return true; }; #ifdef __linux__ unsigned long long getTimeValue( void ){ unsigned long long tMilliseconds; struct timeval tData; struct timezone tTZ; tMilliseconds = 0; tTZ.tz_minuteswest = 0; tTZ.tz_dsttime = 0; if( gettimeofday( &tData, &tTZ ) == -1 ){ } else { tMilliseconds = tData.tv_sec; tMilliseconds = tMilliseconds *1000; tMilliseconds += tData.tv_usec / 1000; }; #else /* void TimetToFileTime( time_t t, LPFILETIME pft ){ LONGLONG ll = Int32x32To64(t, 10000000) + 116444736000000000; pft->dwLowDateTime = (DWORD) ll; pft->dwHighDateTime = ll >>32; }*/ unsigned __int64 getTimeValue( void ){ unsigned __int64 tMilliseconds; SYSTEMTIME Ztime; GetSystemTime(&Ztime); SystemTimeToFileTime( &Ztime, (FILETIME*) &tMilliseconds ); tMilliseconds -= UNIX_TimeStamp_2_WINDOWS_FileTime_SHIFT; tMilliseconds = tMilliseconds / 10000; #endif tMilliseconds += g_iTimeDiff; return tMilliseconds; }; static uint32_t UID_INCREMENTAL_VALUE = 0; #define UID_INCREMEMTAL (UID_INCREMENTAL_VALUE++) CSTR getTimeStamp( void ){ CSTR RetVal = NULL; time_t rawtime; uint32_t msec; struct tm * ptm = NULL; time ( &rawtime ); ptm = gmtime ( &rawtime ); msec = getTimeValue() % 1000; //2019-03-24T12:32:59.670Z if( ptm != NULL ) { RetVal = (CSTR) malloc( 128 ); if( RetVal!=NULL ){ sprintf( RetVal, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", (ptm->tm_year+1900), (ptm->tm_mon+1), ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec, msec ); }; }; return RetVal; }; CSTR getTimeStampI( void ){ CSTR RetVal = NULL; time_t rawtime; uint32_t msec; struct tm * ptm = NULL; time ( &rawtime ); ptm = gmtime ( &rawtime ); msec = getTimeValue() % 1000; //2019-03-24T12:32:59.670Z if( ptm != NULL ) { RetVal = (CSTR) malloc( 128 ); if( RetVal!=NULL ){ sprintf( RetVal, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ %d", (ptm->tm_year+1900), (ptm->tm_mon+1), ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec, msec, UID_INCREMEMTAL ); }; }; return RetVal; }; CSTR getUniqID_MD5( void ){ CSTR tVal = NULL; CSTR tMD5 = NULL; char buf[33]; tVal = getTimeStampI(); buf[0] = (char)0; if( tVal ){ tMD5 = MD5String( tVal ); if( tMD5 ) { sprintf( buf, "%s", tMD5 ); free( tMD5 ); }; free( tVal ); }; #ifdef __linux__ return strdup( buf ); #else return _strdup( buf ); #endif }; CSTR getUniqID_SHA256(void){ return NULL;}; int rand( int a, int b ){ if( b > a ){ return a + (rand() *( b - a )) / RAND_MAX; }; return b + ( rand() * ( a - b )) / RAND_MAX; }; CSTR getUniqID_UUID( uint32_t SEED ){ /* char buf[46]; if( SEED ) { srand( SEED ); } else { srand( getMilliseconds() );// time(NULL) ); }; snprintf( buf, 42, "%8.8x-%4.4x-%4.4x-%4.4x-%6.6x%6.6x", rand() & 0xFFFFFFFF, rand() & 0xFFFF, (rand() & 0x0FFF) | 0x4000, // M 4 MSB version => version 4 (rand() & 0x1FFF) | 0x8000, // N: 3 MSB variant => variant 1 rand() & 0xFFFFFF, rand() & 0xFFFFFF ); #ifdef __linux__ return strdup( buf ); #else return _strdup( buf ); #endif */ CSTR tVal = NULL; CSTR tMD5 = NULL; char buf[37]; tVal = getTimeStamp(); buf[0] = (char)0; if( tVal ){ char tt[256]; sprintf( tt, "%s %d %d", tVal ,SEED, UID_INCREMEMTAL ); tMD5 = MD5String( tt ); if( tMD5 ) { memcpy( buf, tMD5, 8 ); buf[8] = '-'; memcpy( buf+9, tMD5+8, 4 ); buf[13] = '-'; memcpy( buf+14, tMD5+12, 4 ); buf[18] = '-'; memcpy( buf+19, tMD5+16, 4 ); buf[23] = '-'; memcpy( buf+24, tMD5+20, 12 ); buf[36] = (char)0; free( tMD5 ); }; free( tVal ); }; #ifdef __linux__ return strdup( buf ); #else return _strdup( buf ); #endif }; CSTR trim( CSTR val ){ int i = 0; int j = strlen( val ); if( j ){ while(( i < j ) && (((unsigned char)val[i])< 0x21 )) i++; while(( j > i ) && (((unsigned char)val[j])< 0x21 )) j--; if( ( i > 0 ) && ((j-i+1) > 0 ) ) memcpy( val, val+i, j-i+1 ); val[j-i+1]=(char)0; }; return val; }; // orig - input String to Search In // rep - token to search // with - replacement for token // in case with is NULL - cutting off the token // You must free the result if result is non-NULL. CSTR strReplace( CSTR orig, CSTR rep, CSTR with ){ char *result; // the return string char *ins; // the next insert point char *tmp; // varies int len_rep; // length of rep (the string to remove) int len_with; // length of with (the string to replace rep with) int len_front; // distance between rep and end of last rep int count; // number of replacements // sanity checks and initialization if (!orig || !rep) return NULL; len_rep = strlen(rep); if (len_rep == 0) return NULL; // empty rep causes infinite loop during count if (!with) with =(CSTR)""; // In case With not suplied - just cut off Token len_with = strlen(with); // count the number of replacements needed ins = orig; for (count = 0; tmp = strstr(ins, rep); ++count) { ins = tmp + len_rep; } tmp = result = (CSTR) malloc(strlen(orig) + (len_with - len_rep) * count + 1); if( !result ) return NULL; // first time through the loop, all the variable are set correctly // from here on, // tmp points to the end of the result string // ins points to the next occurrence of rep in orig // orig points to the remainder of orig after "end of rep" while (count--) { ins = strstr(orig, rep); len_front = ins - orig; tmp = strncpy(tmp, orig, len_front) + len_front; tmp = strcpy(tmp, with) + len_with; orig += len_front + len_rep; // move to next "end of rep" } strcpy(tmp, orig); return result; }; uint8_t checksum8( uint8_t *Buffer, size_t BufferSize ){ uint16_t TempVal; TempVal = 0; for( int index = 0; index < BufferSize; index++ ) { TempVal+=Buffer[index]; }; return (uint8_t)(TempVal & 0x00FF); }; uint16_t checksum16( uint8_t *Buffer, size_t BufferSize ){ uint32_t TempVal; TempVal = 0; for( int index = 0; index < BufferSize; index++ ) { TempVal+=Buffer[index]; }; return (uint16_t)(TempVal & 0x0000FFFF); }; uint8_t checksumLGS( uint8_t *Buffer, size_t BufferSize ){ uint16_t TempVal; TempVal = 0; for( int index = 0; index < BufferSize; index++ ) { TempVal+=Buffer[index]; }; return (uint8_t)(TempVal & 0x00FF); }; // Calculating the Check Sum for Ping package uint16_t checksumPing(void *b, size_t len){ uint16_t *buf = (uint16_t *) b; uint32_t sum=0; uint16_t result; for ( sum = 0; len > 1; len -= 2 ) sum += *buf++; if ( len == 1 ) sum += *(unsigned char*)buf; sum = (sum >> 16) + (sum & 0xFFFF); sum += (sum >> 16); result = ~sum; return result; }; CArray *explode( char Delim, CSTR S_Str ){ bool ws = false; CArray * RetVal = NULL; CSTR b_ptr = S_Str; U16 s_ptr = 0; if( S_Str ){ RetVal = new CArray; if( RetVal ){ while ((U8)S_Str[s_ptr]) { if( (( U8 ) Delim ) == (( U8 )S_Str[s_ptr]) ){ if (!ws) { ws = true; S_Str[s_ptr] = (char)0; RetVal->push_back( b_ptr ); s_ptr++; b_ptr = &S_Str[s_ptr]; } else s_ptr++; } else { ws = false; s_ptr++; }; }; RetVal->push_back( b_ptr ); }; }; return RetVal; }; CSTR implode( CArray *Data, CSTR S_Str, U8 Start, U8 End ){ CSTR RetVal; U8 RStart = Start; U8 REnd = End; if( Start > Data->size() ) return NULL; if( End < Start ) return NULL; if( End > Data->size() ) REnd = (U8)(Data->size()-1); if( strlen( (*Data).at( RStart )) ){ RetVal = (CSTR) malloc( strlen( (*Data).at( RStart )) + 1 ); sprintf( RetVal,"%s",(*Data).at( RStart )); } else { RetVal = (CSTR) malloc( 1 ); *RetVal=(char)0; }; if (RetVal != NULL) { for (int i = RStart + 1; i < REnd; i++) { RetVal = (CSTR)realloc(RetVal, strlen(RetVal) + strlen((*Data).at(i)) + 1 + strlen(S_Str)); sprintf(RetVal, "%s%s%s", RetVal, S_Str, (*Data).at(i)); }; }; return RetVal; }; int getIP4( if_info **arrParam, int max_ifs ){ int index = 0; #ifdef __linux__ struct ifaddrs *addrs, *tmp; getifaddrs(&addrs); tmp = addrs; //arrParam= malloc( 10 * sezeof(if_info) ); while (tmp){ if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET){ if( strncmp( tmp->ifa_name, "lo", 2 ) != 0 ){ (*arrParam)[index].if_name = (CSTR)malloc(strlen(tmp->ifa_name)+1); snprintf( (*arrParam)[index].if_name, strlen(tmp->ifa_name)+1,"%s", tmp->ifa_name ); (*arrParam)[index].if_addr = (CSTR)malloc(16); struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr; snprintf( (*arrParam)[index].if_addr, 16, "%s", inet_ntoa(pAddr->sin_addr) ); index++; if( index == max_ifs ) break; } }; tmp = tmp->ifa_next; }; freeifaddrs(addrs); #endif return index; }; #ifdef __linux__ long long getFreeSpace( CSTR DirName ){ struct statvfs fiData; if( ( statvfs( DirName, &fiData ) ) < 0 ) { return -1; }; return fiData.f_bsize * fiData.f_bfree; }; long long getTotalSpace( CSTR DirName ){ struct statvfs fiData; if( ( statvfs( DirName, &fiData ) ) < 0 ) { return -1; }; return fiData.f_bsize * fiData.f_blocks; }; #else __int64 getFreeSpace( CSTR DirName ){ return -1; }; __int64 getTotalSpace( CSTR DirName ){ return -1; }; #endif CSTR getTStr( CSTR Fmt ){ //CSTR RetVal = NULL; char DateStr[200]; time_t t; struct tm *tmp; t = time(NULL); tmp = gmtime(&t); if( tmp == NULL) { fprintf(stderr, "localtime!"); return NULL; }; if( Fmt == NULL ) { if( strftime( DateStr, 200, "%F %T GMT", tmp )==0 ){ fprintf( stderr, "strftime returned 0" ); return NULL; }; } else { if( strftime( DateStr, 200, Fmt, tmp )==0 ){ fprintf( stderr, "strftime returned 0" ); return NULL; }; } //RetVal =(CSTR) malloc( strlen(DateStr) +1 ); //if( RetVal != NULL ) strcpy( RetVal, DateStr ); #ifdef __linux__ return strdup(DateStr); #else return _strdup(DateStr); #endif }; #ifdef __linux__ int xioctl(int fh, int request, void *arg){ int r; do { r = ioctl( fh, request, arg ); } while (-1 == r && EINTR == errno); return r; }; uint64_t getMilliseconds( void ){ uint64_t tMilliseconds = (uint64_t) 0; struct timeval tData; struct timezone tTZ; tTZ.tz_minuteswest = 0; tTZ.tz_dsttime = 0; if( gettimeofday( &tData, &tTZ ) == -1 ){ tMilliseconds = (uint64_t) 0; #ifdef DEBUG URGENT_LOG( "EbioMat'!"); #endif } else { tMilliseconds = (uint64_t) tData.tv_sec; tMilliseconds = ( tMilliseconds * 1000 ); tMilliseconds += (uint64_t)( tData.tv_usec / 1000 ); //URGENT_LOG("MilSecCollected!"); }; #else #include unsigned __int64 getMilliseconds( void ){ unsigned __int64 tMilliseconds; SYSTEMTIME time; GetSystemTime(&time); tMilliseconds = (uint32_t)std::time(NULL); tMilliseconds *= 1000; tMilliseconds += time.wMilliseconds; #endif return tMilliseconds; }; #ifdef __linux__ bool enumerateDevices( enumeratorInfo *mlist, const char *dTemplate){ DIR *d; struct dirent *dir; DeviceInfo *tDevInfo; if( mlist == NULL )return false; if( dTemplate == NULL )return false; for( int i = 0; i < mlist->size(); i++ ) { delete( mlist->at(i) ); }; mlist->clear(); d = opendir("/dev"); if( d ){ while((dir = readdir(d)) != NULL){ if( dir->d_type == DT_CHR || dir->d_type == DT_BLK ){ if( strncmp( dir->d_name, dTemplate, 5 ) == 0 ) { tDevInfo = (DeviceInfo *) malloc( sizeof(DeviceInfo) ); sprintf( tDevInfo->DevicePath, "/dev/%s", dir->d_name ); tDevInfo->FriendlyName[0] =(char)0; if( strncmp( dTemplate, "video", 5 ) == 0 ){ FILE *fd; char CMD[256]; sprintf( CMD, "v4l2-ctl -d %s -D", tDevInfo->DevicePath ); fd = popen( CMD, "r"); if( fd != NULL ) { char * line = NULL; size_t len = 0; ssize_t rd; while ((rd = getline(&line, &len, fd)) != -1) { char *tS1, *tS2; // Future use strcasestr() or make both stings same case if( ( tS1 = strstr( line, "Bus info" )) != NULL ) { tS2 = trim( strstr( tS1, ":" ) + 2 ); sprintf( tDevInfo->FriendlyName, "%s", tS2 ); }; }; fclose( fd ); if( line ) free( line ); }; }; mlist->push_back( tDevInfo ); //printf("%s\n", dir->d_name ); }; //if( strncmp( dir->d_name, "ttyS", 4 ) == 0 ){ // tBuffer = ( char * ) malloc( strlen(dir->d_name)+1 ); // strncpy( tBuffer, dir->d_name, strlen(dir->d_name)+1 ); // mlist->pushBack( tBuffer ); // //printf("%s\n", dir->d_name ); //}; }; }; closedir(d); } else { return false; }; return true; }; #else #ifndef IID_PPV_ARGS extern "C++" { template void** IID_PPV_ARGS_Helper(T** pp) { // make sure everyone derives from IUnknown static_cast(*pp); return reinterpret_cast(pp); } } #define IID_PPV_ARGS(ppType) __uuidof(**(ppType)), IID_PPV_ARGS_Helper(ppType) #endif #pragma comment(lib,"Strmiids.lib") bool enumerateDevices(enumeratorInfo *mlist, REFGUID category){ HRESULT hr; bool initOk = true; hr = CoInitializeEx( NULL, COINIT_SPEED_OVER_MEMORY | COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE ); if( hr == E_INVALIDARG ){ printf("Couldn't Init! hr=0x%x", hr); return false; } else if ( hr == E_OUTOFMEMORY ){ printf("Couldn't Init! hr=0x%x", hr); return false; } else if ( hr == E_UNEXPECTED ){ printf("Couldn't Init! hr=0x%x", hr); return false; } else if( hr == RPC_E_CHANGED_MODE ){ initOk = false; }; if( hr == S_OK || hr == RPC_E_CHANGED_MODE ){ // Create the system device enumerator ICreateDevEnum *pDevEnum; hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pDevEnum) ); if( hr != S_OK ){ printf("Couldn't create system enumerator! hr=0x%x", hr); CoUninitialize(); return false; }; if( pDevEnum != NULL ){ IEnumMoniker *pClsEnum = NULL; hr = pDevEnum->CreateClassEnumerator(category, &pClsEnum, 0); if( hr == S_FALSE ){ // The category is empty. Treat as an error. pDevEnum->Release(); CoUninitialize(); return false; }; if( pClsEnum != NULL ){ IMoniker *pMoniker = NULL; while( pClsEnum->Next(1, &pMoniker, NULL) == S_OK ){ IPropertyBag *pPropBag = NULL; hr = pMoniker->BindToStorage(0, 0, IID_PPV_ARGS(&pPropBag)); if( FAILED(hr) ){ pMoniker->Release(); continue; }; VARIANT var; VariantInit(&var); DeviceInfo *tRec; tRec = (DeviceInfo *)malloc(sizeof(DeviceInfo)); // Get description or friendly name. hr = pPropBag->Read(L"Description", &var, 0); if( FAILED(hr) ){ hr = pPropBag->Read(L"FriendlyName", &var, 0); }; if (SUCCEEDED(hr)){ if (tRec != NULL) { sprintf(tRec->FriendlyName, "%S", var.bstrVal); mlist->push_back(tRec); }; VariantClear(&var); }; hr = pPropBag->Write(L"FriendlyName", &var); // WaveInID applies only to audio capture devices. hr = pPropBag->Read(L"WaveInID", &var, 0); if (SUCCEEDED(hr)){ //printf("WaveIn ID: %d\n", var.lVal); VariantClear(&var); }; hr = pPropBag->Read(L"DevicePath", &var, 0); if (SUCCEEDED(hr)){ // The device path is not intended for display. if( tRec != NULL) { sprintf(tRec->DevicePath, "%S", var.bstrVal); }; VariantClear(&var); }; pPropBag->Release(); pMoniker->Release(); }; pClsEnum->Release(); }; pDevEnum->Release(); }; if( initOk ) CoUninitialize(); }; return true; }; #endif size_t escape_string( char *to, size_t to_length, const char *from, size_t length ){ const char *to_start = to; const char *end, *to_end = to_start + (to_length ? to_length - 1 : 2 * length); bool overflow = false; for( end = from + length; from < end; from++ ) { char escape = 0; int tmp_length; /* If the next character appears to begin a multi-byte character, we escape that first byte of that apparent multi-byte character. (The character just looks like a multi-byte character -- if it were actually a multi-byte character, it would have been passed through in the test above.) Without this check, we can create a problem by converting an invalid multi-byte character into a valid one. For example, 0xbf27 is not a valid GBK character, but 0xbf5c is. (0x27 = ', 0x5c = \) */ tmp_length = 0; if( tmp_length > 1 ){ escape = *from; } else{ switch (*from) { case 0: /* Must be escaped for 'mysql' */ escape = '0'; break; case '\n': /* Must be escaped for logs */ escape = 'n'; break; case '\r': escape = 'r'; break; case '\\': escape = '\\'; break; case '\'': escape = '\''; break; case '"': /* Better safe than sorry */ escape = '"'; break; case '\032': /* This gives problems on Win32 */ escape = 'Z'; break; }; }; if( escape ) { if (to + 2 > to_end) { overflow = true; break; }; *to++ = '\\'; *to++ = escape; } else { if (to + 1 > to_end) { overflow = true; break; }; *to++ = *from; }; }; *to = 0; return overflow ? (size_t)-1 : (size_t)(to - to_start); }; localIpAddresses g_vLocalIpAdressess; bool g_bAdressesAreDiscovered = false; #ifdef __linux__ #include localIpAddresses *getLocalIP(){ // Check for Filter LO and TUN Devices! if( !g_bAdressesAreDiscovered ) { struct ifaddrs *ifaddr, *ifa; localIp4Info *tIpAddress = NULL; if (getifaddrs(&ifaddr) != -1) { /* Walk through linked list, maintaining head pointer so we can free list later */ for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { // Filter Loopback if if( strstr( ifa->ifa_name, "lo" ) != NULL ) continue; // Filter vpn TUN if if( strstr( ifa->ifa_name, "tun" ) != NULL ) continue; char protocol[IFNAMSIZ] = {0}; if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET) continue; tIpAddress = (localIp4Info*)malloc(sizeof(localIp4Info)); if(tIpAddress!=NULL){ sprintf( tIpAddress->address , "%d.%d.%d.%d", (uint8_t)ifa->ifa_addr->sa_data[2], (uint8_t)ifa->ifa_addr->sa_data[3], (uint8_t)ifa->ifa_addr->sa_data[4], (uint8_t)ifa->ifa_addr->sa_data[5] ); sprintf( tIpAddress->netmask , "%d.%d.%d.%d", (uint8_t)ifa->ifa_netmask->sa_data[2], (uint8_t)ifa->ifa_netmask->sa_data[3], (uint8_t)ifa->ifa_netmask->sa_data[4], (uint8_t)ifa->ifa_netmask->sa_data[5] ); sprintf( tIpAddress->broadcast , "%d.%d.%d.%d", (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[2], (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[3], (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[4], (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[5] ); g_vLocalIpAdressess.push_back(tIpAddress); }; }; freeifaddrs(ifaddr); }; g_bAdressesAreDiscovered = true; }; return &g_vLocalIpAdressess; }; #else // linux //https://stackoverflow.com/questions/5213629/how-to-enumerate-all-available-network-interfaces #include #pragma comment(lib, "IPHLPAPI.lib") localIpAddresses* getLocalIP() { char psBuffer[128]; FILE* fd; BYTE mB; localIp4Info* tIpAddress; if (!g_bAdressesAreDiscovered) { ULONG outBufLen = 0; DWORD dwRetVal = 0; IP_ADAPTER_INFO* pAdapterInfos = (IP_ADAPTER_INFO*)malloc(sizeof(IP_ADAPTER_INFO)); // retry up to 5 times, to get the adapter infos needed for (int i = 0; i < 5 && (dwRetVal == ERROR_BUFFER_OVERFLOW || dwRetVal == NO_ERROR); ++i) { dwRetVal = GetAdaptersInfo(pAdapterInfos, &outBufLen); if (dwRetVal == NO_ERROR) { break; } else { if (dwRetVal == ERROR_BUFFER_OVERFLOW) { free(pAdapterInfos); pAdapterInfos = (IP_ADAPTER_INFO*)malloc(outBufLen); } else { //pAdapterInfos = 0; break; }; }; }; if (dwRetVal == NO_ERROR) { IP_ADAPTER_INFO* pAdapterInfo = pAdapterInfos; while (pAdapterInfo) { IP_ADDR_STRING* pIpAddress = &(pAdapterInfo->IpAddressList); while (pIpAddress != 0) { uint8_t A, B, C, D; uint8_t M, O, S, K, G, U, T, E; uint32_t Z1, Z2, Z3, Z4; int RetVal; RetVal = sscanf(pIpAddress->IpAddress.String, "%d.%d.%d.%d", &Z1, &Z2, &Z3, &Z4); A = Z1 & 0xFF; B = Z2 & 0xFF; C = Z3 & 0xFF; D = Z4 & 0xFF; RetVal = sscanf(pIpAddress->IpMask.String, "%d.%d.%d.%d", &Z1, &Z2, &Z3, &Z4); M = Z1 & 0xFF; O = Z2 & 0xFF; S = Z3 & 0xFF; K = Z4 & 0xFF; // // <<<< // here pAdapterInfo->Address should contain the MAC address // >>>> // if (A > 0) { tIpAddress = (localIp4Info*)malloc(sizeof(localIp4Info)); if (tIpAddress != NULL) { sprintf(tIpAddress->address, "%d.%d.%d.%d", A, B, C, D ); sprintf(tIpAddress->netmask, "%d.%d.%d.%d", M, O, S, K ); G = (A & M) | (~M); U = (B & O) | (~O); T = (C & S) | (~S); E = (D & K) | (~K); sprintf(tIpAddress->broadcast, "%d.%d.%d.%d", G, U, T, E ); g_vLocalIpAdressess.push_back(tIpAddress); }; }; pIpAddress = pIpAddress->Next; }; pAdapterInfo = pAdapterInfo->Next; }; }; free(pAdapterInfos); }; return &g_vLocalIpAdressess; }; #endif #ifdef DEBUG #undef URGENT_LOG #endif