Узнать свободен ли порт linux

How to check opened/closed ports on my computer?

@Justgivemeaname: nmap is a tool to check for open ports on another host. If you can run netstat on a machine, it’s much faster and reliable to use it.

@DavidFoerster: Didn’t know about netstat , so I learned that. It says in the link that it should be used from another host, though. Thanks!

8 Answers 8

There’s a few parameters to netstat that are useful for this :

  • -l or —listening shows only the sockets currently listening for incoming connection.
  • -a or —all shows all sockets currently in use.
  • -t or —tcp shows the tcp sockets.
  • -u or —udp shows the udp sockets.
  • -n or —numeric shows the hosts and ports as numbers, instead of resolving in dns and looking in /etc/services.

You use a mix of these to get what you want. To know which port numbers are currently in use, use one of these:

netstat -atn # For tcp netstat -aun # For udp netstat -atun # For both 

In the output all port mentioned are in use either listening for incoming connection or connected to a peer** all others are closed. TCP and UDP ports are 16 bits wide (they go from 1-65535)

** They can also be connecting/disconnecting from the peer.

If it shows some process its used. Its closed(not used) if there is no output.

Another alternative command line easy to use to find out which process is using a port:

lsof -n -i4TCP:$PORT | grep LISTEN 

I added the next function in my .bash_profile,

and now run «pslisten 5060» to see who is grabing my SIP port.

It’s work with Apple Mac OS X too.

Is the port status «LISTENING» indicated that the port is opened?

Yes. It means that some service is listening to that port on your computer for incoming connection i.e. this port is open for establishing new connections.

Any port that are not shown in the output indicated that it’s closed?

Yes. Remember netstat -a will show all active (listening) and passive (non-listening) connections i.e. the ports that are acting as both server (some services are listening to these ports for connections from a different machine/process) and established (connections are established on these ports regardless of the fact the host/a service can be a server or client)

All TCP and UDP ports belong to a category called sockets and there are a whole lot of those. To view socket info you can check man ss .

Читайте также:  Linux partition for server

Thanks. you wrote that -a means server and established. Does «server» means ports that are being listened at by some services? Does «established» mean ports where there are existing connections regardless of it is a client or server’s port? Then what kinds of ports does -a not show?

I don’t think the -a option means «all active» sockets; it just means «all». netstat shows all active sockets by default, but leaves out the passive sockets (open, listening). By using the -a option both active and passive sockets are shown.

@heemayl The second part of your answer is still not correct. A TCP socket in the «listening» state can never be a connection; it is not connected to anything, it is only listening. Listening TCP sockets are also called passive sockets because of this. If a client attempts to connect to a (listening) socket on a server, a new socket will be created on the server to establish a connection with the client. A socket which is part of an established connection is called an active socket.

Another option is ss. It’s much easier to use.

The below command will only output a list of current listening sockets.

root@server:~# ss -l Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port u_dgr UNCONN 0 0 * 23353 * 23352 u_dgr UNCONN 0 0 * 568 * 362 u_dgr UNCONN 0 0 * 14836 * 14837 u_dgr UNCONN 0 0 * 20446 * 369 u_dgr UNCONN 0 0 * 22877 * 369 u_dgr UNCONN 0 0 * 504 * 347 u_dgr UNCONN 0 0 * 16298 * 369 u_dgr UNCONN 0 0 * 23343 * 369 u_dgr UNCONN 0 0 * 24125 * 369 u_dgr UNCONN 0 0 * 24617 * 369 u_dgr UNCONN 0 0 * 23352 * 23353 u_dgr UNCONN 0 0 * 23334 * 369 u_dgr UNCONN 0 0 * 17113 * 369 u_dgr UNCONN 0 0 * 16957 * 369 u_dgr UNCONN 0 0 * 14793 * 362 u_dgr UNCONN 0 0 * 23345 * 362 u_dgr UNCONN 0 0 * 24070 * 369 udp UNCONN 0 0 *:sunrpc *:* udp UNCONN 0 0 *:981 *:* udp UNCONN 0 0 . sunrpc . * udp UNCONN 0 0 . 981 . * tcp LISTEN 0 128 127.0.0.1:85 *:* tcp LISTEN 0 128 *:ssh *:* tcp LISTEN 0 128 *:3128 *:* tcp LISTEN 0 100 127.0.0.1:smtp *:* tcp LISTEN 0 128 *:8006 *:* tcp LISTEN 0 128 *:sunrpc *:* tcp LISTEN 0 128 . ssh . * tcp LISTEN 0 100 ::1:smtp . * tcp LISTEN 0 128 . sunrpc . * 

