HOME
  Security
   Software
    Hardware
  
FPGA
  CPU
   Android
    Raspberry Pi
  
nLite
  Xcode
   etc.
    ALL
  
LINK
BACK
 

2014/11/21

Windows Server 2012、Windows 10対応のネットワーク パケット キャプチャ アプリを紹介 Windows Server 2012、Windows 10対応のネットワーク パケット キャプチャ アプリを紹介

(無料で使える Windowsサーバー対応のネットワーク プロトコル アナライザーアプリを紹介)

Tags: [Windows開発]




● Windows Server 2012、Windows 10対応のネットワーク パケット キャプチャ アプリを紹介


● 2014年版 Windows Server対応のパケットキャプチャアプリの紹介

 ieHTTPHeaders 2.25 (Webプロトコルのみ、IE上で動く、★)
 Fiddler 2 (Webプロトコルのみ、単体アプリ、.NET 2.0が必要、★)
 Fiddler 4 (Webプロトコルのみ、単体アプリ、.NET 4.0が必要)
 Wireshark 1.12.2 Stable
 Microsoft Network Monitor 3.4 (軽いのでオススメ ★)
 Microsoft Message Analyzer 1.1 (動作が重い)

 Charles(HTTPS SSL通信の Proxyとして生パケットがキャプチャできます、★)
 Win10Pcap + Wireshark


● ieHTTPHeaders 2.25 (オススメ ★)

 IEの拡張機能として動く Webプロトコル専用パケットキャプチャアプリ。
 あると便利で動作も軽いのでオススメ。
 Windows XPや Windows 7 SP1 x64ビット環境で動作確認済み。

ieHTTPHeadersSetup.exe
87EAE6EFC5F9484F12B612D7D2A8CC7D
661839DF5FAC21FA7FF297BD3CC67DCED3B44833



● Telerik Fiddler 2/4 (オススメ ★)

 Webプロトコル専用パケットキャプチャアプリ。
 動作が軽く、表示もわかりやすいのでオススメ。

 Fiddler2は .NET v2が必要
 Fiddler4は .NET v4が必要

Fiddler Download

fiddler4setup.exe
Version 4.4.9.6, EXE, 1mb
Released on Oct 27, 2014

fiddler2setup.exe
Version 2.4.9.6, EXE, 1mb
Released on Oct 27, 2014

Supported OS: Windows XP to Windows 8.1
Framework: Fiddler2 requires .NET v2, Fiddler4 requires .NET v4

● Telerik Fiddler 5

 The free web debugging proxy for any browser, system or platform

Telerik Fiddler

2018/06/27
Fiddler5 5.0.20182.28034
FiddlerSetup.exe
C1442922C1AD9C0F04C2922B8E42CAE5
AEEA6C25ACB51DB45C4D8B9E78C836DA4544257A

● Fiddler add-ons

 Fiddler用の各種アドオン、機能拡張プラグイン

● Telerik FiddlerCap

 Capturing web traffic logs



● Wireshark 1.12.2 Stable

 パケットキャプチャアプリで定番の Wireshark。
 現在は Wireshark 1.12.2が安定版(Stable)。
 ポータブル版も有る。

Wireshark ネットワーク・アナライザ・ソフトウェア



● Microsoft Network Monitor 3.4 (オススメ ★)

 Network Monitor 2.0/ 2.1は Windows 2000 Serverや Windows Server 2003に機能制限版が付属だったが、Network Monitor 3.0(英語版のみ)以降は単体での無償ダウンロードになった。

 Ver 3.4は Microsoft Network Monitorの最新版でかつ最終版。
 (それ以降は Microsoft Message Analyzerとなる)

 Windows Server系にも対応。
 .NET Frameworkが不要で動作が軽いのでオススメ。

 Windows 10 October 2018 Updateでも動作可能(管理者権限で実行が必要)

Microsoft Network Monitor 3.4 (archive)

Version: 3.4 2350
File Name:
 NM34_x86.exe 6.1MB
 NM34_ia64.exe 8.3MB
 NM34_x64.exe 6.5MB
Date Published: 6/24/2010
KB Articles: KB933741

