Skip to content

Instantly share code, notes, and snippets.

@russcam
Created August 24, 2020 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save russcam/0d62586b8b23faa0a30444a9abb44f50 to your computer and use it in GitHub Desktop.
Save russcam/0d62586b8b23faa0a30444a9abb44f50 to your computer and use it in GitHub Desktop.
Get active TCP connection states and statistics
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation
public static class TcpStats
{
private static int _stateLength = Enum.GetNames(typeof(TcpState)).Length;
private static int _longestState = Enum.GetNames(typeof(TcpState)).Max(s => s.Length);
public static string GetTcpStates(bool detailed)
{
var builder = new StringBuilder();
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
var states = new Dictionary<TcpState, int>(_stateLength);
foreach (var connection in properties.GetActiveTcpConnections())
{
if (detailed)
{
builder.AppendLine($"{connection.State.ToString().PadRight(_longestState)}: {connection.RemoteEndPoint.Address}:{connection.RemoteEndPoint.Port}");
}
if (states.TryGetValue(connection.State, out var count))
{
states[connection.State] = ++count;
}
else
{
states.Add(connection.State, 1);
}
}
builder.AppendLine("TCP states:");
foreach (var kv in states)
{
var key = kv.Key.ToString();
builder.AppendLine($" {key}: {new string(' ', _longestState - key.Length)}\t{kv.Value}");
}
return builder.ToString();
}
public static string GetTcpStats(NetworkInterfaceComponent version)
{
var builder = new StringBuilder();
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
TcpStatistics tcpstat = null;
switch (version)
{
case NetworkInterfaceComponent.IPv4:
tcpstat = properties.GetTcpIPv4Statistics();
builder.AppendLine("TCP/IPv4 Statistics:");
break;
case NetworkInterfaceComponent.IPv6:
tcpstat = properties.GetTcpIPv6Statistics();
builder.AppendLine("TCP/IPv6 Statistics:");
break;
default:
throw new ArgumentException("version");
}
builder
.AppendLine($" Minimum Transmission Timeout: {tcpstat.MinimumTransmissionTimeout}")
.AppendLine($" Maximum Transmission Timeout: {tcpstat.MaximumTransmissionTimeout}")
.AppendLine(" Connection Data:")
.AppendLine($" Current: {tcpstat.CurrentConnections}")
.AppendLine($" Cumulative: {tcpstat.CumulativeConnections}")
.AppendLine($" Initiated: {tcpstat.ConnectionsInitiated}")
.AppendLine($" Accepted: {tcpstat.ConnectionsAccepted}")
.AppendLine($" Failed Attempts: {tcpstat.FailedConnectionAttempts}")
.AppendLine($" Reset: {tcpstat.ResetConnections}")
.AppendLine(" Segment Data:")
.AppendLine($" Received: {tcpstat.SegmentsReceived}")
.AppendLine($" Sent: {tcpstat.SegmentsSent}")
.AppendLine($" Retransmitted: {tcpstat.SegmentsResent}");
return builder.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment