반응형

build.bat

@echo off
setlocal
echo DiskFilter Driver Build Script
echo =============================

call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat" 2>nul
if %ERRORLEVEL% NEQ 0 (
    call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" 2>nul
    if %ERRORLEVEL% NEQ 0 (
        call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat" 2>nul
        if %ERRORLEVEL% NEQ 0 (
            echo Error: Visual Studio not found. Please install Visual Studio or run from Developer Command Prompt.
            exit /b 1
        )
    )
)

set WDKPATH=C:\Program Files (x86)\Windows Kits\10

REM Check if we're in WDK environment
if not defined WDKPATH (
    echo Error: WDK environment not detected.
    echo Please run this script from WDK Developer Command Prompt.
    echo.
    echo To open WDK Developer Command Prompt:
    echo 1. Start Menu -> Windows Driver Kit -> WDK x64 x86 Cross-Tools Command Prompt
    echo 2. Navigate to this directory
    echo 3. Run this script again
    pause
    exit /b 1
)

echo WDK environment detected: %WDKPATH%
echo.

REM Clean previous build
echo Cleaning previous build...
del *.obj *.sys *.pdb *.ilk 2>nul

REM Compile
echo Compiling diskfilter.c...
cl /c /I"%WDKPATH%\Include\10.0.26100.0\km" /I"%WDKPATH%\Include\10.0.26100.0\shared" ^
 /I"C:\Program Files (x86)\Windows Kits\10\Include\10.0.26100.0\km\crt" ^
 /I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include" ^
 /DDRIVER /DWIN32 /D_WIN32 /DNT /DNTDDI_VERSION=NTDDI_WIN10 /DWINVER=0x0A00 ^
 /D_WIN32_WINNT=0x0A00 /DUNICODE /D_UNICODE /DNDEBUG /Zi /Od /W3 /WX- /GS /Gy ^
 /Zc:wchar_t /Zc:forScope /Zc:inline /fp:precise /errorReport:prompt /kernel /D_AMD64_ /GS- diskfilter.c

if %errorLevel% neq 0 (
    echo Compilation failed!
    pause
    exit /b 1
)

REM Link
echo Linking diskfilter.sys...
link /DRIVER /SUBSYSTEM:NATIVE /ENTRY:DriverEntry ^
/NODEFAULTLIB /INCREMENTAL:NO /NOLOGO /DEBUG /PDB:diskfilter.pdb ^
/SUBSYSTEM:NATIVE /DRIVER:WDM /MACHINE:X64 /IGNORE:4099 /IGNORE:4210 /IGNORE:4049 /IGNORE:4103 /IGNORE:4098 ^
/LIBPATH:"%WDKPATH%\Lib\10.0.26100.0\km\x64" ^
/OUT:diskfilter.sys diskfilter.obj ntoskrnl.lib hal.lib bufferoverflowk.lib

if %errorLevel% neq 0 (
    echo Linking failed!
    pause
    exit /b 1
)

REM Check if build was successful
if exist diskfilter.sys (
    echo.
    echo Build completed successfully!
    echo Generated: diskfilter.sys
    echo.
    echo To install the driver, run: install.bat
    echo To test the driver, run: test.bat
) else (
    echo Build failed - diskfilter.sys not found!
)

echo.
echo Test completed.
endlocal
pause

 

 

 

반응형
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <windows.h>
#include <iphlpapi.h>
#include <psapi.h>
#include <tlhelp32.h>

#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")

struct TcpConnection {
    std::string localAddress;
    std::string localPort;
    std::string remoteAddress;
    std::string remotePort;
    std::string state;
    DWORD pid;
    std::string processName;
};

class NetStat {
private:
    std::vector<TcpConnection> connections;

    std::string getStateString(DWORD state) {
        switch (state) {
            case MIB_TCP_STATE_CLOSED: return "CLOSED";
            case MIB_TCP_STATE_LISTEN: return "LISTENING";
            case MIB_TCP_STATE_SYN_SENT: return "SYN_SENT";
            case MIB_TCP_STATE_SYN_RCVD: return "SYN_RCVD";
            case MIB_TCP_STATE_ESTAB: return "ESTABLISHED";
            case MIB_TCP_STATE_FIN_WAIT1: return "FIN_WAIT1";
            case MIB_TCP_STATE_FIN_WAIT2: return "FIN_WAIT2";
            case MIB_TCP_STATE_CLOSE_WAIT: return "CLOSE_WAIT";
            case MIB_TCP_STATE_CLOSING: return "CLOSING";
            case MIB_TCP_STATE_LAST_ACK: return "LAST_ACK";
            case MIB_TCP_STATE_TIME_WAIT: return "TIME_WAIT";
            case MIB_TCP_STATE_DELETE_TCB: return "DELETE_TCB";
            default: return "UNKNOWN";
        }
    }

    std::string getProcessName(DWORD pid) {
        if (pid == 0) return "System";
       
        HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
        if (hProcess == NULL) return "Unknown";
       
        char processName[MAX_PATH];
        DWORD size = MAX_PATH;
        if (QueryFullProcessImageNameA(hProcess, 0, processName, &size)) {
            CloseHandle(hProcess);
            std::string fullPath(processName);
            size_t lastSlash = fullPath.find_last_of("\\/");
            if (lastSlash != std::string::npos) {
                return fullPath.substr(lastSlash + 1);
            }
            return fullPath;
        }
       
        CloseHandle(hProcess);
        return "Unknown";
    }