・Supported Operating System
 Windows 7, Windows 8, Windows Server 2003 Service Pack 2, Windows Server 2003 Service Pack 2 x64 Edition, Windows Server 2008, Windows Server 2008 R2, Windows Server 2008 R2 for Itanium-based Systems, Windows Server 2012, Windows Vista 64-bit Editions Service Pack 1, Windows Vista Service Pack 1, Windows XP 64-bit, Windows XP Service Pack 3


● Network Monitor 3.4でキャプチャした結果を Wiresharkで閲覧する方法

 Network Monitor 3.4でキャプチャした結果(.etlファイル)を Wiresharkで閲覧する事もできる。

So you want to use Wireshark to read the netsh trace output .etl ?


● Microsoft Network Monitorでネットワークアダプタが選択できない場合の対処方法

 ネットワークアダプタに規定のサービスがインストールされていない可能性が有る。
C:\Program Files\Microsoft Network Monitor 3> sc query nm3
[SC] EnumQueryServicesStatus:OpenService FAILED 1060:

指定されたサービスはインストールされたサービスとして存在しません。

 Microsoft Network Monitorをインストールしたディレクトリで下記のコマンドを実行してインストールする。
 (To rebind the Network Monitor driver, enter the following in an elevated command window:)
C:> nmconfig.exe /install


●「システムにインストールされているフィルターが限界に達しました」の対処方法

 Windows Vista/ 7 では、ネットワークアダプタにインストールできるフィルタに上限が掛かっている。
 この制限は下記の
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network
 のレジストリの MaxNumFiltersで変更できる。
 デフォルトの 8から 9に修正するとインストールできる様になる。

 ※この問題は例えば VirtualBoxの「VirtualBox Bridged Networking Driver」等のインストール時にも発生する。


MaxNumFilters.reg
この例では制限値を 10にしている。
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network]
"MaxNumFilters"=dword:0000000A



● Network-related programs no longer work after you upgrade to Windows 7

 他にはここも参考に

ネットワーク関連のプログラムを Windows 7 にアップグレードした後で動作しなく

 This issue occurs if the third-party programs use any of the following Network Driver Interface Specification (NDIS) drivers:
 NDIS intermediate (IM) filter driver
 NDIS IM multiplexer (MUX) driver
 NDIS protocol driver
 NDIS Filter driver

 To resolve this issue, reinstall the third-party program that has this problem.



● Network Monitorの後継ソフト Microsoft Message Analyzer

 Windows Server系にも対応。
 .NET Framework 4.0が必要で動作がとても重いので Network Monitorの方がオススメ。

Microsoft Message Analyzer

Version: 1.4 10/28/2016
Microsoft Message Analyzer v1.4 Known Issues.docx 144 KB
MessageAnalyzer.msi 66.6 MB
MessageAnalyzer64.msi 67.1 MB
Windows 10対応

Version: 1.1
File Name:
 Message Analyzer 1.1 Known Issues.docx 141KB
 Message Analyzer v1.1 Operating Guide.docx 1.1MB
 MessageAnalyzer.msi 48.4MB
 MessageAnalyzer64.msi 48.7MB
Date Published: 10/31/2014
KB Articles: KB933741

・Supported Operating System
 Windows 7, Windows 8, Windows 8.1, Windows Server 2008 R2, Windows Server 2012, Windows Server 2012 R2
 32-bit and 64-bit versions of Windows 7, Windows 8, Windows 8.1, Windows Server 2012 and Windows Server 2012 R2

・requirements
 .NET Framework 4.0、.NET Framework 4.5

MessageAnalyzer Blog


 下記は 1.0の古いバージョン

Microsoft Message Analyzer (1.0 archive)

Version: 1.0
File Name:
 Message Analyzer FAQ and Known Issues.docx 126KB
 MessageAnalyzer.msi 33.6MB
 MessageAnalyzer64.msi 33.9MB
Date Published: 9/24/2013

・Supported Operating System
 Windows 7, Windows 8, Windows 8.1, Windows Server 2008 R2, Windows Server 2012, Windows Server 2012 R2
 32-bit and 64-bit of Windows 7, Windows 8, Windows 8.1, Windows Server 2012 and Windows Server 2012 R2



