{"id":294,"date":"2011-10-31T08:09:43","date_gmt":"2011-10-30T22:09:43","guid":{"rendered":"http:\/\/www.reenadu.com\/?p=294"},"modified":"2011-10-31T08:09:43","modified_gmt":"2011-10-30T22:09:43","slug":"build-your-own-network-usage-monitor-in-c-raw-socket","status":"publish","type":"post","link":"https:\/\/nickdu.com\/?p=294","title":{"rendered":"Build your own network usage monitor in C# (raw socket)"},"content":{"rendered":"<p>Although there are lots of excellent network monitor available, e.g <a title=\"NetWorx\" href=\"http:\/\/www.softperfect.com\/products\/networx\/\" target=\"_blank\">NetWorx<\/a>, <a title=\"DU Meter\" href=\"http:\/\/www.hageltech.com\/dumeter\/about\" target=\"_blank\">DU Meter<\/a>, I just think to build my own network monitor. Firstly I can explore the socket programming, secondly it&#8217;s free of charge.<\/p>\n<p>OK, let&#8217;s do it.<\/p>\n<p>Create a new WinForm project from Visual Studio<\/p>\n<figure id=\"attachment_295\" aria-describedby=\"caption-attachment-295\" style=\"width: 248px\" class=\"wp-caption alignleft\"><a href=\"http:\/\/www.nickdu.com\/wp-content\/uploads\/2011\/10\/monitor.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-295\" title=\"monitor\" src=\"http:\/\/www.nickdu.com\/wp-content\/uploads\/2011\/10\/monitor.jpg\" alt=\"Network monitor\" width=\"248\" height=\"72\" \/><\/a><figcaption id=\"caption-attachment-295\" class=\"wp-caption-text\">Network monitor<\/figcaption><\/figure>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<pre lang=\"CSharp\">\npublic MainForm()\n{\n\t\/\/\n\t\/\/ Required for Windows Form Designer support\n\t\/\/\n\tInitializeComponent();\n\t\/\/\n\t\/\/ Set your PC ip address\n\t\/\/\n\trs.CreateAndBindSocket(ipaddress);\n\trs.Run();\n}\n\/\/when main window showing up, we update meter text\nprivate void ShowMainWindow(object sender, System.EventArgs e)\n{\n\ttodayUsage.Text = string.Format(\"Today's Usage: {0}\",FormatSize((ulong)rs.TotalReceivedBytes));\t\n}\n\/\/define ip header\n[StructLayout(LayoutKind.Explicit)]  \npublic   struct   IPHeader  \n{  \n\t[FieldOffset(0)]    public  byte       ip_verlen;    \n\t[FieldOffset(1)]    public  byte       ip_tos;    \n\t[FieldOffset(2)]    public  ushort     ip_totallength;  \n\t[FieldOffset(4)]    public  ushort     ip_id;  \n\t[FieldOffset(6)]    public  ushort     ip_offset;    \n\t[FieldOffset(8)]    public  byte       ip_ttl;    \n\t[FieldOffset(9)]    public  byte       ip_protocol;    \n\t[FieldOffset(10)]   public  ushort   ip_checksum;    \n\t[FieldOffset(12)]   public  uint       ip_srcaddr;    \n\t[FieldOffset(16)]   public  uint       ip_destaddr;    \n}  \n\/\/the core function - raw socket   \npublic   class   RawSocket  \n{\n\tprivate\t\tbool\terror_occurred;  \n\tprivate\t  int\ttotalReceivedBytes = 0;\n\tprivate\t  const   int   BUFFER_SIZE = 8192;\n\tprivate\t  byte []\treceive_buf = new byte[BUFFER_SIZE];\n\tprivate\t  Socket\tsocket   =   null;    \n\tconst\t  int   SIO_R = unchecked((int)0x98000001);  \n\tconst\t  int   SIO_1 = unchecked((int)0x98000002);  \n\tconst\t  int   SIO_2 = unchecked((int)0x98000003);  \n\n\tpublic   int   TotalReceivedBytes\n\t{  \n\t\tget\t{return   totalReceivedBytes;}  \n\t\tset\t{totalReceivedBytes = value;}\n\t}\n\n\tpublic   RawSocket() \n\t{  \n\t\terror_occurred=false;   \n\t}  \n       \n\tpublic   void   CreateAndBindSocket(string   IP)\n\t{  \n\t\tsocket   =   new   Socket(AddressFamily.InterNetwork,   SocketType.Raw,   ProtocolType.IP);  \n\t\tsocket.Blocking   =   false; \n\t\tsocket.Bind(new   IPEndPoint(IPAddress.Parse(IP),   0));  \n\t\tif   (SetSocketOption()==false)   \n\t\t\terror_occurred=true;  \n\t}  \n   \n\tpublic   bool   ErrorOccurred  \n\t{  \n\t\tget  { return   error_occurred;}  \n\t}\n\n\tpublic   void   Shutdown()  \n\t{  \n\t\terror_occurred = true;\n\t\tif(socket   !=   null)  \n\t\t{  \n\t\t\tsocket.Shutdown(SocketShutdown.Both);  \n\t\t\tsocket.Close();  \n\t\t}  \n\t}  \n  \n\tprivate   bool   SetSocketOption()  \n\t{  \n\t\tbool   ret_value   =   true;  \n\t\ttry  \n\t\t{  \n\t\t\tsocket.SetSocketOption(SocketOptionLevel.IP,   SocketOptionName.HeaderIncluded,   1);       \n\t\t\tbyte   []IN   =   new   byte[4]{1,   0,   0,   0};  \n\t\t\tbyte   []OUT   =   new   byte[4];      \n\t\t\tint   ret_code   =   socket.IOControl(SIO_R,   IN,   OUT);\n\t\t\tret_code   =   OUT[0]   +   OUT[1]   +   OUT[2]   +   OUT[3];   \n\t\t\tif(ret_code   !=   0)   ret_value   =   false;  \n\t\t}  \n\t\tcatch(SocketException)  \n\t\t{  \n\t\t\tret_value   =   false;  \n\t\t}  \n\t\treturn   ret_value;  \n\t}\n\n\tunsafe   private   bool   IsInternetTraffic(byte[] buf)  \n\t{  \n\t\tbyte\ttemp_protocol=0;  \n\t\tuint\ttemp_version=0;  \n\t\tuint\ttemp_ip_srcaddr=0;  \n\t\tstring  sourceIP;  \n  \n\t\tfixed(byte   *fixed_buf   =   buf)  \n\t\t{  \n\t\t\tIPHeader   *   head   =   (IPHeader   *)   fixed_buf;  \n\t\t\ttemp_protocol   =   head->ip_protocol;  \n\t\t\ttemp_version   =(uint)(head->ip_verlen   &   0xF0)   >>   4;  \n\t\t\ttemp_ip_srcaddr   =   head->ip_srcaddr;  \n\t\t\tsourceIP   =   new   IPAddress(temp_ip_srcaddr).ToString();  \n\t\t}\n                \/\/we only capture internet traffic  \n\t\treturn !sourceIP.StartsWith(\"10.\") \n\t\t\t&& !sourceIP.StartsWith(\"172.16.\") \n\t\t\t&& !sourceIP.StartsWith(\"127.\") \n\t\t\t&& !sourceIP.StartsWith(\"192.168.\");\n\t}  \n       \n\tprivate void ReceiveCallback( IAsyncResult ar)\n\t{\n\t\ttry\n\t\t{\n\t\t\tint received_bytes = socket.EndReceive(ar);\n\t\t\tif(received_bytes>0 && IsInternetTraffic(receive_buf))\n\t\t\t{\n\t\t\t\ttotalReceivedBytes += received_bytes;\n\t\t\t}\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tsocket.BeginReceive(receive_buf,0,BUFFER_SIZE,SocketFlags.None,new AsyncCallback(ReceiveCallback),null);\n\t\t}\n\t}\n\t\t\n\tpublic   void   Run()    \n\t{  \n\t\tsocket.BeginReceive(receive_buf,0,BUFFER_SIZE,SocketFlags.None,new AsyncCallback(ReceiveCallback),null);\n\t}\n}\n\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Although there are lots of excellent network monitor available, e.g NetWorx, DU Meter, I just think to build my own network monitor. Firstly I can explore the socket programming, secondly it&#8217;s free of charge. OK, let&#8217;s do it. Create a new WinForm project from Visual Studio &nbsp; &nbsp; &nbsp; &nbsp; public MainForm() { \/\/ \/\/ &hellip; <a href=\"https:\/\/nickdu.com\/?p=294\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Build your own network usage monitor in C# (raw socket)&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9,2],"tags":[],"class_list":["post-294","post","type-post","status-publish","format-standard","hentry","category-net","category-it"],"_links":{"self":[{"href":"https:\/\/nickdu.com\/index.php?rest_route=\/wp\/v2\/posts\/294","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nickdu.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nickdu.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nickdu.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nickdu.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=294"}],"version-history":[{"count":0,"href":"https:\/\/nickdu.com\/index.php?rest_route=\/wp\/v2\/posts\/294\/revisions"}],"wp:attachment":[{"href":"https:\/\/nickdu.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=294"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nickdu.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=294"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nickdu.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=294"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}