Пропингуйте IP-порт через командную строку

Пропингуйте IP-порт через командную строку Хостинг

Тематические термины: Ping, Windows, Linux.

Мы рассмотрим использование команды ping для Windows и, немного, для Linux.

Содержание
  1. Параметры команды ping и их описание
  2. Общий синтаксис
  3. Windows
  4. Linux
  5. Примеры использования
  6. Открытие порта для Ping
  7. Проверка портов
  8. Ping IP and port using Telnet
  9. Install Telnet on Linux
  10. Install Telnet on Windows
  11. Ping IP and port with Telnet example
  12. Ping IP and port using Nmap
  13. Install Nmap on Linux
  14. Install Nmap on Windows
  15. Ping IP and port using Nmap
  16. Ping IP and port using PowerShell
  17. Summary
  18. Ping Specific Port with telnet Command
  19. Ping Specific Port with nc (netcat) Command
  20. Ping Specific Port with nmap
  21. Ping Specific Port with Test-Connection In PowerShell
  22. Ping Port with PaPing Tool
  23. Ping Port with curl Command
  24. Ping Port with psping Command
  25. Ping and ICMP Protocol
  26. Ping Uses ICMP Type 8 and Type 0
  27. Ping Packet Content
  28. Is Port 7 Used For Ping ICMP?
  29. Alternative Way Ping TCP Ports
  30. Can You Ping a Specific Port?
  31. Ping a Specific Port Using Telnet
  32. Ping a Specific Port Using Netcat
  33. Ping a Specific Port Using Nmap
  34. How to Ping a Specific Port in Windows?
  35. Ping a Port Using Telnet
  36. Ping a Port Using PowerShell
  37. Что такое пинг в Интернете
  38. От чего зависит пинг сайта
  39. Что делает команда ping
  40. Команда ping в Windows и Linux
  41. Как проверить пинг через командную строку
  42. Как снизить пинг
  43. Программы для снижения пинга
  44. Заключение
  45. TNSPING Utility
  46. TNSPING Usages
  47. 1. Connect Identifier
  48. Single Testing
  49. Multiple Testing
  50. 2. IP Address or Hostname
  51. IP Address Only
  52. With Port Number
  53. Service Name Added
  54. Hostname
  55. 3. Connection Description
  56. Errors Related to TNSPING

Параметры команды ping и их описание

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

Читайте также:  Лучшие хостинг Бразилия - Популярные хостинговые компании Бразилия статистика

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

Независимо от системы, команду ping можно применять так:

Windows

Для просмотра в Windows также используйте команду ping /?

Linux

При минимальной инсталляциии данной системы или использовании docker, утилиты ping может не быть. В таком случае мы увидим ошибку:

bash: ping: command not found

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

а) для систем на базе deb (Debian, Ubuntu, Mint):

apt install iputils-ping

б) для систем на базе RPM (Rocky Linux, CentOS, Red Hat, Fedora):

yum install iputils

Готово, теперь можно пользоваться командой ping.

Список ключей можно посмотреть так:

Примеры использования

Простой пример использования команды ping

Примерный ответ с исправной связью:

Пример ответа, если узел недоступен:

* до удаленного узла нет сигнала. Возможно, существуют неполадки на сети.

При проверке связи не удалось обнаружить узел
Проверьте имя узла и повторите попытку.

* не удалось определить имя узла. Возможные неполадки: нет связи с DNS, не работает DNS, запрашиваемого имени узла не существует.

В Linux при отсутствии ответа, мы ничего не увидим, но если нам нужно видеть неудачные попытки, то используем ping с опцией -O:

Открытие порта для Ping

Справедливо заметить, что не во всех случаях отсутствие ответа на ping означает, что удаленный узел недоступен. Администратор ресурса может намеренно отключить ответы на эхо-запросы.

Также важно знать, что ping не использует конкретный номер порта. Чтобы открыть возможность пинга, необходимо либо найти соответствующую опцию (во многих домашних роутерах) или разрешить ICMP (Internet Control Message Protocol) на брандмауэре. Ну, или наоборот — чтобы закрыть возможность пинга, блокируем запросы ICMP.

Проверка портов

С помощью команды ping нельзя проверить открытость того или иного порта.

Читайте также:  Gitlab com на русском

Для этих целей используется команда telnet или программа, например, nmap.

Дмитрий Моск — частный мастер

Была ли полезна вам эта инструкция?

One of the things I do the most when troubleshooting deployments of services exposing data to the internet is pinging the IP and port where the service is supposed to be alive. In this tutorial, I will show you how to ping IP and port on Linux and Windows.

Often it’s enough to just ping an IP to validate that you got “life” on the server. However if you like me often got many services running on one server (often when using Docker), I need to ping the specific port number on the server. One of the Kubernetes clusters I manage is running more than 100 services and here I use it a lot.

In this article/reference post, I will show you how to ping IP and port on your Windows or Linux machine using different commands in the terminal (CLI).

Ping IP and port using Telnet

This is my favorite when working on both Windows and Linux. I also think that it’s the easiest one to use and it’s called Telnet. You can with a simple command using Telnet ping IP and port on the remote server you would like to check.

Telnet — Wikipedia

Пропингуйте IP-порт через командную строкуWikimedia Foundation, Inc.Contributors to Wikimedia projects