● Charles

 HTTPS SSL通信の Proxyとして生パケットがキャプチャできます。
 (通信クライアント側で SSL証明書のハッシュ照合を行なっていない場合)

Charles

 Charles is an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet.
 This includes requests, responses and the HTTP headers (which contain the cookies and caching information).

 Javaアプリなので Windows、Mac、Linuxのそれぞれの環境で動作します。



● Win10Pcap : WinPcap for Windows 10 (NDIS 6.x ドライバモデル対応)

Win10Pcap
 Win10Pcap は WinPcap をベースに開発された新しい Ethernet パケットキャプチャライブラリです。

 Win10Pcap-v10.2-5002.msi 2015 年 10 月 8 日
 Win10Pcap 10.2.5002 (October 8, 2015)

● Wireshark

 上記の Win10Pcapと組み合わせて Windows 10環境でも使用可能。

Wireshark のダウンロードサイト
 Stable Release (2.6.6)
https://1.as.dl.wireshark.org/win64/Wireshark-win64-2.6.6.exe



●拡張子 .dlmファイルって何?download.dlm

 Microsoft File Transfer Manager用のダウンロード指示ファイルです。
 下記をインストールします。

Microsoft File Transfer Manager

Microsoft File Transfer Manager インストール/アップグレード
最新バージョン情報
バージョン : 5.0.0.32
リリース日 : 2007/12/26



● Network Monitor Command Line Capture

 Network Monitor 3.4をコマンドラインで動かして、その結果を Wiresharkで閲覧する事もできる。
C:\Program Files\Microsoft Network Monitor 3> NMCAP
Network Monitor Command Line Capture (nmcap) 3.4.2350.0
NMCAP Version = 3.4.2350.0
Try using nmcap /Usage or nmcap /Examples for help.

C:\Program Files\Microsoft Network Monitor 3> NMCAP /Usage
Network Monitor Command Line Capture (nmcap) 3.4.2350.0

Options:
 /Help /? /Usage
      Displays this message.
      Example Usage: nmcap /Usage

 /Example(s)
      Displays a list of examples.
      Example Usage: nmcap /Example
                     nmcap /examples

 /TimeFormat
      Displays the list of date and time formats available for the /Time switch.

      Example Usage: nmcap /TimeFormat

 /DisplayNetwork(s)
      Displays the network adapters that Network Monitor can capture from.
      Example Usage: nmcap /DisplayNetwork
                     nmcap /displaynetworks

 /SetNplPath <path>[;<path>;...]
      Builds a profile titled "NMCap Last Path" and attempts to compile.
      If compilation is successful, the new profile is set as active.
      If the provided NPL cannot compile, the Active Profile is unchanged.
      On success, any existing "NMCap Last Path" profile is updated.

 /DisplayNplPath
      Displays the NPL path.
      Example Usage: nmcap /DisplayNplPath
      Note:
      Nmcap gets the NPL files in the following order:
      1) Files in the current directory
      2) Files in the path set by /SetNplPath
      3) Default NMCap installation directory

 /DisplayProfiles
      Display the installed profiles.

 /DisplayProfileInfo <Profile Key>
      Display detailed information for the indicated profile.
      A Profile Key can be either the GUID or the Index displayed when using
      the /DisplayProfiles argument.

 /UseProfile <Profile Key>
      Use an alternate profile for the capture session. This setting must be
      before any /Capture arguments. Otherwise, the active profile is used.
      A Profile Key can be either the GUID or the Index displayed when using
      the /DisplayProfiles argument.

 /SetActiveProfile <Profile Key>
      Set the active profile for to the indicated profile. This setting changes
      the default profile for other Network Monitor applications, as well.
      A Profile Key can be either the GUID or the index displayed when using
      the /DisplayProfiles argument.

 /DeleteProfile <Profile Key>
      Delete the indicated profile.
      Only user-defined profiles can be deleted.
      A Profile Key can be either the GUID or the index displayed when using
      the /DisplayProfiles argument.

 /SetDefaultParser [NplFileName.npl]
      Specifies the default NPL parser
      Example Usage: nmcap /SetDefaultParser sparser.npl

 /DisplayDefaultParser
      Displays the default NPL parser.
      Example Usage: nmcap /DisplayDefaultParser
      Note: If you do not explicitly set the default parser using
      /SetDefaultParser, /DisplayDefaultParser does not display anything.

 /MaxFrameLength <Number of Bytes>
      Specifying the Max Frame Length limits the number of bytes captured per
      frame to the specified value.  If you enter a value of 68, every
      frame is truncated to the first 68 bytes.  This has an impact
      on filtering because the filter may require elements defined in the frame
      which are no longer present as a result of the truncation.
      Example Usage:  The following captures all traffic on all adapters
      and limits the captured data to the first 68 bytes.
      nmcap /network * /MaxFrameLength 68
      Note: This does not apply to frames retrieved from /inputcapture files.

 The following options are used together and have no meaning independently.
 Refer to the examples to better understand how they can be used together.

