Checking internet connection linux

Linux: Check Network Connection Command

H ow do I check network connections under Linux using command line options?

You need to use any one of the following tool or command under Linux to check network connections including their state, source/destination, and addresses and bandwidth usage etc:

  1. ss command: It dump socket (network connection) statistics such as all TCP / UDP connections, established connection per protocol (e.g., display all established ssh connections), display all the tcp sockets in various state such as ESTABLISHED or FIN-WAIT-1 and so on.
  2. netstat command: It can display network connections, routing tables, interfaces and much more.
  3. tcptrack and iftop commands: Displays information about TCP connections it sees on a network interface and display bandwidth usage on an interface by host respectively.

Display Currently Established, Closed, Orphaned and Waiting TCP sockets, enter:

# ss -s
Sample outputs:

Or you can use the netstat command as follows:
# netstat -s
Sample outputs:

Display All Open Network Ports

Use the ss command as follows:
# ss -l
Sample outputs:

OR Use the netstat command as follows:
# netstat -tulpn
Sample outputs:

Display All TCP Sockets

Type the ss command as follows:
# ss -t -a
Or use the netstat command as follows:
# netstat -nat

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Display All UDP Sockets

Type the ss command as follows:
# ss -u -a
Or use the netstat command as follows:
# netstat -nau

lsof Command

You can use the lsof command follows to list more information about open ports:
# lsof -i :portNumber
# lsof -i tcp:portNumber
# lsof -i udp:portNumber
# lsof -i :80 | grep LISTEN

View Established Connections Only

Use the netstat command as follows:
# netstat -natu | grep ‘ESTABLISHED’

Say Hello To tcptrack

The tcptrack command displays the status of TCP connections that it sees on a given network interface. tcptrack monitors their state and displays information such as state, source/destination addresses and bandwidth usage in a sorted, updated list very much like the top command.
# tcptrack -i eth0
Sample outputs:

Fig.01: tcptrack in Action

iftop command

The iftop command listens to network traffic on a given network interface such as eth0, and displays a table of current bandwidth usage by pairs of hosts:
# iftop -i eth1
It can display or analyses packet flowing in and out of the 192.168.1.0/24 network:
# iftop -F 192.168.1.0/24
Sample outputs:

Fig.02: iftop command in action

Please go through the following articles for more information:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

9 commands to check if connected to internet with shell script examples

Table of Contents

In this article I will share multiple commands and examples to check if connected to internet for your Linux machine. At the end of the article I will also share some example to test internet connection from the Linux to external network using shell script.

But before we do that there are certain things you must take care of, such as

  • You have IP Address assigned to your network interface (static or dhcp)
  • Your gateway is reachable from the Linux system
  • If you are on virtual machine then make sure your VM is configured to be able to connect external network
  • Your DNS is properly configured

Now there are multiple commands which are available in Linux which can be used to check if connected to internet, we will try to discuss some of them here in brief.

Читайте также:  Как пользоваться кодовой страницей windows 1251 таблицы кодировки ascii

1. Ping Test

The very first tool I use to check if connected to internet is via ping utility . But do you know how to check ping or perform ping check to check if connected to internet? Ping is part of iputils rpm so make sure iputils is installed on your setup

To perform ping check, try to ping any page on internet such as google.com

Here we use -c 1 with ping tool to send only one packet . Now check the statistics section, we see 1 packet was transmitted and received and there was 0% packet loss so it means we are connected to internet.

If you plan to check if connected to internet via shell script then you can use below, anything in the output other than «0» means not connected to internet.

2. Check port availability using cat, echo..

There are various tools which can be used to check port availability which I will share in this article. But many of them are not installed by default so you may have to install them manually. Alternatively you can use below command to check if connected to internet without installing any additional rpm

If the output is 0 then it means you are connected to internet, but if the output is something like below

Then your linux node is not connected to internet.

Alternatively you can also use

3. DNS lookup using nslookup, host etc..

You can perform a DNS lookup any web page address to check if connected to internet. With a successful DNS lookup you should get a response something like below.

For a failed DNS lookup you should get something like

There are many more commands to perform DNS lookup such as host, dig etc

4. Curl

curl is a tool to transfer data from or to a server, using one of the many supported protocols such as HTTP, FTP etc. We can also use this tool to query a webpage and test internet connection in Linux.

Here if you receive anything other than 200 OK then it means the server failed to connect to the provided page. So unless you provide an invalid webpage, your node is connected to internet

5. Telnet

Telnet is another tool to check port connectivity so you can check port availability of any webpage from the Linux node to check if connected to internet. We can try connecting port 53 of Google DNS to check internet connection.

As you see the session was » connected «. If you get an output like below

then it means there is a problem with internet connectivity.

6. Nmap

nmap is normally a port scanner to check the list of open ports on a system. We will use this to connect to external network to scan the port. If it is able to connect to the external network for port scanning then we can check if connected to internet.

Here I am scanning google.com on port 443. As you see highlighted section, nmap was able to establish connection with google.com

7. netcat or nc

