Как находить проблемы с интернетом и кто виноват ч.2

Оглавление

Другие команды

Команда tracert позволяет проследить путь пакетов от вашего компьютера до цели. Попробуйте, например протрассировать путь до этого сайта: tracert it.sander.su. Строки в выводе трассировки есть точки, через которые проходит пакет на своем пути. Первой точкой будет ваш шлюз. Использование команды tracert позволяет найти источник проблем при связи с каким-либо адресом. Пакеты, посылаемые командой tracert, имеют показатель TTL — time to live — целое положительное число. Каждый маршрутизатор на пути уменьшает этот показатель на 1, если TTL падает до нуля, то трассировка заканчивается. По умолчанию используется начальный TTL равный 30, задать другое значение можно опцией -h.

Посмотреть таблицу маршрутизации можно командой route print, однако я не буду подробно останавливаться на ней — это тема отдельной статьи.

Команда netstat позволяет просмотреть список установленных соединений. В режиме по умолчанию команда пытается преобразовывать все IP-адреса в доманные имена (при помощи службы DNS), что может работать медленно. Если вас устраивает числовой вывод, вызывайте команду netstat -n. Если вас также интересуют открытые порты на вашем компьютере (что означает, что он готов принимать соединения по этим портам), то вызовите команду с ключом -a: например, netstat -na. Можно также вызвать команду netstat -nb, чтобы посмотреть, какие процессы установили соединения. Команда netstat -r эквивалентна команде route print.

Команда netsh позволяет изменить настройки сети через командную строку. Введите команду netsh interface ip show address. У меня получилось:

C:\Documents and Settings\Администратор>ipconfig /all

Настройка интерфейса «Ethernet»

            DHCP разрешен: да

            Метрика интерфейса: 0

← Настройка параметров сети Скорость интернета →

Analyzing Tracert Results

Round Trip Times (RTT)

  • RTT (latency) is the main thing you want to focus on in your tracert report. For these values, the lower the number, the better. You also want to see fairly consistent times for each hop.
  • RTT above 150ms within the United States is considered to be long, but may be normal if the remote device is in the opposite side of the world.
  • If an asterisk (*) appears for RTT instead of a time, this indicates that the packet was not received back within the expected time frame. For Windows tracert, the default is 4,000 milliseconds (or 4 seconds). This parameter can be increased by using the switch if necessary. Seeing one or two asterisks does not necessarily indicate a problem. Routers can be configured to limit the number of ping or tracert packets it responses to as a way to prevent them from being affected by denial-of-service attacks.
  • If there are three asterisks followed by a Request Timed Out message, there can be a few reasons for this:
    • If this appears at the beginning of a tracert report, it can be ignored as it is often due to the device configured to not respond to ping and tracert packets.
    • If this appears toward the end of a tracert report, it can indicate one of the following:
      • Firewall — A security device (such as a firewall) at the destination network is blocking the request. However, this does not mean the destination device is not reachable (such as a web server). This only indicates that a security device is configured to not response to ping or tracert packets.
      • Problem with Return Path — As mentioned, RTT measures the round trip time a packet traverse from your computer to the router and back. The pathway to the hop is often not going to be same for the return trip.
      • Problem with Remote Device — The remote device is not configured correctly or has system problems affecting your connection.
  • A progressively increase in latency to the remote device can indicate an issue starting with the hop where the sudden increase began.
  • A high latency in the middle of your tracert report does not necessarily indicate a problem as the associated router may have be configured to respond to ping and tracert packets with low priority.
  • A high latency at the beginning of a tracert report (the first two hops) may indicate issues with your local network or Internet Service Provider (ISP). To resolve, contact the I.T. department of your organization or your ISP.

Traceroute Command Syntax and Options (for Windows)

The tracert (for windows) command is available at the Command Prompt in all Windows operating systems including Windows 10, Windows 8, Windows 7, Windows XP, Windows Vista, and older versions of Windows as well.

The tracert command syntax is given below:

tracert       target 

Below is a brief description with each tracert option in Windows…