Specifying Input Sources:

   /Network <Network Adapter> [<network Adapter> ...]
      Selects one or more space-delimited network adapters to capture from.
      Adapters may be specified using their index, partial name with wildcard (*
), or
      quoted friendly name. (find using /DisplayNetwork above).
      Example Usage: /Network inte* 2 'Local Area Connection 1'

   /InputCapture <CaptureFile> [<CaptureFile> ...]
      Selects one or more space-delimited capture files to capture from.
      The frames in the capture files are replayed through NMCap.
      Example Usage: /InputCapture dns.cap tcp.cap c:\temp\test.cap

   /DisableConversations
      Disables conversations. This enhances the performance of
      NMCap. Some protocols such as MSRPC require conversation to be enabled.
      Example Usage: /DisableConversations

   /CaptureProcesses
      Enables process tracking. This is incompatible with the
      /DisableConversations switch as process tracking requires conversations.
      Example Usage: /CaptureProcesses

   /DisableLocalOnly
      Disables local-only capture. This enables the capture in p-mode. All
      frames seen by this computer are captured.
      Example Usage: /DisableLocalOnly

   /RecordFilters
      Records the capture filters in the capture file.
      Example Usage: /RecordFilters

   /RecordConfig
      Records the network configuration in the capture file.
      Example Usage: /RecordConfig

   /MinDiskQuotaPercentage <Minimal Disk Size Percentage>
      Specifies the minimal disk size percentage allowed.
      Note: Default minimal disk size percentage is 2 percent.
      Example Usage: /MinDiskQuotaPercentage 20
      (Sets the minimal disk size percentage to 20 percent.)

   /MinDiskQuota:<Minimal disk Size>
      Specifies the minimal disk size allowed.
      Example Usage: /MinDiskQuota 20M
      (Sets the minimal disk size to 20 MB.)

  /Frame <Filter>
      Frame filter. The frame filter is constructed from the NPL files.
      You can use all the filter expressions that you can in the Netmon UI.
      For more sample filters, type nmcap /Examples or see Standards Filter
      in the Filter Toolbar of the UI.
      This switch must be part of /StartWhen, /StopWhen, and /TerminateWhen.
      Example Usage: /Frame Dns.Flags.Stats == 3


Capture File output:

  /Capture [FrameFilter] /File <CaptureFile> [/File <CaptureFile>...]
      Saves frames that pass the frame filter to the specified capture files.
      Example Usage: /Capture dns.flags.status == 3 /File t.cap /File t2.cap

  /ReassembleCapture [FrameFilter] /File <CaptureFile> [/File <CaptureFile>...]
      An alternate to Capture (above) Saves frames that pass the frame filter
      to the specified capture files, along with reassembled payloads.
      Example Usage: /ReassembleCapture tcp /File tcp.cap /File tcp2.cap

  /File <Capture File>[:<File Size Limit>]
      Name of capture file to save frames to. Extensions are used to determine
      the behavior of NMCap.
       .cap -- Netmon 2 capture file
       .chn -- Series of Netmon 2 capture files: t.cap, t(1).cap, t(2).cap...
      <File Size Limit> is optional. It limits the file size of each capture
      file generated. Default single capture file size limit is 20 MB. The
      upper bound of the file size limit is 500 MB. The lower bound of the file

      size limit depends on the frame size captured. (Note that the maximal size

      of Ethernet frames is 1500 bytes)
      The files are circular, so once the size limit is reached, new data
      overwrites older data.
      Example Usage: /File t.cap:50M