Пропингуйте IP-порт через командную строку

If you want to, you can also use a domain instead of the IP. A domain is often easier for humans to remember instead of numbers to multiple different servers locally or externally.

Below are the commands to ping IP and port on a server using Telnet:

$ telnet <server_ip_address> <server_port_number>
$ telnet <server_domain_name> <server_port_number>

As I mentioned above, you can use Telnet on both Windows and Linux computers/servers which makes it a great choice for most sys-ops.

On most computers, telnet is not installed by default. If you get the annoying error “telnet: command not found”, you have to install Telnet on the machine using the commands below:

Install Telnet on Linux

If you are working on a Linux Server or Desktop, you can use the below command to install Telnet on that machine:

$ sudo apt install telnet

Install Telnet on Windows

  1. Click on Start.
  2. Select Control Panel.
  3. Choose Programs and Features.
  4. Click Turn Windows features on or off.
  5. Select the Telnet Client option.
  6. Click OK.
    A dialog box appears to confirm installation when it’s done. The telnet command should now be available in your Command Prompt. Remember to restart your CMD window.

Ping IP and port with Telnet example

Let’s check out how Telnet works. This website is running at IP: 172.67.161.26 – this is the public IP address of the website to which the domain is mapped to.

By default, all requests are redirected to HTTPS (port 443) if a request is made at port 80. This means that the server accepts connections on port 80 too – let’s try and ping both ports:

$ telnet 172.67.161.26 80
Trying 172.67.161.26...
Connected to 172.67.161.26.
Escape character is '^]'.
$ telnet 172.67.161.26 443
Trying 172.67.161.26...
Connected to 172.67.161.26.
Escape character is '^]'.

That went well. We got connected and could see that the server is responding on both ports. This simply means that the service on the port is up and running.

Ping IP and port using Nmap

Another well-used tool is Nmap. In Nmap, you can ping a port by using the “-p” option including the IP or domain you would like to scan.

Nmap: the Network Mapper — Free Security Scanner

Nmap Free Security Scanner, Port Scanner, & Network Exploration Tool. Download open source software for Linux, Windows, UNIX, FreeBSD, etc.

Пропингуйте IP-порт через командную строкуFree Security Scanner

Пропингуйте IP-порт через командную строку

$ nmap -p <server_port_number> <server_ip_address>
$ nmap -p <server_port_number> <internet_domain_name>

A heads up – be aware of legal issues!

“When used properly, Nmap helps protect your network from invaders. But when used improperly, Nmap can (in rare cases) get you sued, fired, expelled, jailed, or banned by your ISP.” – Nmap website.

If you get an error telling you that Nmap is not available on your computer/server, you would have to install it.

Install Nmap on Linux

To install Nmap on your Linux machine, you can use the below command:

$ sudo apt install nmap

Install Nmap on Windows

Not as simple as Linux, but it’s still easy to use the official installer from Nmap’s website. Go to this page: Download Nmap and look under the Windows Binaries for the latest available installer file.

Once the installer has completed installing, you are now ready to use Nmap on your Windows computer.

Ping IP and port using Nmap