    std::string formatAddress(DWORD address) {
        struct in_addr addr;
        addr.s_addr = address;
        return std::string(inet_ntoa(addr));
    }

    std::string formatPort(DWORD port) {
        return std::to_string(ntohs((u_short)port));
    }

public:
    bool getTcpConnections() {
        DWORD size = 0;
        DWORD result = GetExtendedTcpTable(NULL, &size, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
       
        if (result != ERROR_INSUFFICIENT_BUFFER) {
            std::cerr << "GetExtendedTcpTable failed with error: " << result << std::endl;
            return false;
        }

        std::vector<BYTE> buffer(size);
        PMIB_TCPTABLE_OWNER_PID tcpTable = (PMIB_TCPTABLE_OWNER_PID)buffer.data();
       
        result = GetExtendedTcpTable(tcpTable, &size, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
        if (result != NO_ERROR) {
            std::cerr << "GetExtendedTcpTable failed with error: " << result << std::endl;
            return false;
        }

        connections.clear();
        for (DWORD i = 0; i < tcpTable->dwNumEntries; i++) {
            MIB_TCPROW_OWNER_PID& row = tcpTable->table[i];
           
            TcpConnection conn;
            conn.localAddress = formatAddress(row.dwLocalAddr);
            conn.localPort = formatPort(row.dwLocalPort);
            conn.remoteAddress = formatAddress(row.dwRemoteAddr);
            conn.remotePort = formatPort(row.dwRemotePort);
            conn.state = getStateString(row.dwState);
            conn.pid = row.dwOwningPid;
            conn.processName = getProcessName(row.dwOwningPid);
           
            connections.push_back(conn);
        }
       
        return true;
    }

    void printConnections() {
        std::cout << std::left
                  << std::setw(20) << "Local Address"
                  << std::setw(10) << "Local Port"
                  << std::setw(20) << "Remote Address"
                  << std::setw(10) << "Remote Port"
                  << std::setw(15) << "State"
                  << std::setw(8) << "PID"
                  << "Process Name" << std::endl;
       
        std::cout << std::string(100, '-') << std::endl;
       
        for (const auto& conn : connections) {
            std::cout << std::left
                      << std::setw(20) << conn.localAddress
                      << std::setw(10) << conn.localPort
                      << std::setw(20) << conn.remoteAddress
                      << std::setw(10) << conn.remotePort
                      << std::setw(15) << conn.state
                      << std::setw(8) << conn.pid
                      << conn.processName << std::endl;
        }
       
        std::cout << "\nTotal TCP connections: " << connections.size() << std::endl;
    }
};

int main() {
    std::cout << "TCP Connections (IPv4)" << std::endl;
    std::cout << "======================" << std::endl << std::endl;
   
    NetStat netstat;
   
    if (!netstat.getTcpConnections()) {
        std::cerr << "Failed to get TCP connections" << std::endl;
        return 1;
    }
   
    netstat.printConnections();
   
    return 0;
}

'Develop > C&CPP' 카테고리의 다른 글

[cpp] optional  (0) 2025.04.25
[cpp] thread  (0) 2025.04.20
[cpp] atomic  (0) 2025.04.20
[cpp] mutex, lock  (0) 2025.04.20
[cpp] cpp17에서 달라진 점  (0) 2025.04.20
반응형

윈도우에서 UTF-8 with BOM 파일을 찾아 모두   UTF-8 without BOM 형식으로 변환하기.

아래에서 첫 번째에 최상위 경로를 주고 powershell에서 실행하면 일괄로 변경한다. 

 

$targetFolder = "data"  # 변환할 최상위 폴더 경로

# UTF-8 BOM 3바이트 시퀀스
$utf8BOM = [byte[]](0xEF,0xBB,0xBF)

# 대상 폴더 내 모든 파일 재귀 탐색
Get-ChildItem -Path $targetFolder -File -Recurse | ForEach-Object {
    $file = $_.FullName

    # 파일을 바이트 단위로 읽기
    $bytes = [System.IO.File]::ReadAllBytes($file)

    # BOM 존재 여부 체크
    if ($bytes.Length -ge 3 -and $bytes[0] -eq $utf8BOM[0] -and $bytes[1] -eq $utf8BOM[1] -and $bytes[2] -eq $utf8BOM[2]) {
        Write-Host "BOM 발견 및 제거 중: $file"

        # BOM 제거한 바이트 배열 생성
        $bytesWithoutBOM = $bytes[3..($bytes.Length - 1)]

        # BOM 제거된 바이트를 임시 파일에 기록
        $tempFile = [System.IO.Path]::GetTempFileName()
        [System.IO.File]::WriteAllBytes($tempFile, $bytesWithoutBOM)

        # 임시 파일을 원본 파일로 덮어쓰기
        Move-Item -Path $tempFile -Destination $file -Force
    }
    else {
        Write-Host "BOM 없음: $file"
    }
}

 

이 시스템에서 스크립트를 실행할 수 없으므로 ~~~파일을 로드할 수 없습니다. 라고 에러가 나면.

관리자 모드 powershell에서

Set-ExecutionPolicy RemoteSigned

 

 

+ Recent posts