Starting, stopping, and events:

  /StartWhen <Command Line Switch>
      List of conditions that specify when to start capturing network frames.
      If it is ignored, NMCap starts capturing immediately. When input
      from capture files by /InputCapture, this switch is generally ignored.
      Example Usage: /StartWhen /Time 7:02:00 AM 9/10/2005

  /StopWhen <Command Line Switch>
      List of conditions that specify when to stop capturing network frames.
      Example Usage: /StopWhen /TimeAfter 20 min
      This switch becomes active only after a preceding /StartWhen evaluates
      to TRUE.
      Example: /StartWhen /TimeAfter 10 min ... /StopWhen /TimeAfter 20 min
      Nmcap starts after 10 minutes and stops after 10+20=30 minutes.
      /StopWhen never terminates the program while the /StartWhen option
      is set to FALSE.  /TerminateWhen should be used to safely terminate immedi
ately.

  /TimeAfter <number>[units]
      Indicates a time period. This switch can be part of /StartWhen, /StopWhen,

      and /TerminateWhen. The user specifies the time units. By default it
      is in seconds.
      Example Usage: /TimeAfter 20 seconds

  /Time <Time/Date>
      Indicates a time of day. This switch can be part of /StartWhen, /StopWhen,

      and /TerminateWhen. The time and date format depends on the settings in
      the 'Region and Language' Control Panel.
      Example Usage: /Time 10:30:00 AM 9/10/2005

  /TerminateWhen <Command Line Switch>
      This switch terminates NMCap immediately once it evaluates to TRUE.
      Example Usage: /TerminateWhen /KeyPress x
      Note:
      The default relationship among the conditions following /Startwhen,
      /Stopwhen, and /TerminateWhen is AND and the order is sensitive.
      For example: /TerminateWhen /Timeafter 10 min /Keypress x
      Nmcap terminates after 10 minutes have passed and the user presses the 'x'
 key.
      And:         /TerminateWhen /Keypress x /Timeafter 10 min
      Nmcap terminates 10 minutes after the user press 'x' key.

  /KeyPress <character>
      Specifies which key to press. This switch can be part of /StartWhen,
      /StopWhen, and /TerminateWhen.
      Example Usage: /KeyPress z




● Visual C# .NETで WebBrowserコントロールのキャッシュを消す方法

 [HOWTO] Visual C# .NET で WebBrowser コントロールをホストするアプリケーションからキャッシュをクリアする方法

 kbwininet KB326201
 WinInet 関数
 Visual C# .NET でキャッシュをクリアする手順

WinInet's cache management APIs

 ただし、ここに掲載されているキャッシュクリアプログラムは無限ループ(infinite loop)になる。
 The first 'while(true)' loop in ClearCache() appears to go in an infinite loop
  if there are no error conditions; returnValue is true, GetLastWin32Error return 0,
   and so the next url cache group is never retrieved.
 I take it that DeleteUrlCacheGroup() used to have different behavior than
  it does now.
 - Sandra Walters Aug 13 '13 at 16:40

Class1.cs

using System;
using System.Runtime.InteropServices;

namespace Q326201CS
{
    ~~~~~
    ~~~~~
    ~~~~~

    // Loop through Cache Group, and then delete entries.
*** infinite loop at Windows 7 SP1 x64 ***
    while(true)
    {
        // Delete a particular Cache Group.
        returnValue = DeleteUrlCacheGroup(groupId, CACHEGROUP_FLAG_FLUSHURL_ONDELETE, IntPtr.Zero);
        if (!returnValue && ERROR_FILE_NOT_FOUND == Marshal.GetLastWin32Error())
        {
            returnValue = FindNextUrlCacheGroup(enumHandle, ref groupId, IntPtr.Zero);
        }

        if (!returnValue && (ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error() || ERROR_FILE_NOT_FOUND == Marshal.GetLastWin32Error()))
            break;
    }