C:\Users\christian>nmap -p 443 172.67.161.26
Starting Nmap 7.92 ( https://nmap.org ) at 2022-02-10 06:50 Romance Standard Time
Nmap scan report for 172.67.161.26
Host is up (0.028s latency).

Well, once again the port is returned as open on the server. This means that there is a service accepting data at port 443, which was just verified by Nmap.

Ping IP and port using PowerShell

Normally when I’m not on my own machines, which means I’m working on production servers not related to my own business/platform and it’s a Windows Server Environment, I always use PowerShell to ping IP and port.

A great thing about PowerShell is that you can use the methods in scripts running automated stuff in the background or during the setup of service or multiple services. A great thing if deploying with PowerShell would be to check if the ports were active after deployment and return a status to the terminal.

PS C:\Users\christian> Test-NetConnection <server_ip_address> -p <server_port_number>

Below is an example of what this would look like on a local network:

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved. PS C:\Users\christian> Test-NetConnection 192.168.1.1 -p 80 ComputerName : 192.168.1.1
RemoteAddress : 192.168.1.1
RemotePort : 80
InterfaceAlias : Wi-Fi
SourceAddress : 192.168.1.68
TcpTestSucceeded : True

In the test above you can see that the TCP call to my gateway at home succeeded at port 80. If you can’t get through to the service you will status False in TcpTestSucceeded.

Summary

In this quick article on how to ping IP and port using different tools on Windows or Linux machines, we learned how we can use the terminal to check if a given port is open and accepting requests.

If you got any issues, questions, or suggestions, please let me know in the comments below. Happy pinging!

Christian Schou

A ping is a tool and command used to troubleshoot network and system-related problems. The ping command normally uses the ICMP protocol and make checks if the remote system is up or down without a TCP or UDP. The ping port is a term used to check a remote port which can be TCP or UDP if it is open and accessible. There are different tools that can be used to ping a TCP or UDP port. Telnet, nmap, putty, netcat,psping are some of them.

  • The application can not connect database service.
  • If the firewall has configured properly to allow or deny specific ports.
  • Check if the remote SNMP service is running properly.
  • Before attacking the remote port if the port is up and responding properly.

Ping Specific Port with telnet Command

The most popular and basic tool to ping a remote port is the telnet command. Telnet is a tool and protocol created to connect remote systems via the command line. Telnet work from the command line and provides simple access to the remote telnet server. Telnet command uses the TCP protocol and first tries to connect remote port which is very useful to check remote port.

By default, telnet is not installed for both Linux and Windows systems. In Linux systems like Ubuntu, Debian, Mint, Kali you can install the telnet command like below.

$ sudo apt install telnet

Alternatively, you can use 3rd party tools like Putty for telnet command but it is not practical as expected. Syntax of the telnet command to ping the remote port is like below. The telnet command only uses the TCP protocol which is the most popular transmission protocol. So only TCP ports can be pinged with the telnet command which can not be used for the UDP ports.

telnet IP PORT
telnet DOMAIN PORT
  • IP or DOMAIN is used to specify the remote system.
  • PORT is the remote system port number which is a number from 9 to 65000.

Let’s ping the remote HTTP port with the telnet command by providing the port number as 80. We will ping the google.com TCP port number 80 like below.

$ telnet google.com 80

The output will be like below where the telnet will try to connect remote system port number 80 and when the connection is established e will see the message “Connected to google.com.

Trying 172.217.18.110...
Connected to google.com.
Escape character is '^]'.
get /
HTTP/1.0 400 Bad Request
Content-Type: text/html; charset=UTF-8
Referrer-Policy: no-referrer
Content-Length: 1555
Date: Thu, 12 Nov 2020 01:57:34 GMT
<!DOCTYPE html>
<html lang=en> <meta charset=utf-8>
...
Пропингуйте IP-порт через командную строку
Ping Specified Port with telnet

Alternatively, we can try to ping a remote port with the IP address. We will just change the domain name with the IP address below.

$ telnet 172.217.18.110 80
$ telnet google.com 89
Trying 172.217.18.110...
Trying 2a00:1450:4001:809::200e...
telnet: Unable to connect to remote host: Network is unreachable
Пропингуйте IP-порт через командную строку
Ping Specified Port with telnet

Ping Specific Port with nc (netcat) Command

The nc or with its well-known name netcat is a tool used by security professionals for remote connectivity and management. Similar to the telnet command nc command can be used to ping specific port numbers for a remote system.

The nc command is provided by the Linux distributions like Ubuntu, Debian, Mint, Kali and can be installed like below.

$ sudo apt install netcat

For Windows operating systems the nc command and executable can be downloaded from alternative locations where one of them is https://github.com/diegocr/netcat .

The syntax of the nc command is very similar to the telnet command. But the difference is -v and -z parameters should be specified. The -v parameter is used for verbose output in order to see the log or status information like connected or not connected. The -z parameter is used for scan mode which will check or scan the specified remote port.

nc -vz DOMAIN PORT
nc -vz IP PORT
  • The DOMAIN is the remote system domain name.
  • The IP is the remote system IP address.
  • The PORT is the remote system port number we want to ping.
$ nc -vz goole.com 80
Connection to goole.com 80 port [tcp/http] succeeded!

We can see that the connection is succeeded which means the remote port number 80 responds to ping requests. We can also use the IP address for the remote system.

$ nc -vz 172.217.18.110 80
$ nc -vz goole.com 89
nc: connect to goole.com port 89 (tcp) failed: Connection refused

As we can see from the result we will get the “Connection refused” message which means the remote port does not respond to ping.

Ping Specific Port with nmap

The nmap is a security tool used to scan remote systems ports and services. The nmap can be also used to ping a specific port. Nmap can be installed for the Linux distributions like Ubuntu, Debian, Mint, Kali like below.

$ sudo apt install nmap

For Windows operating systems use the official nmap site Windows download section like below.

The syntax of the nmap command for the port ping is like below.

nmap -p PORT_RANGE TARGET
  • PORT_RANGE is the remote port number or protocol name. The PORT_RANGE can be also a range of port numbers too.
  • TARGET is a domain name or IP address. Also the target can be an IP range too which includes multiple sequencial IP addresses.

Let’s make an example with the nmap to ping remote port. We will provide the port number with the -p parameter which will be 80 and the remote system is google.com.

$ nmap -p 80 google.com

The nmap is the fastest tool to ping a specified remote port. The command will be executed in 2 seconds and detailed output about the remote port will be provided like below. The line “80/tcp open http” simply expresses that the remote port number 80 responds to pings.

Starting Nmap 7.80 ( https://nmap.org ) at 2020-11-11 18:27 PST
Nmap scan report for google.com (172.217.18.110)
Host is up (0.036s latency).
Other addresses for google.com (not scanned): 2a00:1450:4001:809::200e
rDNS record for 172.217.18.110: zrh04s05-in-f110.1e100.net
PORT STATE SERVICE
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 0.28 seconds
Пропингуйте IP-порт через командную строку
Ping Specified Port with nmap

Alternatively, we can specify the IP address of the remote system we want to ping port.

$ nmap -p 80 172.217.18.110
$ nmap -p 80-90 google.com

The output will be like below where the open ports will be listed with the STATE open.

Starting Nmap 7.80 ( https://nmap.org ) at 2020-11-11 18:32 PST
Nmap scan report for google.com (172.217.18.110)
Host is up (0.039s latency).
Other addresses for google.com (not scanned): 2a00:1450:4001:809::200e
rDNS record for 172.217.18.110: fra16s42-in-f14.1e100.net
PORT STATE SERVICE
80/tcp open http
81/tcp filtered hosts2-ns
82/tcp filtered xfer
83/tcp filtered mit-ml-dev
84/tcp filtered ctf
85/tcp filtered mit-ml-dev
86/tcp filtered mfcobol
87/tcp filtered priv-term-l
88/tcp filtered kerberos-sec
89/tcp filtered su-mit-tg
90/tcp filtered dnsix
Пропингуйте IP-порт через командную строку
Ping Multiple Specified Ports with nmap

Ping Specific Port with Test-Connection In PowerShell

The Windows operating system provides the strong command-line interface named PowerShell with its recent versions. PowerShell provides a lot of useful commands like Test-NetConnection . The Test-NetConnection can be used to ping specified remote ports easily and provides detailed information. The Test-NetConnection is the preferred tool over the telnet command for Windows systems. The Test-NetConnection command is by default with PowerShell and Windows so there is no need for an extra installation process.

The syntax of the Test-NetConnection command is like below.

Test-NetConnection TARGET -p PORT
  • TARGET is an IP address or domain name to port ping.
  • PORT is the remote system port number.

We will use the Test-NetConnection command to test google.com port number 80.

PS> Test-NetConnection google.com -p 80

The output of the ping remote port with the Test-NetConnection command will be like below. We can see that remote system ComputerName, RemoteAddress, RemotePort, InterfaceAlias, SourceAddress, TcpTectSucceeded information is provided.

ComputerName : google.com
RemoteAddress : 172.217.18.110
RemotePort : 80
InterfaceAlias : Ethernet0
SourceAddress : 192.168.142.130
TcpTestSucceeded : True
Пропингуйте IP-порт через командную строку
Ping Port with PowerShell Test-NetConnection

Let’s make another test for port number 89 for google.com.

PS> Test-NetConnection google.com -p 80

The output is like below which means the ping port is failed. For failed ping port operations extra information like PingRelyDetails (RTT), TcpTestSucceeded is provided.

WARNING: TCP connect to (172.217.18.110 : 89) failed
ComputerName : google.com
RemoteAddress : 172.217.18.110
RemotePort : 89
InterfaceAlias : Ethernet0
SourceAddress : 192.168.142.130
PingSucceeded : True
PingReplyDetails (RTT) : 46 ms
TcpTestSucceeded : False
Пропингуйте IP-порт через командную строку
Ping Port with PowerShell Test-NetConnection

Ping Port with PaPing Tool

The PaPing tool is a 3rd party tool created to ping remote specified port. The PaPing project is open source and located in Google Code.

> paping.exe wisetut.com -p 80 -c 5

Ping Port with curl Command

curl HOST:PORT
$ curl 192.168.136.136:80

If the remote port is open some response like a warning, error, etc is returned by the remote port service.

Пропингуйте IP-порт через командную строку
Ping Port with curl Command

Ping Port with psping Command

Windows Sysinternals is used to debug, troubleshoot the Windows operating system. The psping is a Windows Sysinternals tool that can be used to ping a port. The syntax of the psping tool is like below.

psping HOST:PORT
> psping 192.168.136.136:80

The ping is a term and command-line tool used to check remote system network connectivity. It is one of the most popular tools for network diagnostics. By default, the usage of the ping command does not require any port number and will work with just a target IP address or domain name. But you may ask what port number is used by the ping command.

The TCP and UDP protocols are very popular where they can provide multiple port numbers to provide different services over the network. The ping command can be related to these TCP and UDP protocols but it does not use TCP or UDP. This may be even asked you in an interview or certificate exam or class exam. The ping command uses the ICMP protocol. The ping is an old method and tool described in the RFC792 and this standard does not provide any port number for the ping.

Ping and ICMP Protocol

The ping tool uses the ICMP protocol which is different from the TCP and UDP protocol where it is tightly integrated with the IP protocol. The ICMP is a layer 3 protocol that is transmitted with the IP packets even the IP is also a layer 3 protocol too. The ICMP is created to support the IP protocol.

Ping Uses ICMP Type 8 and Type 0

Ping Packet Content

$ ping 8.8.8.8
Пропингуйте IP-порт через командную строку
Ping ICMP Request Packet Details
Пропингуйте IP-порт через командную строку
Ping ICMP Reply Packet Details

Is Port 7 Used For Ping ICMP?

Alternative Way Ping TCP Ports

The ping command is a network tool for checking whether a remote system is up and running. In other words, the command determines if a certain IP address or a host are accessible. Ping uses a network layer protocol called Internet Control Message Protocol (ICMP) and is available on all operating systems.

On the other hand, port numbers belong to transport layer protocols, such as TCP and UDP. Port numbers help identify where an Internet or other network message is forwarded when it arrives.

In this tutorial, you will learn how to ping a port in Windows and Linux using different tools.

How to ping a specific port number.
  • A Linux or Windows system
  • Access to the command line
  • An account with sudo/admin privileges

Can You Ping a Specific Port?

Network devices use ICMP to send error messages and information on whether communication with an IP address is successful or not. ICMP differs from transport protocols as ICMP is not used to exchange data between systems.

Ping uses ICMP packets, and ICMP does not use port numbers which means a port can’t be pinged. However, we can use ping with a similar intention – to check if a port is open or not.

Some network tools and utilities can simulate an attempt to establish a connection to a specific port and wait to see if the target host responds. If there is a response, the target port is open. If not, the target port is closed, or the host is unable to accept a connection because there is no service configured to listen for connections on that port.

You can use three tools to ping a port in Linux:

  • ‎Telnet
  • Netcat (nc)
  • ‎Network Mapper (nmap)

See our tutorial on how to use the ping command in Linux to learn about additional ping options and variations in Linux.

Ping a Specific Port Using Telnet

Telnet is a protocol used for interactive communication with the target host via a virtual terminal connection.

1. To check whether telnet is already installed, open a terminal window and enter telnet.

Install Telnet on Linux.
  • For CentOS/Fedora: yum -y install telnet
  • For Ubuntu: sudo apt install telnet
telnet <address> <port_number>

The <address> syntax is the domain or the IP address of the host, while <port_number> is the port you want to ping.

telnet google.com 443
Ping a port in Linux using Telnet

If the port is open, telnet establishes a connection. Otherwise, it states a failure.

Ping a Specific Port Using Netcat

Netcat (nc) reads and writes from connections using TCP and UDP protocols. This command-line tool can perform many network operations.

1. To check if netcat is installed:

  • For Debian, Ubuntu, and Mint: enter netcat -h
  • For Fedora, Red Hat Enterprise Linux, and CentOS: ncat -h
sudo apt install netcat
nc -vz <address> <port_number>
Ping a port using netcat

Ping a Specific Port Using Nmap

Nmap is a network tool used for vulnerability scanning and network discovery. The utility is also useful for finding open ports and detecting security risks.

Important: Be aware of legal ramifications regarding improper Nmap use, for example, flooding a network or crashing a system.

1. Check if you have Nmap installed by entering nmap -version in the terminal.

Check nmap version on Linux
  • For CentOS or RHEL Linux: sudo yum install nmap
  • For Ubuntu or Debian Linux: sudo apt install nmap
nmap -p <port_number> <address>
Ping a port using nmap on Linux

4. To ping more than one port, enter nmap -p <number-range> <address>.

The <number-range> syntax is the range of port numbers you want to ping, separated by a hyphen.

nmap -p 88-93 google.com
Ping several ports using nmap on Linux

Learn in-depth how to use nmap to scan ports with our guide How To Scan & Find All Open Ports With Nmap.

How to Ping a Specific Port in Windows?

There are two ways to ping a port in Windows:

  • Telnet
  • PowerShell

Ping a Port Using Telnet

Before using telnet, make sure it is activated:

1. Open the Control Panel.

2. Click Programs, and then Programs and Features.

3. Select Turn Windows features on or off.

4. Find Telnet Client and check the box. Click OK.

You activated the Telnet Client on the system.

After completing the activation, you are ready to ping a port using telnet.

1. Search for “cmd” in the start menu. Click the Command Prompt.

2. In the command prompt window, enter

telnet <address> <port_number>

The <address> syntax is the domain or the IP address of the host, while <port_number> is the port number you want to ping.

Ping a port using telnet on Windows

The output lets you know if the port is open and reachable. Alternatively, a connection failure message is shown.

Ping a Port Using PowerShell

PowerShell is a text-based shell that comes with Windows by default.

1. Search for “PowerShell” in the start menu. Click the Windows PowerShell app.

2. In the PowerShell prompt window enter

Test-NetConnection <address> -p <port_number>
Ping a port using PowerShell on Windows

If the port is open and the connection passes, the TCP test is successful. Otherwise, a warning message appears saying the TCP connection failed.

Now you know how to ping and check if a port is open by using several network tools and utilities on Linux and Windows.

Bear in mind that you should not do TCP probing or scan a system unless you have the owner’s permission. Otherwise your actions may be interpreted as an attempt to compromise security.

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

Что такое пинг в Интернете

Ping или пинг — это утилита командной строки, то есть вспомогательная компьютерная программа в составе общего программного обеспечения. С её помощью можно проверить качество подключения к другому компьютеру на уровне IP.

Она считается основным инструментом для администрирования сервера, помогая в решении нескольких задач:

  • Устранение неполадок подключения.
  • Проверка доступности удаленных узлов.
  • Определение имени и IP-адреса устройства.
  • Измерить время, за которое сервер отвечает на команду.

Также пингом называют сам запрос и затраченное на передачу пакета данных время, измеряемое в миллисекундах. Если ещё проще, это задержка между действием пользователя (кликом мыши или нажатием на кнопку) и отображением этого действия на мониторе.

Пинговать — это значит проверить пинг. Но если слышите фразу «я пингую» от участников онлайн-игр, скорее всего, пользователь имеет в виду, что у него медленный интернет и игра виснет.

От чего зависит пинг сайта

Чтобы было легче понять особенности пинга, подключим воображение.

Представьте 2 абстрактных населённых пункта, которые соединяет шоссе. От одного к другому и обратно можно добраться за разное время. Если на дороге нет пробок, всего за час. Если есть заторы, то можно провести в пути несколько часов.

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

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

Таким образом, можно выделить 5 ключевых критериев, которые влияют на пинг.

  • Интернет-тариф. Как правило, при дешёвых тарифах скорость передачи данных низкая. Если планируете играть в онлайн-игры или использовать компьютер для работы в сети, стоит приобретать тариф с подходящей скоростью. Эконом-варианты актуальны для «неспешного» просмотра сайтов.
  • Сетевое оборудование. Причиной низкой скорости может стать качество канала. Иногда проблема низкого пинга решается путём смены провайдера.
  • Производительность сервера. Чем оперативнее обрабатываются запросы, тем лучше соединение и ниже пинг.
  • Расстояние между устройством и сервером. Чем дальше друг от друга они расположены, тем больше времени необходимо для отправки пакетов.
  • Загруженность канала. Чем больше устройств обслуживает один сервер, тем ниже скорость.

Что делает команда ping

Команда Ping в cmd (командной строке) отправляет на сервер пакеты маленького размера и считает время, за которое они достигли цели и вернулись. В результате на экране отображаются данные, на основании которых удаётся сделать выводы о качестве соединения, а также выявить неполадки.

Если пакеты возвращаются быстро и в полной объёме, устройство работает нормально. В ответе отображаются 4 параметра.

  • IP-адрес устройства, с которого отправляется команда.
  • Число отправленных байт, по умолчанию это 32 байта;
  • Время отклика.
  • «Время жизни пакета» — Time to live (TTL). Так называют число промежуточных устройств в сети, которые проходит пакет информации.

Пропингуйте IP-порт через командную строку

В нашем случае самое важный параметр – это время отклика.

  • До 40 мс — хорошее значение, которое свидетельствует о высоком качестве интернет-соединения, удачной конфигурации сети и отсутствии проблем.
  • От 40 — 110 мс – нормальный показатель для комфортной работы в интернете.
  • Более 210 мс – медленное подключение и наличие неполадок.

Команда ping в Windows и Linux

Ping в Windows имеет множество параметров, предназначенных для различных целей. Полный список команд можно посмотреть, открыв справочное окно.

Для этого кликните значок поиска на Панели задач. В поисковой строке напишите «cmd». Выберете пункт «Командная строка». В открывшемся меню нажмите на «Запустить от имени администратора».

Введите команду «ping /?». Откроется такое окно, в котором указано, как пропинговать ip адрес через командную строку.

Пропингуйте IP-порт через командную строку

Здесь отображён список команд для проверки широкого перечня параметров.

В Linux для отображения списка команда нужно написать команду «ping -help». Откроется такое окно.

Пропингуйте IP-порт через командную строку

Для корректного ответа необходимо прямое соединение с устройством. Если вы пользуетесь прокси-сервером, команда не будет работать.

Как проверить пинг через командную строку

Самый удобный способ проверки доступности – пинговать через популярные ресурсы, например, поисковики.

Windows по умолчанию отправляет 4 пакета. Это ограничение можно снять командой «ping «название введённого домена» -t». Также можно принудительно прервать процесс с помощью сочетания клавиш «Ctrl+C». В этом случае отобразится статистика до момента отмены.

На Linux нужно самостоятельно устанавливать ограничение на количество отправляемых пакетов. Иначе операционная система будет посылать их до тех пор, пока вы не остановите процесс вручную с помощью того же сочетания «Ctrl+C». Например, если введёте команду «ping -c 3 ya.ru», будет отправлено только 3 пакета.

Стандартный интервал передачи пакетов составляет 1 с. Но так как проверить пинг иногда необходимо для нестандартных задач, возможно изменить интервал между отправкой пакетов. Это делается с помощью команды «ping -i».

Команда пинг может быть комбинированной, то есть состоять из нескольких параметров. Например, «ping —с 6 —s 100 domain.name». В данном случае задаётся интервал, размер пакетов и адрес источника.

Как снизить пинг

Если превышен интервал ожидания для запроса, пинг можно уменьшить.

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

Если играете в онлайн-игры, старайтесь выбирать серверы вашей страны. Если сервер находится на другом континенте, пинг будет очень высокий. Именно поэтому разработчики предлагают несколько вариантов.

Фоновые загрузки желательно отключить. Если вы одновременно будете скачивать фильмы, общаться через видео-звонки в мессенджерах и играть онлайн, операционная система будет вынуждена потреблять внушительный объём трафика. Его банально не хватит для эффективной работы. Сначала дождитесь, когда процессы завершатся, а потом приступайте к следующему действию. Также стоит отключить раздачи на торренте, так как он тоже отнимает ресурсы.

Периодически следует обновлять программное обеспечение и сетевой адаптер. Технологии постоянно развиваются и требуют больше ресурсов. Устаревшие программы могут не справиться с высокой нагрузкой.

На работоспособность негативно могут влиять вирусы. Поэтому не стоит пренебрегать антивирусами, выполняйте проверку систематически.

Проблема может скрываться в сетевых устройствах и проводах. Убедитесь, что устройство подключено, а кабель не повреждён. Считается, что оптоволокно обеспечивает лучшее качество связи по сравнению с витой парой. Однако его нельзя сгибать, поскольку оно очень хрупкое. Если у вас под столом хаотично свисают или лежат провода, скорее всего, это витая пара.

Программы для снижения пинга

Интернет-трафик можно оптимизировать с помощью специальных программ.

  1. Auslogics Internet Optimizer ― это бесплатный вариант, разработанный для Windows. При запуске выполняется сканирование компьютера или другого устройства. После завершения проверки на монитор выводятся варианты оптимизации. Пользователю нужно выбрать из представленного списка подходящие параметры для настройки.
  2. NetScream ― нацелена на увеличение скорости интернета через настройку модема. Разобраться в возможностях легко благодаря интуитивно понятному интерфейсу и функционалу.
  3. cFosSpeed представляет собой драйвер для Windows. Он выполняет автоопределение и настройку маршрутизатора.
  4. NameBench увеличивает скорость путём оптимизации DNS-серверов.
  5. Throttle выставляет оптимальные настройки модема, выполняет регулировку файлов реестра и ускоряет обработку крупных пакетов.
  6. Internet Accelerator – удобное решение, которое помогает разогнать интернет методом подбора настроек.
  7. Advanced SystemCare оптимизирует скорость интернет-соединения за счёт дефрагментирования и оптимизации реестра, удаления шпионских модулей.
  8. OUTFOX и HASTE – а это VPN-клиенты для онлайн-игр. Они используют для транспортировки трафика виртуальную частную сеть VyprVPN. То есть трафик поступает напрямую на VPN-сервер, а от него на сервер игры. В результате сокращается число сетевых узлов между компьютером и игровым сервером.
  9. VPN4GAMES тоже ведут трафик через виртуальную частную сеть. Однако в отличие от предыдущих вариантов охватывают весь трафик, а не только игровой.
  10. EXITLAG действует через VPN-серверы, а также перенастраивает некоторые системные параметры. Программа автоматически выбирает оптимальный маршрут соединения с серверами.

У этих программ довольно много аналогов. При их выборе важно ориентироваться на ваши цели, в том числе название конкретной игры. Дело в том, что некоторые решения «заточены» под ограниченный спектр игровых серверов.

Заключение

Итак, мы выяснили, что ping — эта утилита, которая предназначена для косвенной оценке качества работы сети передачи данных. К ней относится проверка доступности серверов, расчёт времени задержки, выявление потерянных пакетов.

Высокий пинг свидетельствует о неполадках в оборудовании или сбоях в канале. Однако с помощью команд легко обнаружить проблемы.

Кроме того, его можно привести к оптимальному значению, увеличив скорость соединения. Это можно сделать с помощью специальных программ, проверки оборудования или смены оператора.

TNSPING Utility

is a network testing utility provides by Oracle to test the availability of listener through the substrate of Oracle Net.

Somebody may mistakenly think is a database connection testing tool, no, it’s not. It’s a listener connection testing one.

Essentially, only care about the reachability of listener from client sides, the required elements to test a target are hostname (or IP address) and port number only. It really does not care about whether in the connection string is correct or not.

TNSPING Usages

The simplest format of using is:

tnsping + <Target>

The target can be a connect identifier, an IP address or a full connection description.

1. Connect Identifier

A connect identifier is not an IP address, it’s an alias to represent a connection string defined in .

Single Testing

Let’s see a standard testing.

TNS Ping Utility for 64-bit Windows: Version 19.0.0.0.0 - Production on 20-JAN-2021 19:08:23

Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.1.11)(PORT = 1521))) (CONNECT_DATA = (SERVICE_NAME = ORCLPDB)))
OK (30 msec)