In some variant of Linux you will find netcat while in others nc , you can use either of these tools for port scanning. nc or ncat is part of nmap-ncat rpm. Here we use nc command to check connection to google.com on port 443

8. wget

GNU Wget is a free utility for non-interactive download of files from the Web. But we can also use this to check if connected to internet.

Here with —spider Wget will behave as a Web spider, which means that it will not download the pages, just check that they are there
With echo $? we check the exit status, anything other than 0 in the output means your system is not connected to internet

9. Traceroute

The traceroute command shows every step taken on the route from your machine to a specified host. Assuming you are having problems connecting to www.google.com so you can use traceroute to check all the hubs taken to reach the destination server. This will also test internet connection.

Here we were able to trace the route to google.com upto a certain point.

What do those * * * mean?

Each one indicates a five-second timeout at that hop. Sometimes that could indicate that the machine simply doesn’t understand how to cope with that traceroute packet due to a bug, but a consistent set of * indicates that there’s a problem somewhere with the router to which 216.239.43.239 hands off packets.

On a Linux system with no internet connection, you would face problem with DNS resolution itself

Читайте также:  Драйверы для 64 битного windows

How To check if connected to internet using shell script?

You can easily use any or all the above commands/methods to check if connected to internet using bash/shell script.

For example by using wget you can test internet connection in the below shell script:

Here this script will print the status of the internet, similarly for other scripts you can check the exit status and perform tasks accordingly.

Lastly I hope the steps from the article to check if connected to internet (test internet connection) on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

How to Check Internet Connectivity in Linux Terminal

Method 1: PING Command

The best and foremost way is to check the internet availability through the PING command.

The PING command is used for sending and receiving packages from and to some external/remote server.

As an example, we will try to send three internet packages to the Google server and check the internet connectivity if we will be able to receive the internet packets from the Google server.

In the output, you can also witness that the three packages are transmitted and received. Again, this is because pinging to the Google server went successful.

Method 2: CURL Command

Another way to check the internet connection is through the CURL command.

The CURL command is used to download, upload, or transfer the data over the network from or to the server. It supports various protocols, and we can use it to check the internet connectivity by connecting to linuxhint.com and fetch the headers. If the headers are fetched successfully, that means the internet is working; otherwise, there is a problem.

If you get the status 200 OK and the website’s headers, the internet connection is working perfectly fine.

These are the methods to check internet connectivity.

Diagnose the Problem

If the internet is not connected using any of the above methods, you can use the IP command to check whether there is a problem in the gateway settings or network interface.

To get the IP address of your system assigned by the network adapter, use the command provided below:

To get the default gateway IP address, use the “ip r” command:

And try to ping to the default gateway using the PING command:

If pinging goes unsuccessful, it means there is a problem with the gateway settings, and you need to reconfigure them. Otherwise, the gateway settings are fine, but the internet is not working from the internet service provider end.

Conclusion

This post contains a profound guide on how to check the internet connectivity in Linux terminal and how to diagnose the problem. PING command is precisely used for pinging purposes, as its name is saying, while CURL command is used to transferring the data over the network. Using the “ip” command, we can diagnose the problem. Either there is a problem in the default gateway, DNS server resolution, Network adaptor, or ISP (internet service provider).

Источник

Утилита ss в Linux

Иногда бывает необходимо посмотреть какие сетевые подключения Linux открыты, какие IP адреса используются или какие порты прослушиваются. Раньше для таких целей использовалась утилита netstat. Её, без сомнения, знают все системные администраторы и специалисты по безопасности. Но она больше не поставляется по умолчанию в новых дистрибутивах. Вместо неё используется новая утилита под названием ss.

Netstat сканирует директорию /proc для получения необходимой информации, но в новых версиях ядра была реализована специальная подсистема для мониторинга сети в Linux. Её и использует ss, с помощью этой утилиты вы можете получить больше информации о сетевых подключениях и работает она гораздо быстрее.

Как вы уже поняли в этой статье мы рассмотрим мониторинг сетевых подключений в Linux с помощью утилиты из пакета iproute — ss linux. Начнем, как обычно, с синтаксиса и основных опций.

Общая информация

Как уже было сказано работает утилита ss в Linux на основе подсистемы ядра. Синтаксис очень простой — сама команда и ее опции:

$ ss опции [ фильтр_состояния] [фильтр_адреса]

Для удобства вывод команды ss можно фильтровать с помощью grep:

$ ss опции | grep шаблон

Опции указывает различные параметры отображения и фильтрации информации. Фильтры по состоянию и адресу очень интересная вещь, они позволяют выполнять мониторинг сетевых подключений в Linux, только тех что нужно. Например, только открытых, закрытых или находящихся на этапе подключения. Подробнее мы рассмотрим это в конце статьи.

Читайте также:  Coreldraw windows 10 crack

Опции утилиты ss

