Click here to Skip to main content
15,901,505 members
Please Sign up or sign in to vote.
1.50/5 (8 votes)
See more:
This code is a little progress to my previous question .. http://www.codeproject.com/Questions/448236/Monitoring-Network-Traffic

The problem is, I was not able to get the correct number of packets sent and received when the connection is established though my datacard (i.e. when I am connected to the internet usnig a modem)..

Kindly help me out..

Just like, in the network connections under control panel, the status shows so many info; how do I get it in my application?



C#
using System;
using System.Runtime;
using System.Runtime.InteropServices;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.NetworkInformation;

namespace NetworkTracer
{
    public partial class Tracer : Form
    {        
        private Timer _timer;
        private DateTime _startTime = DateTime.MinValue;
        private bool _isNetworkOnline;
        IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
        IPGlobalStatistics ipstat = null;
        Decimal start_r_packets;
        Decimal end_r_packets;

        public Tracer()
        {
            // check if connection exist or not

            InitializeComponent();

            btnMonitor.Enabled = true;
            btnCancel.Enabled = false;
            _timer = new Timer();           
            _timer.Tick += new EventHandler(timerTicker);
        }


        protected void startMonitor(object sender, EventArgs e)
        {
            _startTime = DateTime.Now;                        
            _timer.Start();                        
            btnMonitor.Enabled = false;
            btnCancel.Enabled = true;
            ipstat = properties.GetIPv4GlobalStatistics();

            getConnectionInfo();
        }

        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
        public static bool IsConnectedToInternet()
        {
            int Desc;
            return InternetGetConnectedState(out Desc, 0);
        }

        protected void getConnectionInfo()
        {
            try
            {
                string myHost = System.Net.Dns.GetHostName();
                IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(myHost);
                IPAddress[] addr = ipEntry.AddressList;
                NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
                _isNetworkOnline = NetworkInterface.GetIsNetworkAvailable();

                if (addr.Length > 0)
                {
                    start_r_packets = Convert.ToDecimal(ipstat.ReceivedPackets);
                    start_r_packets = Math.Round(start_r_packets / 1048576 * 100000) / 100000;
                    //System.Net.NetworkInformation.
                    txtboxInfo.Text = "";
                    txtboxInfo.Text += "IP Address: " + addr[addr.Length - 1].ToString() + Environment.NewLine;
                    txtboxInfo.Text += Environment.NewLine + "Is Network Available: " + _isNetworkOnline.ToString() + Environment.NewLine;                    
                    txtboxInfo.Text += Environment.NewLine + "Starting Received Packets (in mb): " + start_r_packets.ToString() + Environment.NewLine;
                    txtboxInfo.Text += Environment.NewLine + "Is Network up: " + System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable().ToString() + Environment.NewLine;
                    txtboxInfo.Text += Environment.NewLine + "New method output: " + IsConnectedToInternet().ToString();
                }                                
                
            }
            catch (Exception ex)
            {
                txtboxInfo.Text = "Error!" + Environment.NewLine + ex.Message.ToString();
                _timer.Stop();
                lblTime.Text = "";
                btnCancel.Enabled = false;
                btnMonitor.Enabled = false;
            }
        }

        protected void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) 
        { 
            _isNetworkOnline = e.IsAvailable; 
        } 

        protected void closeEverything(object sender, EventArgs e)
        {
            _timer.Stop();
            btnCancel.Enabled = false;
            btnMonitor.Enabled = true;
            txtboxInfo.Text = lblTime.Text + Environment.NewLine;

            ipstat = properties.GetIPv4GlobalStatistics();
            end_r_packets = Convert.ToDecimal(ipstat.ReceivedPackets);
            end_r_packets = Math.Round(end_r_packets / 1048576 * 100000) / 100000;

            txtboxInfo.Text += Environment.NewLine + "Starting Received Packets (in mb): " + start_r_packets.ToString() + Environment.NewLine;
            txtboxInfo.Text += Environment.NewLine + "Ending Received Packets (in mb): " + end_r_packets.ToString() + Environment.NewLine;
            end_r_packets = end_r_packets - start_r_packets;
            txtboxInfo.Text += Environment.NewLine + "Total Received Packets (in mb): " + end_r_packets.ToString() + Environment.NewLine;

            writetoFile();
        }

        protected void writetoFile()
        {
            string path_file = @"C:\\Documents and Settings\\user\\Desktop\\Test Tracer.txt";
            string empty_line = "===============================================================";
            if (System.IO.File.Exists(path_file))
            {
                System.IO.File.AppendAllText(path_file, empty_line + Environment.NewLine + "Connection opened: " + _startTime + Environment.NewLine + "Connection Closed: " + DateTime.Now.ToString() + Environment.NewLine + Environment.NewLine + txtboxInfo.Text + Environment.NewLine);
            }
        }

        protected void timerTicker(object sender, EventArgs e)
        {
            var timeSinceStartTime = DateTime.Now - _startTime;
            timeSinceStartTime = new TimeSpan(timeSinceStartTime.Hours,
                                              timeSinceStartTime.Minutes,
                                              timeSinceStartTime.Seconds);                        
            lblTime.Text = "Time: " + timeSinceStartTime.ToString();
        }
    }
}
Posted
Updated 9-Sep-12 22:40pm
v3
Comments
manognya kota 10-Sep-12 2:25am    
What is the question?
Prasad_Kulkarni 10-Sep-12 2:25am    
What is this??
prashant patil 4987 10-Sep-12 2:26am    
whats your question??????? put your question properly.
Menon Santosh 10-Sep-12 2:33am    
code is useless without question :)
bbirajdar 10-Sep-12 3:02am    
Not a question

 
Share this answer
 
If you are ready to look at existing ideas:

SharpPcap - A Packet Capture Framework for .NET[^]

Open Source WinPCap is PInvoked and created SharpPCap. Try to see if you can gain anything or make your code more efficient.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900