As you can see, the testing includes several information.

  • Client release version
  • The Oracle client we used is release 19c.

  • Testing date time
  • Applied SQL parameter file
  • The applied is in the same folder of .

  • Connect descriptor
  • Since the target we tested is a connect identifier, needs to lookup the its content in at run-time.

    By the way, do you know where is?

  • Response
  • The response message «OK» means a successful reaching to the listener and 30 ms of response time is good.

Multiple Testing

We can sequentially test the same destination multiple times.

The response times are pretty decent for a cross-LAN environment. In my opinion, any response times less than 1 second are all good. If your cannot respond quickly, it may hang for some reason.

2. IP Address or Hostname

IP address or hostname can be used as a testing target. In such case, use easy connect to parse the connection.

IP Address Only

Without specifying port number, assumes that you use port 1521 by default to test your environment.

With Port Number

Of course, we can specify a port number in the testing.

Service Name Added

As I said earlier, does not care about , this is another proof.

In this case, I added a random string for in the connection string, such string is actually an incorrect service name on the listener.

It alway succeeds if we provided correct IP address and port number.

Hostname

A hostname needs to be resolve before connecting to the target listener.

3. Connection Description

In some cases, you may not be able to access because of permission or something. However, you can use a full connection description to test it.

In this case, the command does not parse anything, just use the connection description you provided.