Источник

Проверка занятости порта сервисом в Linux

Oct 4, 2018 06:09 · 637 words · 3 minute read lsof netstat fuser tips

Однажды вам обязательно понадобится проверить используемый порт определенного сервиса (или наоборот, найти сервисы, слушающие конкретный порт) — в Linux существует несколько утилит командной строки, которые могут с этим помочь. Давайте разберемся!

Первым делом на ум приходит утилита netstat , с помощью которой можно проверить сетевые соединения, статистику сетевых интерфейсов, таблицу маршрутизации и т. д.

Устанавливается данная утилита в разных дистрибутивах по-разному, например, для RedHat и CentOS:

sudo yum install net-tools 
sudo apt-get install net-tools 

Для вывода детальной информации о всех TCP и UDP ендпоинтах можно воспользоваться следующей командой:

Читайте также:  Kali linux настройка tor

Вывод будет примерно следующим:

Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN 1323/systemd-resolv tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1661/sshd tcp 0 0 127.0.0.1:17123 0.0.0.0:* LISTEN 1753/python tcp6 0 0 . 31341 . * LISTEN 30068/java tcp6 0 0 . 22222 . * LISTEN 30068/java tcp6 0 0 . 80 . * LISTEN 30068/java tcp6 0 0 . 10769 . * LISTEN 126755/docker-proxy tcp6 0 0 . 10770 . * LISTEN 129459/docker-proxy tcp6 0 0 . 10771 . * LISTEN 129540/docker-proxy tcp6 0 0 . 10772 . * LISTEN 130172/docker-proxy tcp6 0 0 . 10773 . * LISTEN 130187/docker-proxy tcp6 0 0 . 10774 . * LISTEN 130545/docker-proxy tcp6 0 0 . 22 . * LISTEN 1661/sshd tcp6 0 0 . 10775 . * LISTEN 7406/docker-proxy 
  • -p — вывод ID процесса и его имени;
  • -n — вывод адресов;
  • -l — вывод сокетов;
  • -t — вывод TCP соединений;
  • -u — вывод UDP соединений.

Найти сервис, запущенный на определенном порту можно так:

Аналогично можно найти на каком порту запущен определенный сервис:

netstat -pnltu | grep -i "sshd" 

Также для наших целей подойдет утилита командной строки fuser . По умолчанию она не установлена в большинстве операционных систем, чтобы установить ее в Centos/RedHat делаем так:

Например, чтобы найти идентификаторы процессов (PIDs), запущенных на 80-м порту, выполняем команду:

Результат выполнения будет примерно следующим:

Далее можем найти имя процесса по его идентификатору (PID):

Еще один способ — использование утилиты lsof . Установка ее в RedHat/CentOS выглядит так:

Вывод всех активных TCP и UPD соединений:

