In this tutorial, I will show you how to receive network traffic with a simple C# code source.
First, create one folder named NetConsole and go in this with these commands:
1 2 | mkdir NetConsole cd NetConsole |
Run the install for DotNet, you can add a package if you want:
1 2 3 4 5 6 | NetConsole>dotnet new --install .\ Welcome to .NET 5.0! --------------------- SDK Version: 5.0.411 ... |
You can see the version of this project and list all templates with these two commands:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | dotnet --version 5.0.411 ... dotnet new --list Template Name Short Name Language Tags -------------------------------------------- ------------------- ---------- ------------------------------------- Console Application console [C#],F#,VB Common/Console Class library classlib [C#],F#,VB Common/Library WPF Application wpf [C#] Common/WPF WPF Class library wpflib [C#] Common/WPF WPF Custom Control Library wpfcustomcontrollib [C#] Common/WPF WPF User Control Library wpfusercontrollib [C#] Common/WPF Windows Forms (WinForms) Application winforms [C#] Common/WinForms Windows Forms (WinForms) Class library winformslib [C#] Common/WinForms Worker Service worker [C#] Common/Worker/Web ... |
Start one new console project with this command:
1 2 3 4 5 6 7 8 | dotnet new console The template "Console Application" was created successfully. Processing post-creation actions... Running 'dotnet restore' on C:\CSharpprojects\NetConsole\NetConsole.csproj... Determining projects to restore... Restored C:\CSharpprojects\NetConsole\NetConsole.csproj (in 582 ms). Restore succeeded. |
Change the default content for Program.cs with this source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | using System; using System.Net.NetworkInformation; namespace NetConsole { class Program { static void Main() { if (!NetworkInterface.GetIsNetworkAvailable()) return; NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface ni in interfaces) { Console.WriteLine(" Bytes Sent: {0}", ni.GetIPv4Statistics().BytesSent); Console.WriteLine(" Bytes Received: {0}", ni.GetIPv4Statistics().BytesReceived); } } } } |
You can run the program with this command:
1 2 3 4 5 | dotnet run Bytes Sent: 336910154 Bytes Received: 16398125819 Bytes Sent: 0 Bytes Received: 0 |