If there’s any problem in the network channel to the destination, it will fail with different aspects. Here I list several possible error types below for your reference.

TNSPING is an Oracle utility to determine if the listener for a service on an oracle network can be reached successfully. This utility is located on ORACLE_HOME/bin directory. Oracle Client should be installed to use this utility not Oracle database. This only tests if the listener for a given service name is up or not. This does not report back the database status.

 <net service name> <count>

The net service name is found on tnsnames.ora, the count is the number of times you want test your connections.
>tnsping ora.dbarepublic.com

TNS Ping Utility for 64-bit Windows: Version 11.2.0.1.0 - Production on 10-APR-2
017 13:57:31
Copyright (c) 1997, 2010, Oracle. All rights reserved.
Used parameter files:
C:\Oracle\product\11.2.0\client_1\network\admin\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = ora_linux.dbarepublic.com)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = ora_db.dbarepublic.com)))
OK (90 msec)

>tnsping oracl_db.dbarepublic.com 10

TNS Ping Utility for 64-bit Windows: Version 11.2.0.1.0 - Production on 10-APR-2
017 14:09:38
Copyright (c) 1997, 2010, Oracle. All rights reserved.
Used parameter files:
C:\Oracle\product\11.2.0\client_1\network\admin\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = ora_linux.dbarepublic.com
1)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = oracl_db.dbarepublic.com
)))
OK (10 msec)
OK (0 msec)
OK (20 msec)
OK (0 msec)
OK (10 msec)
OK (20 msec)
OK (0 msec)
OK (20 msec)
OK (0 msec)
OK (30 msec)