Option Description
-d This tracert option prevents tracert from resolving IP addresses to hostnames, often resulting in much faster results.
-h MaxHops This option specifies the maximum number of hops in the search for the target. If you do not specify MaxHops, and a target has not been found by the default max hops (30 for Windows), tracert will stop looking.
-w TimeOut Using this tracert option, you can specify the time, in milliseconds, to allow each reply before timeout.
-4 It forces tracert to use IPv4 only.
-6 It forces tracert to use IPv6 only.
Target A mandatory option. It is used to specify the destination, either an IP address or hostname.
/? Use the help switch with the tracert command to show detailed help about the command’s multiple options.

What is Traceroute?

Traceroute is a monitoring command commonly used by network and system administrators in their day-to-day operations.

This basic network diagnostic tool has three primary objectives, which give you an accurate and complete understanding of a network problem.

With Traceroute, you can?

  1. Get the complete path that a packet uses to reach its destination.
  2. Discover the names and identity of routers and devices within the path.
  3. Find the time it took to send and receive data to each device on the path.

Traceroute gives you complete information about the path that your data will take to reach its destination, without actually sending data (other than ICMP).

For example, if the source of the path (your computer) is in Boston, Massachusetts and the destination in San Jose, California (a Server), Traceroute will identify the complete path, each hop (the computers, routers, or any devices that comes in between the source and the destination) on the path, and the time it takes to go and come back.

List Of Available Methods

In general, a particular traceroute method may have to be chosen by -M name, but most of the methods have their simple cmdline switches (you can see
them after the method name, if present).

default

The traditional, ancient method of tracerouting. Used by default.

Probe packets are udp datagrams with so-called «unlikely» destination ports. The «unlikely» port of the first probe is 33434, then for each next probe it is
incremented by one. Since the ports are expected to be unused, the destination host normally returns «icmp unreach port» as a final response. (Nobody knows
what happens when some application listens for such ports, though).

This method is allowed for unprivileged users.

icmp -I

Most usual method for now, which uses icmp echo packets for probes.
If you can ping(8) the destination host, icmp tracerouting is applicable as well.

tcp -T

Well-known modern method, intended to bypass firewalls.
Uses the constant destination port (default is 80, http).

If some filters are present in the network path, then most probably any «unlikely» udp ports (as for default method) or even icmp echoes (as for
icmp) are filtered, and whole tracerouting will just stop at such a firewall. To bypass a network filter, we have to use only allowed protocol/port
combinations. If we trace for some, say, mailserver, then more likely -T -p 25 can reach it, even when -I can not.

This method uses well-known «half-open technique», which prevents applications on the destination host from seeing our probes at all. Normally, a tcp syn is
sent. For non-listened ports we receive tcp reset, and all is done. For active listening ports we receive tcp syn+ack, but answer by tcp reset (instead of
expected tcp ack), this way the remote tcp session is dropped even without the application ever taking notice.

There is a couple of options for tcp method:

syn,ack,fin,rst,psh,urg,ece,cwr

Sets specified tcp flags for probe packet, in any combination.

flags=num

Sets the flags field in the tcp header exactly to num.

ecn

Send syn packet with tcp flags ECE and CWR (for Explicit Congestion Notification, rfc3168)

sack,timestamps,window_scaling

Use the corresponding tcp header option in the outgoing probe packet.

sysctl