    ~~~~~
    ~~~~~
    ~~~~~


 それの解決方法は下記の Stack Overflowの Oliver Bockの書き込み

Stack Overflow WebBrowser control caching issue

 Further to Serj Sagan, here is the code with bizarre error handling simplified, the infinite loop removed, and 32/64-bit capable.
- Oliver Bock answered Jun 25 at 6:18
/**
* Modified from code originally found here: http://support.microsoft.com/kb/326201
**/
public class WebBrowserHelper
{
    #region Definitions/DLL Imports
    /// <summary>
    /// For PInvoke: Contains information about an entry in the Internet cache
    /// </summary>
    [StructLayout(LayoutKind.Explicit)]
    public struct ExemptDeltaOrReserverd
    {
        [FieldOffset(0)]
        public UInt32 dwReserved;
        [FieldOffset(0)]
        public UInt32 dwExemptDelta;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct INTERNET_CACHE_ENTRY_INFOA
    {
        public UInt32 dwStructSize;
        public IntPtr lpszSourceUrlName;
        public IntPtr lpszLocalFileName;
        public UInt32 CacheEntryType;
        public UInt32 dwUseCount;
        public UInt32 dwHitRate;
        public UInt32 dwSizeLow;
        public UInt32 dwSizeHigh;
        public FILETIME LastModifiedTime;
        public FILETIME ExpireTime;
        public FILETIME LastAccessTime;
        public FILETIME LastSyncTime;
        public IntPtr lpHeaderInfo;
        public UInt32 dwHeaderInfoSize;
        public IntPtr lpszFileExtension;
        public ExemptDeltaOrReserverd dwExemptDeltaOrReserved;
    }

    // For PInvoke: Initiates the enumeration of the cache groups in the Internet cache
    [DllImport(@"wininet",
        SetLastError = true,
        CharSet = CharSet.Auto,
        EntryPoint = "FindFirstUrlCacheGroup",
        CallingConvention = CallingConvention.StdCall)]
    public static extern IntPtr FindFirstUrlCacheGroup(
        int dwFlags,
        int dwFilter,
        IntPtr lpSearchCondition,
    int dwSearchCondition,
    ref long lpGroupId,
    IntPtr lpReserved);

    // For PInvoke: Retrieves the next cache group in a cache group enumeration
    [DllImport(@"wininet",
    SetLastError = true,
        CharSet = CharSet.Auto,
    EntryPoint = "FindNextUrlCacheGroup",
        CallingConvention = CallingConvention.StdCall)]
    public static extern bool FindNextUrlCacheGroup(
        IntPtr hFind,
        ref long lpGroupId,
        IntPtr lpReserved);

    // For PInvoke: Releases the specified GROUPID and any associated state in the cache index file
    [DllImport(@"wininet",
        SetLastError = true,
        CharSet = CharSet.Auto,
        EntryPoint = "DeleteUrlCacheGroup",
        CallingConvention = CallingConvention.StdCall)]
    public static extern bool DeleteUrlCacheGroup(
        long GroupId,
        int dwFlags,
        IntPtr lpReserved);

    // For PInvoke: Begins the enumeration of the Internet cache
    [DllImport(@"wininet",
        SetLastError = true,
        CharSet = CharSet.Auto,
        EntryPoint = "FindFirstUrlCacheEntryA",
        CallingConvention = CallingConvention.StdCall)]
    public static extern IntPtr FindFirstUrlCacheEntry(
        [MarshalAs(UnmanagedType.LPTStr)] string lpszUrlSearchPattern,
        IntPtr lpFirstCacheEntryInfo,
        ref int lpdwFirstCacheEntryInfoBufferSize);