All the above examples showed the successful tnsping connection. There are cases where tnsping can or might fails. I am more interested in showing why it fails? and how you can make it works vs why it works. Off the top of my head, these are few reasons why tnsping fails

  1. Invalid syntax
  2. Wrong net service name
  3. Database host Server Down
  4. Listener Down.

Wrong net Service Name: See what happens when you enter invalid net service name.

C:\Users\dbarepublic>tnsping wrongservice
TNS Ping Utility for 64-bit Windows: Version 11.2.0.1.0 - Production on 10-APR-2
017 14:20:21
Copyright (c) 1997, 2010, Oracle. All rights reserved.
Used parameter files:
C:\Oracle\product\11.2.0\client_1\network\admin\sqlnet.oraTNS-03505: Failed to resolve name
dbarepublic.example.com = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = myserver.example.com)(PORT = 1521)) ) (CONNECT_DATA = (SERVICE_NAME = orcl) ) )

dbarepublic.example.com is the net service name that you need for tnsping. If you don’t see the service name on tnsnames.ora, your tnsping won’t work. The net service
name must exist in the tnsnames.ora file. This file is used by client and database servers to identify server destination.

The net service name used was wrong, now you now the correct name from tnsnames.ora file. Your tnsping is still erroring out even if the service name is correct.
First, I will check to see if the database host, this is where you database is installed is up and working. How do you check that?