Use current sysctl (/proc/sys/net/*) setting for the tcp header options above and ecn. Always set by default, if nothing else
specified.

mss=num

Use value of num for maxseg tcp header option (when syn).

Default options is syn,sysctl.

tcpconn

An initial implementation of tcp method, simple using connect(2) call, which does full tcp session opening. Not recommended for normal use, because a
destination application is always affected (and can be confused).

udp -U

Use udp datagram with constant destination port (default 53, dns).
Intended to bypass firewall as well.

Note, that unlike in tcp method, the correspond application on the destination host always receive our probes (with random data), and most can
easily be confused by them. Most cases it will not respond to our packets though, so we will never see the final hop in the trace. (Fortunately, it seems that
at least dns servers replies with something angry).

This method is allowed for unprivileged users.

udplite -UL

Use udplite datagram for probes (with constant destination port, default 53).

This method is allowed for unprivileged users.
Options:

coverage=num

Set udplite send coverage to num.

raw -P proto

Send raw packet of protocol proto.
No protocol-specific headers are used, just IP header only.
Implies -N 1.
Options:
protocol=proto
Use IP protocol proto (default 253).

What is Traceroute?

Traceroute is a monitoring command commonly used by network and system administrators in their day-to-day operations.

This basic network diagnostic tool has three primary objectives, which give you an accurate and complete understanding of a network problem.

With Traceroute, you can?

  1. Get the complete path that a packet uses to reach its destination.
  2. Discover the names and identity of routers and devices within the path.
  3. Find the time it took to send and receive data to each device on the path.

Traceroute gives you complete information about the path that your data will take to reach its destination, without actually sending data (other than ICMP).

For example, if the source of the path (your computer) is in Boston, Massachusetts and the destination in San Jose, California (a Server), Traceroute will identify the complete path, each hop (the computers, routers, or any devices that comes in between the source and the destination) on the path, and the time it takes to go and come back.

Traceroute Command

Let’s see this in action. I will use the following topology for this demonstration:

Above we have two host computers. H1 is a Windows computer (192.168.1.1) and H2 a Linux computer (192.168.1.2) running Ubuntu. The routers have been configured with EIGRP so that we have full connectivity.

Windows

Let’s start with a windows trace:

Above we see all routers and the destination. For each hop, traceroute will send three IP packets. We do this to get a good average of the round trip time for each hop. Let’s see what the IP packets look like in Wireshark. Here’s the first one:

Above we see the first IP packet with a TTL of one. We can see that this is an ICMP request. When R1 receives this IP packet, it will respond like this:

Above we see that R1 responds with a TTL expired message to S1. In the capture file, you will see the two packets above three times. Let’s look at the next IP packet:

This one has a TTL of two which will make it to R2:

And the third packet with a TTL of three:

R3 will respond to it with a TTL exceeded message:

Finally, the last IP packet with a TTL of four will be sent by H1:

This one finally makes it to S1 so we get an ICMP reply:

That’s how traceroute works on Windows. You can take a look at the capture file yourself if you want:

Linux

The traceroute commands on Linux works similar to Windows. One important difference is that it doesn’t use ICMP but UDP. It also allows you to specify the number of IP packets (probes) you want to send. To create a nice clean wireshark capture, I configured it to send only one probe for each hop:

Here’s what this traceroute looks like in Wireshark:

Above we can see that H2 is sending UDP packets instead of ICMP requests. Let’s take a closer look at these packets. Here’s the first one:

Above we see that H2 is sending the first IP packet with a TTL of one. We see we use UDP and the destination port number is 33434. R1 will reply to this:

Since the TTL is zero, R1 drops it and replies with a TTL exceeded message. Time for the second IP packet with a TTL of two:

The packet above is the same as the first one except you can see that the destination port number has increased from 33434 to 33435. R2 will drop this:

Time for packet with a TTL of three:

Above you can see the destination port number has increased from 33435 to 33436. R3 will drop this:

The last packet will have a TTL of four and a destination port number of 33437:

This one will make it all the way to S1. Since S1 is not listening on any of these UDP port numbers, it will reply that the destination / port is unreachable:

This tells H2 that we made it to the destination.

The linux traceroute command has a lot of options. It also allows you to use ICMP or TCP for traceroute.

Cisco IOS

We can also use the traceroute command on Cisco IOS. Like Linux, Cisco uses UDP for traceroute. Let’s do a trace from R1 to S1, I will use a single probe:

Above we see that this trace makes it to the destination.

Traceroute on Cisco IOS might be very slow. This is because it will attempt a DNS lookup for each IP address. To make it faster, make sure these lookups can be resolved or disable DNS lookups with the no ip domain-lookup command.

Here’s what the capture looks like in Wireshark:

This capture is the same as the Linux capture we just looked at so I won’t add the screenshots again. You will find the capture file at the end of this lesson if you want to see it for yourself.

Let’s look at some of the options of the traceroute command instead:

We can choose if we want to trace an IP address or a hostname. If you don’t specify anything, then you can choose some parameters that you want to use:

You can also add these parameters behind the IP address, like this:

Like I did when I specified the number of probes:

If you want to cancel traceroute, hit SHIFT+CTRL+6, let go then press X.

Here you can find the capture file if you want to see it for yourself:

Как сделать трассировку?

Для этого вам понадобится служебная программа (утилита) traceroute. Принцип ее действия прост: программа посылает в проблемном направлении информационный сигнал – пакет данных, получая ответ от каждого из узлов – своеобразное информационное эхо. Таким образом, можно замерить время прохождения сигнала от одного узла к другому, без труда выявив «слабое звено».

Не нужно бросаться искать, где бы скачать такую полезную вещь: утилита traceroute уже встроена в вашу операционную систему. Для ее запуска служит команда tracert. Итак, что вам необходимо сделать:

  1. Вызываем командную строку. Для этого:
    • Нажимаем кнопку пуск на экране либо клавишу win на клавиатуре (клавиша win на стандартной клавиатуре находится между Alt и Control, на ней изображен всемирно известный логотип всеми любимой операционной системы Windows);
    • В появившемся меню (стартовом меню) выбираем пункт «выполнить». Команда «выполнить» позволяет задействовать служебные программы системы Windows, спрятанные подальше от рук любопытных пользователей, так как неумелое пользование некоторыми программами может нанести вред работе операционной системе и хранящимся на компьютере данным. Своего рода «защита от дурака». Но мы уж точно не дураки, поэтому продолжаем;
    • В появившейся после выбора «выполнить» строке вводим вручную латинским шрифтом cmd и нажимаем Ok. Командная строка вызвана.

Справка: быстро вызвать строку «выполнить» можно нажав на клавиатуре комбинацию win+r. После чего можно ввести cmd.

  1. В командную строку вводим команду tracert имя или IP сайта (с подсоединением к которому возникли проблемы). Например, tracert ru.
  2. Ожидаем результат. В результате мы увидим несколько строк (до 30), каждая из которых – узел, через который проходит информация. В строке будет написано имя или IP узла и время прохождения сигнала в миллисекундах (ms – тысячная доля секунды).

Выше описанное актуально для операционной системы Windows, а как выполняется трассировка маршрута под Linux? В общих чертах аналогично, только терминал (аналог командной строки) вместо cmd вызывается сочетанием клавиш Ctrl+Alt+t, а вместо tracert вводим traceroute. Стоит также отметить, что трассировка в Linux будет продолжаться, пока пользователь не прервет ее сам, нажав ctrl+c.

Что нам даст результат? Чем больше время прохождения пакета, тем больше сайт «тормозит», таким образом, мы выявим узел, виновный в «тормозах». Непроходимый же узел будет обозначен надписью «Превышен интервал ожидания маршрута». Чем выше в списке проблемная строка, тем более локальна проблема. «Непроходимость» внизу списка указывает на проблемы с сайтом или доменом, а вверху – у вашего провайдера либо в локальной сети.

Трассировка маршрута

Использование утилиты «Tracert».

Рассмотрим пример работы программы в операционной системе Windоws. Программа tracert выполняет отправку данных указанному узлу сети, при этом отображая сведения о всех промежуточных маршрутизаторах, через которые прошли данные на пути к целевому узлу. В случае проблем при доставке данных до какого-либо узла программа позволяет определить, на каком именно участке сети возникли неполадки. Здесь хочется отметить, что программа работает только в направлении от источника пакетов и является весьма грубым инструментом для выявления неполадок в сети. В силу особенностей работы протоколов маршрутизации в сети Интернет, обратные маршруты часто не совпадают с прямыми, причем это справедливо для всех промежуточных узлов в трейсе. Поэтому ICMP ответ от каждого промежуточного узла может идти своим собственным маршрутом, затеряться или прийти с большой задержкой, хотя в реальности с пакетами, которые адресованы конечному узлу, этого не происходит. Кроме того, на промежуточных маршрутизаторах часто стоит ограничение числа ответов ICMP в единицу времени, что приводит к появлению ложных потерь.
Запуск программы производится из командной строки. Для этого вы должны войти в неё. Для операционных систем семейства Windows существует несколько способов запуска командной строки:

1. Пуск — Выполнить — В графе «Открыть» написать «cmd» и нажать Ок.

2. Сочетание клавиш Win (кнопка с логотипом Windows) + R (должны быть нажаты одновременно) — В графе «Открыть» написать «cmd» и нажать Ок.

3. Пуск — Все программы (или просто «Программы», зависит от версии операционной системы) — Стандартные — Командная строка.

Далее вам необходимо произвести трассировку до заданного ip адреса или доменного имени.

Использование утилиты «Pathping

PathPing предоставляет информацию о латентности сети и потерях данных на промежуточных узлах между исходным пунктом и пунктом назначения. Команда pathping в течение некоторого периода времени отправляет многочисленные сообщения с эхо-запросом каждому маршрутизатору, находящемуся между исходным пунктом и пунктом назначения, а затем на основании пакетов, полученных от каждого из них, вычисляет результаты. Поскольку pathping показывает коэффициент потери пакетов для каждого маршрутизатора или связи, можно определить маршрутизаторы или подсети, имеющие проблемы с сетью. Команда pathping выполняет эквивалентное команде tracert действие, идентифицируя маршрутизаторы, находящиеся на пути.

Запуск программы производится из командной строки. Для этого вы должны войти в неё. Для операционных систем семейства Windows существует несколько способов запуска командной строки:

1. Пуск — Выполнить — В графе «Открыть» написать «cmd» и нажать Ок.

2. Сочетание клавиш Win (кнопка с логотипом Windows) + R (должны быть нажаты одновременно) — В графе «Открыть» написать «cmd» и нажать Ок.

3. Пуск — Все программы (или просто «Программы», зависит от версии операционной системы) — Стандартные — Командная

Внимание! Выполнение данной команды потребует некоторое время, необходимо дождаться полного выполнения, как указано в примере ниже

Копирование текста из командной строки.

Чтобы скопировать текст к кликаем правой кнопкой мышки по командной строке и вызываем контекстное меню. В открывшемся меню выбираем пункт «Пометить». После этого текст в командной строке можно выделить обычным движением мышкой и скопировать с помощь комбинации клавиш Ctrl+C.

Далее результаты необходимо будет переслать на электронный адрес почты 911@profintel.ru, с указанием вашего id номера и кратким описанием вашей проблемы.

Синтаксис и основные ключи утилиты route

Теперь поговорим поподробней о команде route.

Общий синтаксис:

route

Основные ключи:

  • -f — удаляет из таблицы маршрутизации все маршруты;
  • -p – сохраняет маршрут на постоянную основу;
  • add – добавляет новый маршрут;
  • change — меняет текущий маршрут в таблице маршрутизации;
  • delete — удаляет маршрут из таблицы маршрутизации;
  • print — отображает содержимое таблицы маршрутизации;
  • destination — при добавлении или изменении маршрута этот параметр используется для указания идентификатора сети назначения;
  • mask — при добавлении или изменении маршрута этот параметр используется для указания маски подсети для сети назначения;
  • gateway — при добавлении или изменении нового маршрута этот параметр используется для указания шлюза (маршрутизатора или модема);
  • metric — используется для указания целого числа в диапазоне от 1 до 9999, являющегося метрикой стоимости для маршрута. Если для определенной сети назначения существует несколько возможных маршрутов, будет использован маршрут с наименьшим значением метрики;
  • if — используется для указания номера индекса интерфейса, который подключен к сети назначения.

Для того чтобы просто посмотреть таблицу маршрутизации у себя на компьютере введите в командную строку следующие:

route print

Вот в принципе и все что я хотел Вам рассказать, но следует помнить что, проводя все выше указанные манипуляции нужно быть внимательным, так как ошибка всего в одной цифре приведет к нежелательным результатам, не критичным, но нежелательным. В особенности это относится к корпоративным сетям, где маршрутизация уже настроена, и Вы можете легко изменить, удалить нужные маршруты.

Traceroute Test FAQ

Using the Traceroute Tool

This tool is typically used to diagnose hiccups or interruptions in the transfer of data and pinpoint where along the chain it occurred. This IPv4 or IPv6 traceroute is unique in that it allows you to simultaneously test different locations at once. This lets you quickly determine if there is any packet loss or unexpected latency to the given IP or hostname. A CDN can help dramatically reduce latency by minimizing the distance between hops.

What is Traceroute?

Traceroute, also called tracert, is a utility that uses ICMP packets to record the route through the internet from one computer to another. It calculates the time taken for each hop as the packet is routed to the destination. To guarantee accuracy, each hop is queried multiple times (in this case four times) to better measure the response of that particular hop.

Синтаксис команды Tracert

ЬгасегЬ -d -час MaxHops -w TimeOut -4 -6 цель /?

Совет: См. «Как прочитать командный синтаксис», если вам трудно понять синтаксис tracert, описанный выше или в приведенной ниже таблице.

-d Эта опция запрещает трассировать от разрешения IP-адресов на имена хостов, что часто приводит к гораздо более быстрым результатам.
-час MaxHops Этот параметр tracert указывает максимальное количество переходов в поиске цель , Если вы не указали MaxHops , и цель не был найден 30 прыжками, tracert перестанет смотреть.
-w TimeOut Вы можете указать время в миллисекундах, чтобы разрешить каждый ответ до таймаута, используя этот параметр tracert.
-4 Этот параметр заставляет tracert использовать только IPv4.
-6 Этот параметр заставляет tracert использовать только IPv6.
цель Это назначение, либо IP-адрес, либо имя хоста.
/? Используйте переключатель справки с помощью команды tracert, чтобы показать подробную справку о нескольких параметрах команды.

Другие менее часто используемые параметры для команды tracert также существуют, в том числе -j Список_адресов , -Р, а также -S Адрес источника . Для получения дополнительной информации об этих параметрах используйте ключ справки с помощью команды tracert.

Совет: Сохраните длинные результаты команды tracert в файл с помощью оператора перенаправления. Посмотрите, как перенаправить вывод команды в файл или получить подсказки командной строки для этого и других полезных советов.

Advanced information

This tool is based on Linux open-source utilities traceroute.

This graphical traceroute implementation is set up to track the path of an IP packet to a maximum of 30 hops. These raw ICMP echoes are in the form of ECHO_REQUEST datagrams, eliciting an ICMP TIME_EXCEEDED response from the last hop on the complete trip of a probing packet. The program will wait no more than 2 s before timing out waiting for such TIME_EXCEEDED response packets.

As UDP and TCP-type packets are more commonly blocked or throttled by modern devices or routers, this ping test provides a maximum guaranteed network penetration by using the ICMP protocol.

Are there alternatives to the traceroute command?

Yes, there are various alternatives to the traceroute commands like MTR command, Dig command, Open Visual Traceroute, Nmap.

MTR command (Linux and macOS)

mtr domain.com

The MTR command is an improved traceroute command that can give more statistics and data for lost packets (percentage).

Dig command (Linux and macOS)

dig +trace domain.com

If you already use the Dig command, you can use it for tracing the route too.

Open Visual Traceroute (Linux, macOS, and Windows)

This one is for people who want a visual interface. It is heavier, but it can show you, in a graphical way, the route of the queries and also get Gantt graphs.

Nmap (Linux, macOS, Windows, BSD, and more)

nmap –traceroute domain.com

The results are very similar to the traceroute command.