Traceroute with starting TTLs

Tracing stuff with tracert or traceroute you can’t specify a starting TTL. So there will always be routers that show up and waste time.

This code is pretty rudimentary. Hopefully I’ll be able to expand on it to include ipv6 and make it faster.

param(
    $targetIP,
    $BeginHop = 1,
    $EndHop = 30,
    $timeout = 1000,
    [switch]$GetHostname
)

$addrtype = [System.Net.Sockets.AddressFamily]::InterNetwork;
if($v6.ispresent) {
    $addrtype = [System.Net.Sockets.AddressFamily]::InterNetworkV6;
}

$targetIPActual = $null;
if(![net.ipaddress]::TryParse($targetIP, [ref]$targetIPActual)) {
    $target = [net.dns]::GetHostEntry($targetIP);
    $targetIPActual = $target.addresslist | where {$_.addressfamily -eq $addrtype} | select -First 1
} else {
    $target = New-Object psobject -Property @{"HostName" = $targetIP.tostring()}
}

for($i = $BeginHop; $i -lt $EndHop; $i++) {
    
    $ping = new-object System.Net.NetworkInformation.ping;
    $pingo = new-object System.Net.NetworkInformation.PingOptions $i, $true;
    $sendbytes = @([byte][char]'a'..[byte][char]'z');
    $pr = $ping.Send($targetIPActual, $timeout, $sendbytes, $pingo);
    try {
        $rtn = New-Object psobject -Property @{
            "IP" = $pr.Address;
            "RoundtripTime" = $pr.RoundtripTime;
            "Status" = $pr.Status;
        }
    } catch {
        $rtn = New-Object psobject -Property @{
            "IP" = "*";
            "RoundtripTime" = $pr.RoundtripTime;
            "Status" = $pr.Status;
        }
    }
    
    try {
        if($GetHostname.ispresent) {
            Add-Member -InputObject $rtn -MemberType NoteProperty -Name Hostname -Value ([net.dns]::GetHostEntry($pr.Address).hostname)
        }
    } catch{}
    
    $rtn;
    
    #$pr
    try { 
        if($pr.Address.tostring() -eq $targetIPActual) { break; }
    } catch{}
}

Comments

2 responses to “Traceroute with starting TTLs”

Leave your response
  1. Gilles says:

    Excellent et très efficace, bien mieux que le tracert d’origine. merci