    // For PInvoke: Retrieves the next entry in the Internet cache
    [DllImport(@"wininet",
        SetLastError = true,
        CharSet = CharSet.Auto,
        EntryPoint = "FindNextUrlCacheEntryA",
        CallingConvention = CallingConvention.StdCall)]
    public static extern bool FindNextUrlCacheEntry(
        IntPtr hFind,
        IntPtr lpNextCacheEntryInfo,
        ref int lpdwNextCacheEntryInfoBufferSize);

    // For PInvoke: Removes the file that is associated with the source name from the cache, if the file exists
    [DllImport(@"wininet",
        SetLastError = true,
        CharSet = CharSet.Auto,
        EntryPoint = "DeleteUrlCacheEntryA",
        CallingConvention = CallingConvention.StdCall)]
    public static extern bool DeleteUrlCacheEntry(
        IntPtr lpszUrlName);
    #endregion

    /// <summary>
    /// Clears the cache of the web browser
    /// </summary>
    public static void ClearCache()
    {
        // Indicates that all of the cache groups in the user's system should be enumerated
        const int CACHEGROUP_SEARCH_ALL = 0x0;
        // Indicates that all the cache entries that are associated with the cache group
        // should be deleted, unless the entry belongs to another cache group.
        const int CACHEGROUP_FLAG_FLUSHURL_ONDELETE = 0x2;
        const int ERROR_INSUFFICIENT_BUFFER = 0x7A;

        // Delete the groups first.
        // Groups may not always exist on the system.
        // For more information, visit the following Microsoft Web site:
        // http://msdn.microsoft.com/library/?url=/workshop/networking/wininet/overview/cache.asp
        // By default, a URL does not belong to any group. Therefore, that cache may become
        // empty even when the CacheGroup APIs are not used because the existing URL does not belong to any group.
        long groupId = 0;
        IntPtr enumHandle = FindFirstUrlCacheGroup(0, CACHEGROUP_SEARCH_ALL, IntPtr.Zero, 0, ref groupId, IntPtr.Zero);
        if (enumHandle != IntPtr.Zero) {
            bool more;
            do {
                // Delete a particular Cache Group.
                DeleteUrlCacheGroup(groupId, CACHEGROUP_FLAG_FLUSHURL_ONDELETE, IntPtr.Zero);
                more = FindNextUrlCacheGroup(enumHandle, ref groupId, IntPtr.Zero);
            } while (more);
        }

        // Start to delete URLs that do not belong to any group.
        int cacheEntryInfoBufferSizeInitial = 0;
        FindFirstUrlCacheEntry(null, IntPtr.Zero, ref cacheEntryInfoBufferSizeInitial);  // should always fail because buffer is too small
        if (Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER) {
            int cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial;
            IntPtr cacheEntryInfoBuffer = Marshal.AllocHGlobal(cacheEntryInfoBufferSize);
            enumHandle = FindFirstUrlCacheEntry(null, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial);
            if (enumHandle != IntPtr.Zero) {
                bool more;
                do {
                    INTERNET_CACHE_ENTRY_INFOA internetCacheEntry = (INTERNET_CACHE_ENTRY_INFOA)Marshal.PtrToStructure(cacheEntryInfoBuffer, typeof(INTERNET_CACHE_ENTRY_INFOA));
                    cacheEntryInfoBufferSizeInitial = cacheEntryInfoBufferSize;
                    DeleteUrlCacheEntry(internetCacheEntry.lpszSourceUrlName);
                    more = FindNextUrlCacheEntry(enumHandle, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial);
                    if (!more && Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER) {
                        cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial;
                        cacheEntryInfoBuffer = Marshal.ReAllocHGlobal(cacheEntryInfoBuffer, (IntPtr)cacheEntryInfoBufferSize);
                        more = FindNextUrlCacheEntry(enumHandle, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial);
                    }
                } while (more);
            }
            Marshal.FreeHGlobal(cacheEntryInfoBuffer);
        }
    }
}





Tags: [Windows開発]



[HOME] | [BACK]
リンクフリー(連絡不要、ただしトップページ以外は Web構成の変更で移動する場合があります)
Copyright (c) 2014 FREE WING,Y.Sakamoto
Powered by 猫屋敷工房 & HTML Generator

http://www.neko.ne.jp/~freewing/software/packet_capture_ethernet/