Результатом будет примерно следующее:

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME systemd-r 1323 systemd-resolve 12u IPv4 20197 0t0 UDP 127.0.0.53:domain systemd-r 1323 systemd-resolve 13u IPv4 20198 0t0 TCP 127.0.0.53:domain (LISTEN) sshd 1661 root 3u IPv4 29741 0t0 TCP *:ssh (LISTEN) sshd 1661 root 4u IPv6 29743 0t0 TCP *:ssh (LISTEN) python 1754 dd-agent 4u IPv6 39499 0t0 UDP localhost.localdomain:8125 docker-pr 7406 root 4u IPv6 287933991 0t0 TCP *:10775 (LISTEN) docker-pr 7459 root 4u IPv6 287906596 0t0 TCP *:10776 (LISTEN) docker-pr 7792 root 4u IPv6 287937795 0t0 TCP *:10777 (LISTEN) docker-pr 8435 root 4u IPv6 287955267 0t0 TCP *:10778 (LISTEN) docker-pr 8447 root 4u IPv6 287915222 0t0 TCP *:10779 (LISTEN) docker-pr 9060 root 4u IPv6 287891442 0t0 TCP *:10780 (LISTEN) docker-pr 9429 root 4u IPv6 287957044 0t0 TCP *:10781 (LISTEN) docker-pr 9463 root 4u IPv6 287921075 0t0 TCP *:10782 (LISTEN) ntpd 10594 ntp 16u IPv6 35365570 0t0 UDP *:ntp 

Проверить использование конкретного порта можно так:

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME sshd 1661 root 3u IPv4 29741 0t0 TCP *:ssh (LISTEN) sshd 1661 root 4u IPv6 29743 0t0 TCP *:ssh (LISTEN) 

Напоследок можно также воспользоваться утилитой whatportis . Ее установка в RedHat/Centos требует чуть больше действий:

yum install python34-setuptools 

В Debian/Ubuntu все гораздо проще:

В общем виде использование утилиты выглядит так:

whatportis [номер_порта | имя_сервиса] 

Если вам неизвестно точное имя сервиса, можно воспользоваться опцией —like , например:

Читайте также:  Alt linux настройка прокси сервер

Также доступен вывод информации в json-формате:

Источник

How to check if a certain port is open and unused?

Could you please help and tell how can i find out if port 80 is open and unused so that I can start installation.

For what it’s worth, /etc/services is completely static. Grepping it can tell you if a port is officially designated by IANA or some such, but does not tell whether or not it’s in local use.

9 Answers 9

sudo netstat -anp | grep ':80 ' 

That should give you pid & name of the process that holds port 80

This can be achieved using the nc command as follows:

It will return TRUE if the port is already in use, or FALSE is it (i.e, available not listening currently).

I don’t recommend lsof or netstat method as it first try to scan all running PIDs to get all bounded ports:

# time lsof -i:8888 real 0m1.194s user 0m0.137s sys 0m1.056s``` # time nc -z 127.0.0.1 8888 real 0m0.014s user 0m0.011s sys 0m0.004s 

Here 8888 is an unused port. The nc command is ~85 times faster in the above example.

Eg 1:

$ nc -z 127.0.0.1 80 && echo "IN USE" || echo "FREE" IN USE $ nc -z 127.0.0.1 81 && echo "IN USE" || echo "FREE" FREE 

Eg 2:

If you are trying with a remote IP, it is better to add a timeout to auto-exit if it is not accepting connection for the specified time.

Its Google’s IP which is not used, so it will timeout after trying for 2 seconds.

This also works greatly when running inside the Docker image that uses host network. Inside the image, lsof incorrectly reports the port is not in use when it actually is.

The traditional version of nc does not include the -z option. See the differences between traditional and openbsd.

netstat -tln | tail -n +3 | awk '< print $4 >' 

This one displays bind addresses of TCP listening endpoints. All other endpoints are free; Also if on Unix and you are not root, then you can’t bind to a ‘privileged’ port number (port number lower than 1024).

Explained in more details:

  • netstat -tln — all listening tcp ports
  • tail -n +3 — cut off the header of netstat command
  • awk ‘< print $4 >‘ — print the fourth column that consists of [ip]:[port]

For the general case you still need to care to cut out all irrelevant interfaces; a listening address 0.0.0.0 is listening on all network cards, if there is an IP address then that’s the specific IP of the network card/network interface.

Источник

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