-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame_net_analyzer.ps1
More file actions
2364 lines (2023 loc) · 84.2 KB
/
Copy pathgame_net_analyzer.ps1
File metadata and controls
2364 lines (2023 loc) · 84.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory=$false)]
[ValidateSet("pcap","live","compare","menu")]
[string]$Mode = "menu",
# Per Mode=pcap -> file da analizzare
[Parameter(Mandatory=$false)]
[string]$PcapPath,
# Per Mode=live -> interfaccia e durata
[Parameter(Mandatory=$false)]
[string]$Interface = "Ethernet",
[Parameter(Mandatory=$false)]
[ValidateRange(5,600)]
[int]$CaptureSeconds = 30,
# Nome gioco (serve solo per etichetta, detection è auto)
[Parameter(Mandatory=$false)]
[string]$GameName = "Auto",
# Cartella output report (ora relativa a game_net_reports)
[Parameter(Mandatory=$false)]
[string]$OutputDir = "",
# Filtro tshark personalizzato
[Parameter(Mandatory=$false)]
[string]$CustomFilter = "ip && (udp || quic)",
# Per Mode=compare -> pattern files JSON
[Parameter(Mandatory=$false)]
[string]$ComparePattern = "*.json",
# Per Mode=compare -> output HTML compare
[Parameter(Mandatory=$false)]
[string]$CompareOutHtml,
# Abilita diagnostica rete (ping/traceroute)
[Parameter(Mandatory=$false)]
[switch]$EnableDiagnostics,
# Analisi separata traffico QUIC
[Parameter(Mandatory=$false)]
[switch]$AnalyzeQUIC,
# Fight segment: tempo inizio (secondi dall'inizio capture)
[Parameter(Mandatory=$false)]
[double]$FightStartSec = 0,
# Fight segment: tempo fine (secondi dall'inizio capture, 0 = fino alla fine)
[Parameter(Mandatory=$false)]
[double]$FightEndSec = 0,
# HUD mode: mostra metriche real-time durante capture live
[Parameter(Mandatory=$false)]
[switch]$HudMode,
# Test bufferbloat: misura latenza sotto carico
[Parameter(Mandatory=$false)]
[switch]$TestBufferbloat
)
# ================== CONFIG ==================
$ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest
# Path a tshark se non è nel PATH (altrimenti lascia $null)
$Global:TsharkPathOverride = $null # es. "C:\Program Files\Wireshark\tshark.exe"
$Global:ScriptVersion = "1.0.0"
# Profili gioco con tick rates e regioni target
$Global:GameProfiles = @{
"Fortnite" = @{
ExpectedTickMs = 20.0
TargetRegions = @("AWS FRA", "AWS DUB", "eu-central-1", "eu-west-1")
Notes = "Performance mode, UDP/QUIC mix"
}
"Warzone" = @{
ExpectedTickMs = 16.7
TargetRegions = @("AMS", "FRA")
Notes = "Call of Duty: Warzone"
}
"Valorant" = @{
ExpectedTickMs = 8.0
TargetRegions = @("EU West", "euw1")
Notes = "Riot Games - 128-tick servers"
}
"CS2" = @{
ExpectedTickMs = 7.8
TargetRegions = @("EU", "Luxembourg")
Notes = "Counter-Strike 2 - 128-tick subtick"
}
"LeagueOfLegends" = @{
ExpectedTickMs = 33.3
TargetRegions = @("EUW", "EUNE")
Notes = "30Hz tick rate"
}
}
# ============================================
function Test-Prerequisites {
<#
.SYNOPSIS
Checks system requirements and dependencies
#>
[CmdletBinding()]
param()
$issues = @()
# Check OS
if (-not $IsWindows -and $PSVersionTable.PSVersion.Major -ge 6) {
$issues += "This tool requires Windows (detected: $($PSVersionTable.OS))"
}
# Check PowerShell version
if ($PSVersionTable.PSVersion.Major -lt 5) {
$issues += "PowerShell 5.1 or higher required (current: $($PSVersionTable.PSVersion))"
}
# Check tshark
try {
$tshark = Get-TsharkPath -ErrorAction Stop
Write-Verbose "tshark found at: $tshark"
}
catch {
$issues += "Wireshark/tshark not found. Please install from: https://www.wireshark.org/download.html"
}
if ($issues.Count -gt 0) {
Write-Host "`n❌ PREREQUISITES CHECK FAILED" -ForegroundColor Red
Write-Host "The following issues were detected:`n" -ForegroundColor Yellow
foreach ($issue in $issues) {
Write-Host " • $issue" -ForegroundColor Yellow
}
Write-Host "`n📋 Installation Guide:" -ForegroundColor Cyan
Write-Host " 1. Install Wireshark: https://www.wireshark.org/download.html" -ForegroundColor White
Write-Host " - During installation, ensure 'TShark' component is selected" -ForegroundColor Gray
Write-Host " 2. Add Wireshark to PATH, or the tool will auto-detect common locations" -ForegroundColor White
Write-Host " 3. For live captures, run PowerShell as Administrator`n" -ForegroundColor White
return $false
}
Write-Verbose "All prerequisites met"
return $true
}
function Initialize-OutputStructure {
<#
.SYNOPSIS
Crea la struttura di cartelle organizzata per i report
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[string]$BaseDir = "."
)
$baseReportDir = Join-Path $BaseDir "game_net_reports"
# Crea cartella principale se non esiste
if (-not (Test-Path $baseReportDir)) {
New-Item -ItemType Directory -Path $baseReportDir -Force | Out-Null
Write-Verbose "Creata cartella principale: $baseReportDir"
}
# Crea sottocartelle
$subDirs = @(
"pcap_analysis",
"live_captures",
"comparisons",
"diagnostics"
)
foreach ($dir in $subDirs) {
$path = Join-Path $baseReportDir $dir
if (-not (Test-Path $path)) {
New-Item -ItemType Directory -Path $path -Force | Out-Null
Write-Verbose "Creata sottocartella: $path"
}
}
return $baseReportDir
}
function Get-OutputDirectory {
<#
.SYNOPSIS
Determina la directory di output in base al tipo di analisi
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[ValidateSet("pcap","live","compare","diagnostics")]
[string]$AnalysisType,
[Parameter(Mandatory=$false)]
[string]$GameName = "Other",
[Parameter(Mandatory=$false)]
[string]$CustomOutputDir = ""
)
# Se specificata custom dir, usala (per backward compatibility CLI)
if ($CustomOutputDir -and $CustomOutputDir -ne "") {
return $CustomOutputDir
}
# Altrimenti usa struttura organizzata
$scriptDir = Split-Path -Parent $PSCommandPath
$baseReportDir = Initialize-OutputStructure -BaseDir $scriptDir
switch ($AnalysisType) {
"pcap" {
$subDir = Join-Path (Join-Path $baseReportDir "pcap_analysis") $GameName
if (-not (Test-Path $subDir)) {
New-Item -ItemType Directory -Path $subDir -Force | Out-Null
}
return $subDir
}
"live" {
return Join-Path $baseReportDir "live_captures"
}
"compare" {
return Join-Path $baseReportDir "comparisons"
}
"diagnostics" {
return Join-Path $baseReportDir "diagnostics"
}
}
}
function Get-TsharkPath {
<#
.SYNOPSIS
Trova il percorso di tshark.exe
#>
[CmdletBinding()]
param()
Write-Verbose "Searching for tshark.exe..."
if ($Global:TsharkPathOverride -and (Test-Path $Global:TsharkPathOverride)) {
Write-Verbose "Uso TsharkPathOverride: $Global:TsharkPathOverride"
return $Global:TsharkPathOverride
}
# Prova Get-Command prima
$cmd = Get-Command tshark -ErrorAction SilentlyContinue
if ($cmd) {
Write-Verbose "tshark found in PATH: $($cmd.Source)"
return $cmd.Source
}
# Cerca in percorsi comuni su Windows
$commonPaths = @(
"C:\Program Files\Wireshark\tshark.exe",
"C:\Program Files (x86)\Wireshark\tshark.exe",
"$env:ProgramFiles\Wireshark\tshark.exe",
"${env:ProgramFiles(x86)}\Wireshark\tshark.exe"
)
foreach ($path in $commonPaths) {
if (Test-Path $path) {
Write-Verbose "tshark found at: $path"
return $path
}
}
# Non trovato
$errMsg = @"
tshark.exe non trovato nel PATH o nelle directory comuni.
Soluzioni:
1. Installa Wireshark da https://www.wireshark.org/download.html
2. Aggiungi 'C:\Program Files\Wireshark' al PATH di sistema
3. Oppure imposta `$Global:TsharkPathOverride nello script
PATH attuale: $env:PATH
"@
throw $errMsg
}
function Get-LocalIPv4 {
<#
.SYNOPSIS
Ottiene tutti gli IP locali IPv4 (escluso loopback)
#>
[CmdletBinding()]
param()
Write-Verbose "Collecting local IP addresses..."
try {
$ips = Get-NetIPAddress -AddressFamily IPv4 -PrefixOrigin Dhcp,Manual -ErrorAction Stop `
| Where-Object { $_.IPAddress -ne "127.0.0.1" } `
| Select-Object -ExpandProperty IPAddress
if (-not $ips) {
throw "Nessun indirizzo IPv4 valido trovato (escluso loopback)"
}
Write-Verbose "Local IPs found: $($ips -join ', ')"
return $ips
}
catch {
throw "Errore nel recupero degli indirizzi locali: $_"
}
}
function Invoke-TsharkCsv {
<#
.SYNOPSIS
Esegue tshark e restituisce CSV parsato
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Pcap,
[Parameter(Mandatory=$false)]
[string]$Filter = "ip && (udp || quic)"
)
if (-not (Test-Path $Pcap)) {
throw "File PCAP non trovato: $Pcap"
}
$pcapResolved = Resolve-Path $Pcap -ErrorAction Stop
Write-Verbose "PCAP analysis: $pcapResolved"
Write-Verbose "Filtro: $Filter"
$tshark = Get-TsharkPath
$tsharkArgs = @(
"-r", $pcapResolved.Path,
"-Y", $Filter,
"-T", "fields",
"-E", "header=y",
"-E", "separator=,",
"-e", "frame.time_epoch",
"-e", "ip.src",
"-e", "ip.dst",
"-e", "udp.srcport",
"-e", "udp.dstport",
"-e", "_ws.col.Protocol",
"-e", "frame.len"
)
Write-Verbose "Esecuzione: $tshark $($tsharkArgs -join ' ')"
try {
$csvText = & $tshark @tsharkArgs 2>&1
if ($LASTEXITCODE -ne 0) {
throw "tshark exit code: $LASTEXITCODE. Output: $csvText"
}
if (-not $csvText) {
throw "tshark non ha prodotto output. Il file potrebbe essere vuoto o il filtro troppo restrittivo."
}
$csv = $csvText | ConvertFrom-Csv
Write-Verbose "Packets read: $($csv.Count)"
return $csv
}
catch {
throw "Errore esecuzione tshark: $_"
}
}
function Analyze-Flow {
<#
.SYNOPSIS
Analizza un singolo flusso UDP server->client
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[array]$Packets,
[Parameter(Mandatory=$true)]
[string]$LocalIP,
[Parameter(Mandatory=$true)]
[string]$RemoteIP,
[Parameter(Mandatory=$true)]
[string]$RemotePort
)
Write-Verbose "Flow analysis: ${RemoteIP}:${RemotePort} -> $LocalIP"
# Filtra solo traffico Server -> Client
$svrPkts = $Packets | Where-Object {
$_."ip.src" -eq $RemoteIP -and
$_."ip.dst" -eq $LocalIP -and
$_."udp.srcport" -eq $RemotePort
} | Sort-Object {[double]$_."frame.time_epoch"}
if ($svrPkts.Count -lt 5) {
Write-Warning "Troppi pochi pacchetti server->client ($($svrPkts.Count)). Serve almeno 5 pacchetti."
return $null
}
Write-Verbose "Pacchetti server->client: $($svrPkts.Count)"
$times = @()
$lens = @()
foreach ($p in $svrPkts) {
$times += [double]$p."frame.time_epoch"
$lens += [int]$p."frame.len"
}
$first = $times[0]
$last = $times[-1]
$duration = $last - $first
# inter-arrival
$deltas = @()
for ($i=1; $i -lt $times.Count; $i++) {
$d = ($times[$i] - $times[$i-1]) * 1000.0 # ms
$deltas += $d
}
$avgDelta = ($deltas | Measure-Object -Average).Average
$minDelta = ($deltas | Measure-Object -Minimum).Minimum
$maxDelta = ($deltas | Measure-Object -Maximum).Maximum
# jitter = deviazione assoluta media
$jitterAbs = @()
foreach ($d in $deltas) {
$jitterAbs += [math]::Abs($d - $avgDelta)
}
$avgJitter = ($jitterAbs | Measure-Object -Average).Average
$maxJitter = ($jitterAbs | Measure-Object -Maximum).Maximum
# burst detection: delta < avgDelta/3
$burstThreshold = $avgDelta / 3.0
$burstCount = @($deltas | Where-Object { $_ -lt $burstThreshold }).Count
$burstRatio = if ($deltas.Count -gt 0) { $burstCount / $deltas.Count } else { 0 }
# spike detection: delta > avgDelta * 2.5
$spikeThreshold = $avgDelta * 2.5
$spikeCount = @($deltas | Where-Object { $_ -gt $spikeThreshold }).Count
$spikeRatio = if ($deltas.Count -gt 0) { $spikeCount / $deltas.Count } else { 0 }
Write-Verbose "Metriche: AvgDelta=$([math]::Round($avgDelta,2))ms, AvgJitter=$([math]::Round($avgJitter,2))ms, Burst=$([math]::Round($burstRatio,3)), Spike=$([math]::Round($spikeRatio,3))"
# jitter timeline per grafico
$timeline = @()
for ($i=0; $i -lt $deltas.Count; $i++) {
$timeline += [pscustomobject]@{
t = [math]::Round(($times[$i+1] - $first),3) # secondi dall'inizio
d = [math]::Round($deltas[$i],3) # delta ms
}
}
# lunghezze pacchetti (packet size distribuzione)
$lenStats = @{
min = ($lens | Measure-Object -Minimum).Minimum
max = ($lens | Measure-Object -Maximum).Maximum
avg = ($lens | Measure-Object -Average).Average
}
return [pscustomobject]@{
LocalIP = $LocalIP
RemoteIP = $RemoteIP
RemotePort = $RemotePort
PacketCount = $svrPkts.Count
DurationSec = [math]::Round($duration,3)
PktPerSec = if ($duration -gt 0) { [math]::Round($svrPkts.Count / $duration,1) } else { 0 }
AvgDeltaMs = [math]::Round($avgDelta,3)
MinDeltaMs = [math]::Round($minDelta,3)
MaxDeltaMs = [math]::Round($maxDelta,3)
AvgJitterMs = [math]::Round($avgJitter,3)
MaxJitterMs = [math]::Round($maxJitter,3)
BurstRatio = [math]::Round($burstRatio,3)
SpikeRatio = [math]::Round($spikeRatio,3)
LenStats = $lenStats
Timeline = $timeline
}
}
function Score-Metric {
<#
.SYNOPSIS
Assegna un grade (S+/S/A/B/C) a una metrica
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Name,
[Parameter(Mandatory=$true)]
[double]$Value
)
switch ($Name) {
"AvgJitterMs" {
if ($Value -le 1.0) { return "S+" }
elseif ($Value -le 2.0) { return "S" }
elseif ($Value -le 4.0) { return "A" }
elseif ($Value -le 8.0) { return "B" }
else { return "C" }
}
"BurstRatio" {
if ($Value -le 0.01) { return "S+" }
elseif ($Value -le 0.03) { return "S" }
elseif ($Value -le 0.06) { return "A" }
elseif ($Value -le 0.1) { return "B" }
else { return "C" }
}
"SpikeRatio" {
if ($Value -le 0.005) { return "S+" }
elseif ($Value -le 0.01) { return "S" }
elseif ($Value -le 0.03) { return "A" }
elseif ($Value -le 0.06) { return "B" }
else { return "C" }
}
default { return "N/A" }
}
}
function Get-OverallScore {
<#
.SYNOPSIS
Calcola lo score complessivo da più grades
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string[]]$Grades
)
$map = @{
"S+" = 5.0
"S" = 4.5
"A" = 4.0
"B" = 3.0
"C" = 2.0
"N/A"= 0.0
}
$vals = $Grades | ForEach-Object { $map[$_] }
if ($vals.Count -eq 0) { return "N/A" }
$avg = ($vals | Measure-Object -Average).Average
if ($avg -ge 4.75) { return "S+" }
elseif ($avg -ge 4.3) { return "S" }
elseif ($avg -ge 3.5) { return "A" }
elseif ($avg -ge 2.5) { return "B" }
else { return "C" }
}
function Resolve-HostnameSafe {
<#
.SYNOPSIS
Risolve hostname da IP (con timeout e gestione errori)
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$IP
)
Write-Verbose "Resolving hostname for $IP..."
try {
$h = [System.Net.Dns]::GetHostEntry($IP)
Write-Verbose "Hostname resolved: $($h.HostName)"
return $h.HostName
}
catch {
Write-Verbose "Impossibile risolvere hostname per ${IP}: $_"
return ""
}
}
function Get-RegionFromHostname {
<#
.SYNOPSIS
Identifica la regione AWS/Cloud dal hostname
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Hostname
)
if (-not $Hostname) { return "" }
# Mappa regioni AWS
$awsRegions = @{
"eu-central-1" = "AWS Frankfurt (eu-central-1)"
"eu-west-1" = "AWS Dublin (eu-west-1)"
"eu-west-2" = "AWS London (eu-west-2)"
"eu-south-1" = "AWS Milan (eu-south-1)"
"us-east-1" = "AWS Virginia (us-east-1)"
"us-west-1" = "AWS California (us-west-1)"
"us-west-2" = "AWS Oregon (us-west-2)"
"ap-southeast-1" = "AWS Singapore (ap-southeast-1)"
"ap-northeast-1" = "AWS Tokyo (ap-northeast-1)"
}
foreach ($region in $awsRegions.Keys) {
if ($Hostname -match $region) {
return $awsRegions[$region]
}
}
# Riot Games
if ($Hostname -match "euw1") { return "Riot Games EUW (Europe West)" }
if ($Hostname -match "eune1") { return "Riot Games EUNE (Europe Nordic & East)" }
if ($Hostname -match "na1") { return "Riot Games NA (North America)" }
# Altri pattern
if ($Hostname -match "amsterdam|ams") { return "Amsterdam" }
if ($Hostname -match "frankfurt|fra") { return "Frankfurt" }
if ($Hostname -match "london|lon") { return "London" }
if ($Hostname -match "paris|par") { return "Paris" }
return "Unknown"
}
function Get-GameProfile {
<#
.SYNOPSIS
Ottiene il profilo di un gioco se esiste
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$GameName
)
if ($Global:GameProfiles.ContainsKey($GameName)) {
return $Global:GameProfiles[$GameName]
}
return $null
}
function Invoke-NetworkDiagnostics {
<#
.SYNOPSIS
Esegue diagnostica di rete (ping, traceroute) verso un server
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$RemoteIP,
[Parameter(Mandatory=$false)]
[int]$RemotePort = 0,
[Parameter(Mandatory=$false)]
[string]$OutputDir = "."
)
Write-Host "`n>> Network diagnostics to ${RemoteIP}..." -ForegroundColor Magenta
$results = @{
Timestamp = (Get-Date).ToString("o")
RemoteIP = $RemoteIP
RemotePort = $RemotePort
Ping = @{}
Traceroute = @()
TcpConnection = @{}
}
# Ping test
try {
Write-Host " Running ping..." -ForegroundColor Yellow
$pingResults = Test-Connection -ComputerName $RemoteIP -Count 4 -ErrorAction Stop
$latencies = $pingResults | ForEach-Object { $_.Latency }
$results.Ping = @{
Sent = 4
Received = $pingResults.Count
Lost = 4 - $pingResults.Count
MinMs = ($latencies | Measure-Object -Minimum).Minimum
MaxMs = ($latencies | Measure-Object -Maximum).Maximum
AvgMs = ($latencies | Measure-Object -Average).Average
}
Write-Host " Ping: Avg=$([math]::Round($results.Ping.AvgMs,1))ms Min=$($results.Ping.MinMs)ms Max=$($results.Ping.MaxMs)ms" -ForegroundColor Green
}
catch {
Write-Warning "Ping fallito: $_"
$results.Ping = @{ Error = $_.Exception.Message }
}
# Traceroute (tracert)
try {
Write-Host " Running traceroute (may take ~30s)..." -ForegroundColor Yellow
$tracertOutput = & tracert -d -h 15 -w 2000 $RemoteIP 2>&1
$hops = @()
foreach ($line in $tracertOutput) {
if ($line -match '^\s*(\d+)\s+(.+)$') {
$hopNum = $Matches[1]
$hopData = $Matches[2].Trim()
# Parse latenze
$times = @()
if ($hopData -match '(\d+)\s*ms') {
$times = [regex]::Matches($hopData, '(\d+)\s*ms') | ForEach-Object { [int]$_.Groups[1].Value }
}
# Parse IP
$ip = ""
if ($hopData -match '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})') {
$ip = $Matches[1]
}
$hops += [pscustomobject]@{
Hop = [int]$hopNum
IP = $ip
Latencies = $times
AvgMs = if ($times.Count -gt 0) { ($times | Measure-Object -Average).Average } else { $null }
}
}
}
$results.Traceroute = $hops
Write-Host " Traceroute: $($hops.Count) hops detected" -ForegroundColor Green
}
catch {
Write-Warning "Traceroute fallito: $_"
$results.Traceroute = @()
}
# TCP connection test (if port specified)
if ($RemotePort -gt 0) {
try {
Write-Host " TCP connection test port ${RemotePort}..." -ForegroundColor Yellow
$tcpTest = Test-NetConnection -ComputerName $RemoteIP -Port $RemotePort -WarningAction SilentlyContinue -ErrorAction Stop
$results.TcpConnection = @{
Port = $RemotePort
Success = $tcpTest.TcpTestSucceeded
PingSuccess = $tcpTest.PingSucceeded
Latency = if ($tcpTest.PingReplyDetails) { $tcpTest.PingReplyDetails.RoundtripTime } else { $null }
}
if ($tcpTest.TcpTestSucceeded) {
Write-Host " TCP:$RemotePort connection successful" -ForegroundColor Green
} else {
Write-Host " TCP:$RemotePort connection failed (port may be UDP-only)" -ForegroundColor Yellow
}
}
catch {
Write-Warning "Test TCP fallito: $_"
$results.TcpConnection = @{ Error = $_.Exception.Message }
}
}
# Save diagnostics JSON
$diagFile = Join-Path $OutputDir "diagnostics_${RemoteIP}_$(Get-Date -Format 'yyyyMMdd_HHmmss').json"
$results | ConvertTo-Json -Depth 4 | Out-File -FilePath $diagFile -Encoding UTF8
Write-Host " Diagnostics saved: $diagFile" -ForegroundColor Yellow
return $diagFile
}
function Test-Bufferbloat {
<#
.SYNOPSIS
Test dedicato per misurare bufferbloat (latenza sotto carico)
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$RemoteIP,
[Parameter(Mandatory=$true)]
[string]$OutputDir
)
Write-Host "\n>> Bufferbloat Test" -ForegroundColor Magenta
Write-Host " This test measures latency increase under network load" -ForegroundColor Yellow
Write-Host " Duration: ~20 seconds" -ForegroundColor Yellow
# Preliminary check that server responds to ping
Write-Host " Checking server ICMP response..." -ForegroundColor Cyan
$testPing = Test-Connection -ComputerName $RemoteIP -Count 2 -ErrorAction SilentlyContinue
if (-not $testPing) {
Write-Warning "Server $RemoteIP does not respond to ICMP ping"
Write-Host " Many game servers block ping for security." -ForegroundColor Yellow
Write-Host " Bufferbloat test skipped. Use an alternative server (e.g., 8.8.8.8) for generic test." -ForegroundColor Yellow
return $null
}
$results = @{
TestType = "Bufferbloat"
TargetIP = $RemoteIP
BaselineRTT = $null
LoadedRTT = $null
LatencyIncrease = $null
Grade = $null
Timestamp = (Get-Date).ToString("o")
}
try {
# PHASE 1: Baseline (idle) - 10 ping
Write-Host " [1/3] Measuring baseline (idle)..." -ForegroundColor Cyan
$baselinePings = @()
for ($i = 1; $i -le 10; $i++) {
$ping = Test-Connection -ComputerName $RemoteIP -Count 1 -ErrorAction SilentlyContinue
if ($ping) {
# PowerShell 5.1 usa ResponseTime, PowerShell 7+ usa Latency
$latency = if ($ping.PSObject.Properties['Latency']) { $ping.Latency } else { $ping.ResponseTime }
$baselinePings += $latency
}
Start-Sleep -Milliseconds 200
}
if ($baselinePings.Count -lt 5) {
throw "Baseline ping failed: too many packets lost"
}
$baselineRTT = ($baselinePings | Measure-Object -Average).Average
$results.BaselineRTT = [math]::Round($baselineRTT, 2)
Write-Host " Baseline RTT: $($results.BaselineRTT)ms" -ForegroundColor Green
# PHASE 2: Generate load (simultaneous download + upload)
Write-Host " [2/3] Generating network load..." -ForegroundColor Cyan
# Start continuous ping in background
$pingJob = Start-Job -ScriptBlock {
param($ip)
$pings = @()
for ($i = 1; $i -le 40; $i++) {
$p = Test-Connection -ComputerName $ip -Count 1 -ErrorAction SilentlyContinue
if ($p) {
# PowerShell 5.1 vs 7.x compatibility
$latency = if ($p.PSObject.Properties['Latency']) { $p.Latency } else { $p.ResponseTime }
$pings += $latency
}
Start-Sleep -Milliseconds 250
}
return $pings
} -ArgumentList $RemoteIP
# Generate load with multiple downloads
Start-Sleep -Seconds 2 # Wait for ping stabilization
$loadJobs = @()
$testUrls = @(
"https://speed.cloudflare.com/__down?bytes=10000000",
"https://speed.cloudflare.com/__down?bytes=10000000",
"https://speed.cloudflare.com/__down?bytes=10000000"
)
foreach ($url in $testUrls) {
$loadJobs += Start-Job -ScriptBlock {
param($u)
try {
Invoke-WebRequest -Uri $u -Method GET -TimeoutSec 15 -UseBasicParsing | Out-Null
} catch {
# Ignora errori, serve solo per generare carico
}
} -ArgumentList $url
}
Write-Host " Carico attivo... attendere" -ForegroundColor Yellow
# Attendi completamento ping (10 secondi)
$pingResult = @(Wait-Job -Job $pingJob -Timeout 15 | Receive-Job)
Remove-Job -Job $pingJob -Force
# Termina job di carico
$loadJobs | Stop-Job
$loadJobs | Remove-Job -Force
# PHASE 3: RTT analysis under load
Write-Host " [3/3] Analyzing results..." -ForegroundColor Cyan
if (-not $pingResult -or $pingResult.Count -lt 10) {
throw "Loaded ping failed: too many packets lost ($($pingResult.Count) received)"
}
# Use only central 50% of pings (ignore first/last for stabilization)
$validPings = $pingResult | Select-Object -Skip 5 | Select-Object -First 20
$loadedRTT = ($validPings | Measure-Object -Average).Average
$results.LoadedRTT = [math]::Round($loadedRTT, 2)
$latencyIncrease = $loadedRTT - $baselineRTT
$results.LatencyIncrease = [math]::Round($latencyIncrease, 2)
# Grading bufferbloat
if ($latencyIncrease -le 10) {
$results.Grade = "A"
$interpretation = "Excellent - No significant bufferbloat"
$color = "Green"
}
elseif ($latencyIncrease -le 30) {
$results.Grade = "B"
$interpretation = "Good - Slight bufferbloat, acceptable for gaming"
$color = "Yellow"
}
elseif ($latencyIncrease -le 50) {
$results.Grade = "C"
$interpretation = "Moderate - Noticeable bufferbloat, possible lag under load"
$color = "Yellow"
}
else {
$results.Grade = "D"
$interpretation = "Severo - Bufferbloat critico, latenza instabile"
$color = "Red"
}
Write-Host "\n === RISULTATI BUFFERBLOAT ===" -ForegroundColor Cyan
Write-Host " Baseline RTT : $($results.BaselineRTT)ms" -ForegroundColor White
Write-Host " Loaded RTT : $($results.LoadedRTT)ms" -ForegroundColor White
Write-Host " Aumento Latenza : +$($results.LatencyIncrease)ms" -ForegroundColor $color
Write-Host " Grade : $($results.Grade)" -ForegroundColor $color
Write-Host " Interpretazione : $interpretation" -ForegroundColor $color
Write-Host ""
if ($latencyIncrease -gt 30) {
Write-Host " 💡 SUGGERIMENTO: Abilita SQM/QoS sul router o considera router con migliore QoS" -ForegroundColor Yellow
}
}
catch {
Write-Warning "Test bufferbloat fallito: $_"
$results.Error = $_.Exception.Message
}
# Salva risultati
$bufferbloatFile = Join-Path $OutputDir "bufferbloat_${RemoteIP}_$(Get-Date -Format 'yyyyMMdd_HHmmss').json"
$results | ConvertTo-Json -Depth 4 | Out-File -FilePath $bufferbloatFile -Encoding UTF8
Write-Host " Bufferbloat test saved: $bufferbloatFile" -ForegroundColor Yellow
return $bufferbloatFile
}
function Analyze-QUICFlow {
<#
.SYNOPSIS
Analyze QUIC traffic separately for specific patterns
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[array]$Packets,
[Parameter(Mandatory=$true)]
[string]$LocalIP,
[Parameter(Mandatory=$true)]
[string]$RemoteIP
)
Write-Host "\n>> Separate QUIC traffic analysis" -ForegroundColor Magenta
# Filtra solo pacchetti QUIC - force array con @()
$quicPkts = @($Packets | Where-Object {
$proto = $_.PSObject.Properties['_ws.col.Protocol'].Value
if (-not $proto) { $proto = $_.PSObject.Properties['_ws_col_Protocol'].Value }
$proto -match "QUIC"
})
if ($quicPkts.Count -lt 10) {
Write-Warning "Too few QUIC packets ($($quicPkts.Count)) for meaningful analysis"
return $null
}
Write-Verbose "Pacchetti QUIC totali: $($quicPkts.Count)"
# Filtra server -> client - force array con @()
$svrQuic = @($quicPkts | Where-Object {
$srcIP = if ($_.PSObject.Properties['ip.src']) { $_.'ip.src' } else { $_.'ip_src' }
$dstIP = if ($_.PSObject.Properties['ip.dst']) { $_.'ip.dst' } else { $_.'ip_dst' }
$srcIP -eq $RemoteIP -and $dstIP -eq $LocalIP
} | Sort-Object {
if ($_.PSObject.Properties['frame.time_epoch']) {
[double]$_.'frame.time_epoch'
} else {
[double]$_.'frame_time_epoch'
}
})
if ($svrQuic.Count -lt 5) {
Write-Warning "Troppi pochi pacchetti QUIC server->client"
return $null
}
Write-Host " Pacchetti QUIC server->client: $($svrQuic.Count)" -ForegroundColor Yellow
# Calcola metriche QUIC (simile a UDP)
$times = @()
$lens = @()
foreach ($p in $svrQuic) {
$timeVal = if ($p.PSObject.Properties['frame.time_epoch']) {
[double]$p.'frame.time_epoch'