Для сетевых подключений в Linux с помощью утилиты ss можно использовать такие опции:

  • -V — Version показать версию утилиты.
  • -n — Numeric не определять имена служб.
  • -r — Resolve определять сетевые имена адресов с помощью DNS.
  • -a — All отобразить все сокеты (открытые соединения).
  • -l — Listening показать только прослушиваемые сокеты.
  • -o — Options показать информацию таймера.
  • -e — Extended выводить расширенную информацию о сокете.
  • -p — Processes, показать процессы, использующие сокет.
  • -i — Internal, посмотреть внутреннюю информацию TCP.
  • -s — Summary, статистика использования сокета.
  • -D — экспортировать текущее состояние TCP сокетов в файл.
  • -F — работать с информацией, взятой из файла.

Кроме того, можно вывести сокеты только нужного протокола:

  • -4, —ipv4 — только сокеты протокола IP версии 4.
  • -6 —ipv6 — только сокеты протокола IP версии 6.
  • -0, —packet — только PACKET сокеты.
  • -t, —tcp — TCP сокеты.
  • -u, —udp — UDP сокеты.
  • -d, —dhcp — DHCP сокеты.
  • -r, —raw — RAW сокеты.
  • -x, —unix — UNIX сокеты.

Для фильтрации протоколов можно использовать не только эти опции, но и универсальную опцию -f, передав ей в параметре название протокола. Здесь собраны самые основные опции, если вам нужно больше информации — смотрите справку команды.

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

А теперь давайте рассмотрим примеры использования утилиты ss Linux. Возможно, из описания опций вы мало что поняли, но с примерами все встанет на свои места.

Мониторинг сетевых подключений

Сначала смотрим все сетевые подключения:

Посмотрим только TCP соединения:

Теперь только Unix:

Для отображения UDP сокетов используйте опцию u. По умолчанию будут показаны только подключенные соединения. Если хотите получить все, нужно использовать опцию a. Поскольку UDP, это протокол без постоянного соединения, то без опции -a мы ничего не увидим:

По умолчанию утилита не пытается определять имена хостов через dns, но можно ее попросить делать это опцией -r:

Обратная опция -n, не будет выполняться не только dns резолвинг, но и определение протоколов портов, зато мониторинг сети в Linux работать будет быстрее:

Теперь просмотрим только прослушиваемые tcp сокеты.

Здесь мы видим только имена служб, это не всегда удобно, указав опцию n, мы получим номера портов. Так же само можно посмотреть прослушиваемые udp сокеты:

Также мы можем попытаться узнать название и PID процесса, использующего сокет:

Просмотр статистики статистики сетевых подключений

Для просмотра статистики по использованию сетевых подключений наберите:

С помощью опции -о можно посмотреть информацию о таймере и состоянии подключения.

Фильтрация по протоколу

Мы можем отображать только нужный нам протокол. Например только ipv4:

sudo ss -tl -f inet4

Так же само можно отобразить только соединения ipv6:

Фильтрация по состоянию соединения

В синтаксисе команды мы описали два дополнительных параметра. Фильтрация состояния и фильтрация по адресу. Рассмотрим теперь как ими пользоваться. Сокет TCP может находиться в одном из нескольких состояний. Например, так утилита ss linux выведет только подключенные сокеты.

ss -t4 state established

Или сокеты в состоянии ожидания:

sudo ss -t4 state time-wait

В параметр state можно передать одно из следующих значений:

  • established
  • syn-sent
  • syn-recv
  • fin-wait-1
  • fin-wait-2
  • time-wait
  • closed
  • close-wait
  • last-ack
  • closing
  • all — все состояния
  • connected — все кроме прослушиваемых и закрытых
  • synchronized — все кроме syn-sent
  • bucket — time-wait и syn-recv
  • big — все кроме bucket

Не все состояния подключений можно увидеть просто выполнив команду. Например, syn-sent и syn-recv вряд ли получиться словить, потому что соединения находятся в этом состоянии очень короткое время. Для их отображения удобно использовать команду watch:

watch -n 1 «ss -t4 state syn-sent»

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

Фильтрация по адресу и номеру порта

Кроме фильтрации по состоянию, tcp сокеты можно фильтровать по адресам или портам соединений.

Например, отберем все сетевые подключения linux с портом источником или приемником ssh, то есть все входящие и исходящие соединения ssh:

ss -at ‘( dport = :ssh or sport = :ssh )’

Или сокеты с портом назначения 80 или 443:

ss -nt ‘( dst :443 or dst :80 )’

Такой синтаксис тоже будет работать:

ss -nt dst :443 or dst :80

Еще несколько примеров фильтрации:

Фильтрация по адресу:

ss -nt dst 74.125.236.178

Фильтрация по адресу и подсети:

ss -nt dst 74.125.236.178/16

И по адресу и порту:

ss -nt dst 74.125.236.178:80

Если вы хотите фильтровать сетевые соединения по порту, перед портом ставьте двоеточие:

ss -nt dport = :80

Можно использовать такие операторы сравнения:

  • = или ge — больше или ровно порту.
  • == или eq — точное соответствие.
  • != или ne — не равно.
  • или lt — больше.

Выводы

Вот и всё. Основную информацию о том, как выполнять мониторинг сети в Linux с помощью утилиты ss рассмотрели. Если вам нужно больше информации и примеров смотрите документацию по утилитам набора iproute.

Источник

Оцените статью