ping or ip-address
ping myserver.example.com: 

Now, you are getting TNS-12541: TNS: no listener which means the listener is either not configured right or it is down. To resolve this you will need to ensure the the configuration on tnsnames.ora is correct and then check the status of listener using lnsrctl status. By now, you must have corrected the issue. Alternately, this utility is also used in confirming to ensure the oracle names service is running as well.

Have a Database-ious Day!

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку


tnsping <имя хоста>

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку


Пропинговать сервак можно, а вот как проверить работает ли сама БД..

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку



> кто знает как обработать Oracle-вскую ошибку при коннекте
> к серверу

Там много разных ошибок может быть, и каждую можно обработать несколькими способами.

> нифига не подключается

И не подключится, если возникает ошибка, как не обрабатывай.

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку


а вот как проверить работает ли сама БД..
<Цитата>

БД не работает. Она существует или не существует.

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку



> БД не работает. Она существует или не существует.

И тем не менее база может «существовать», а сервис остановлен (это для винды, не знаю, как в *никсах).

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку


И что из этого? Из этого как-то следует, что вопрос «работает ли БД?» имеет смысл?

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку


> БД не работает. Она существует или не существует.
Вообще-то, она может существовать, но быть в состоянии SHUTDOWN

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку


Еще одна иллюстрация бессмысленности вопроса «работает ли БД?»

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку


Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку


tnsping определяет активен ли листенер, но достаточно попробовать подключится к базе.
try
Database.Connection := True;
exception
 обрабатывай как хочется.
end;

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку


>tnsping определяет активен ли листенер

Не только. Листенер связан с конкретным инстансом. А инстанс это и есть воплощение БД в Оракле.

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку



> Листенер связан с конкретным инстансом.

Я не силен в администрировании Оракла, но тем не менее. А если запущено 2 инстанса? И если листенер связан, то почему в командной строке tnsping присутствует IP, но не присутствует какое бы ни было имя БД или сервиса? Что-то не вяжется.

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку


параметром тнспинга является не IP, а имя записи в tnsnames.ora
На одном хосте может быть несколько инстансов и листенеров.
а tnsping проверяет конкретный.

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку


Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку


В параметре указывается имя записи.
Из этой же записи берется адрес или IP сервера.
Еще оттуда берется SID инстанса.
Если изменить SID на неправильный, то tnsping сообщить об ошибке.

Итого: tnsping приблизительно отвечает на вопрос «работает ли БД»

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку



> В параметре указывается имя записи.
> Из этой же записи берется

Если указывается запись, то все понятно откуда и что может браться. С этим я не спорю. Но на это

TNS Ping Utility for 32-bit Windows: Version 8.1.7.0.0 — Production on 13-DEC-20
05 16:02:32

Attempting to contact (ADDRESS=(PROTOCOL=TCP)(HOST=172.16.2.134)(PORT=1521))
OK (0 msec)

мне ж сервер ответил. Значит IP тоже его устраивает. Или я что-то не так понимаю?

Пропингуйте IP-порт через командную строку
Пропингуйте IP-порт через командную строку


Оцените статью
Хостинги