output
stringlengths 9
26.3k
| input
stringlengths 26
29.8k
| instruction
stringlengths 14
159
|
---|---|---|
If the size of the disks are the same, you can copy the whole disk.
dd if=/dev/sda of=/dev/sdb |
I have a machine that contains a disk which one has CentOS 6 Installed.
In that disk, There are two partitions. One of them if mounted on /boot, and the second one is a PV for the rootvg.
I need to replace this disk. How to copy OS from one disk to another safely with no software like Acronis or Symantec Ghost?
| How to replace a disk which contains the CentOS6 |
I'm not sure what the cause of the problem was exactly but I fixed it by booting from a windows 10 live disk and performing a startup repair.
That solved the problem and now I get GRUB on booting the system.
|
I have installed windows 10 in my laptop in BIOS Legacy mode.I have 3 primary partitions including the Windows partition and have extended partition with 2 more logical partitions.
Now for installing Arch-Linux I created 4 more logical partitions for /boot,root,swap and /home in that order under the extended partition.
So this is how it looks:
sda1 primary 163gb ntfs
sda2 primary 175gb ntfs
sda3 primary 175gb ntfs
sda4 extended 185gb
sda5 logical 100gb ntfs
sda6 logical 10gb ntfs
sda7 *(boot) logical 400mb ext4
sda8 (root) logical 23gb ext4
sda9 (swap) logical 4gb linux-swap
sda10 (home) logical 50gb ext4I have an arch linux live usb through which i booted and installed the base system.I installed grub and then restarted. Now the problem is the grub wont load and system is into infinie restart loop just showing this:
then exiting pxe rom and restarts back to this screen infinitely.
Now when i select Run Installed OS from live usb options it just shows syslinux screen for a second and returns to the options.
When I press tab to edit boot setting for installed os, it shows:
.com32 boot/syslinux/chain.c32 hd0 0
when I change it to hd1 0 the grub loads and everything is fine.
But this is temporary..Every time I have to do this using live usb for getting grub.
Why does this happen and what should i do to get grub permanently?
Note: The installation went fine and fdisk -l showed this error alone:
partition 4 does not start at a physical boundary.
| Arch Linux: GRUB does not load after installation |
Grub is a piece of software that is installed in the MBR.
Delete sda5 and run grub-update or change grub config manually to boot from sda1, Maybe this howto can help you.
http://www.techsupportforum.com/357-how-to-configure-grub-bootloader-in-mint-linuxubuntu/
If grub is installed on sda u can change the grub config to boot from sda1.
If not try to install grub on sda.
$sudo grub-install /dev/sda
$sudo update-grubIf grub-install gives problems, you can install manually from the Grub shell with:grub
root (hd0,0)
setup (hd0)
quit |
I have a Linux Mint 17.1 Partition at /dev/sda1 and another Mint 17.1 Partition at /dev/sda5. How do I set the MBR to boot into /dev/sda1 instead of the GRUB menu? I know how to use GParted to delete the /dev/sda5 partition but not how to set the MBR.
| How to set MBR to Linux Partition instead of GRUB |
If you see the Windows Boot Loader and not grub when turning on your machine then deleting the Linux partition should be fine.
You don't need to do this to get a new install of Fedora though, you can just instal over the old system as long as you format your / partition during the install process, you will be fine.
|
I'm using fedora 18 side by side Windows 7 and i want to remove fedora. I'm going to that by deleting the fedora partitions from Windows 7. PS: when i installed in the first place fedora, I didn't overwrite MBR, the GRUB2 is installed in /boot partition. So is this method will expose me to problem when the laptop boot into Windows 7 ? ( the object of this is to get a new fresh installation of Fedora ).
| Is this the right way to uninstall Fedora from a dual-boot system? |
Use the bash [[ conditional construct and prefer the $(<command>) command substitution convention. Additionally, [[ prevents word splitting of variable values therefore there is no need to quote the command substitution bit..
if [[ $(netstat -lnp | grep ':8080') == *java* ]]; then
echo "Found a Tomcat!"
fi |
I am trying to do an IF statement from the output of an executed commmand. Here is how I am trying to do it, but it doesn't work. Does anyone know the right way to do this?
if [ "`netstat -lnp | grep ':8080'`" == *java* ]; then
echo "Found a Tomcat!"
fiEDIT:
I wonder if there is a way to do it by capturing exit code?
| How to do an if statement from the result of an executed command |
If your application supports it, you can try passing port 0 to the application. If your application passes this to the kernel, the port will be dynamically allocated at request time, and is guaranteed not to be in use (allocation will fail if all ports are already in use).
Otherwise, you can do this manually. The script in your answer has a race condition, the only way to avoid it is to atomically check if it is open by trying to open it. If the port is in use, the program should quit with a failure to open the port.
For example, say you're trying to listen with GNU netcat.
#!/bin/bash
read lower_port upper_port < /proc/sys/net/ipv4/ip_local_port_range
while :; do
for (( port = lower_port ; port <= upper_port ; port++ )); do
nc -l -p "$port" 2>/dev/null && break 2
done
done |
What's the easiest way to find an unused local port?
Currently I'm using something similar to this:
port=$RANDOM
quit=0while [ "$quit" -ne 1 ]; do
netstat -a | grep $port >> /dev/null
if [ $? -gt 0 ]; then
quit=1
else
port=`expr $port + 1`
fi
doneIt feels awfully roundabout, so I'm wondering if there's a more simple path such as a builtin that I've missed.
| What's the easiest way to find an unused local port? |
netstat has indeed been deprecated by many distributions, though it's really much of the "net-tools" package (including ifconfig, route and arp) that has been deprecated in favour of the "iproute2" package. iproute2 has evolved along with the latest Linux networking features, and the traditional utilities have not.
The iproute2 equivalent that you want is the little known nstat, this provides the netstat -s counters, albeit in a slightly different form:raw counter names from /proc are used, each prefixed with its class ("Udp", "Tcp", "TcpExt" etc)netstat's long (and possibly localised) descriptions are not availablezero-value counters omitted by defaultusing consistent columnar output with the name and value in the first and second columnsthird column shows the average over a configurable time window if you have started a background nstat (-d daemon mode), or 0.0 if not
e.g. nstat prints "UdpInDatagrams NNN" not "Udp: InDatagrams", and not the verbose netstat version of "Udp: NNN packets received".nstat also assumes you want incremental rather than absolute numbers, so the closest equivalent to netstat -s is /sbin/nstat -asz where the options are -a use absolute counters, -s don't keep history file, -z don't omit zero-value counters.
ss takes over the "socket" parts of netstat, but not its complete function as you have found out. (ss is actually better than netstat in many cases, two specific ones are the ability to use filter expressions and the optional capability to use the tcp_diag and inet_diag Linux kernel modules to access kernel socket data more directly than via /proc.)
Should you need to confirm the mapping for descriptive names, the net-tools source is the definitive reference: http://sourcecodebrowser.com/net-tools/1.60/statistics_8c_source.html
Doug Vitale provides a useful guide for finding the iproute2 equivalents of the older commands (it is unmaintained and slightly incomplete, it omits any reference to nstat which has been part of the iproute2 package since at least 2004 kernel 2.6.x time).
net-tools lives on however, and you should be able to find a package for your distribution (or compile it yourself).
|
netstat -s prints out a lot of very detailed protocol statistics like number of TCP reset messages received or number of ICMP "echo request" messages sent or number of packets dropped because of a missing route.
When in Linux netstat is considered deprecated at nowadays, then is there an alternative?
Statistics provided by ss -s are superficial compared to the ones provided by netstat.
| alternative to "netstat -s" |
(you might have to install the package ip on openwrt (v12 / attitude adjustment)
ifconfig/netstat etc. are considered deprecated, so you should use (as root)
ss -nlput | grep sshdto show the TCP/UDP sockets on which a running program which contains the string sshd is listening to-nno port to name resolution
-lonly listening sockets
-pshow processes listening
-ushow udp sockets
-tshow tcp socketsThen you geht a list like this one:
tcp LISTEN 0 128 *:22 *:* users:(("sshd",3907,4))
tcp LISTEN 0 128 :::22 :::* users:(("sshd",3907,3))
tcp LISTEN 0 128 127.0.0.1:6010 *:* users:(("sshd",4818,9))
tcp LISTEN 0 128 ::1:6010 :::* users:(("sshd",4818,8))the interesting thing is the 5th column which shows a combination of IP address and port:*:22listen on port 22 on every available IPv4 address
:::22listen on port 22 on every available IP address (i do not write IPv6, as IP is IPv6 per RFC 6540)
127.0.0.1:6010listen on IPv4 address 127.0.0.1 (localhost/loopback) and port 6010
::1:6010listen on IP address ::1 (0:0:0:0:0:0:0:1 in full notation, also localhost/loopback) and port 6010You then want to know which interfaces has an IPv4 address (to cover 1.)
ip -4 a
# or "ip -4 address"
# or "ip -4 address show"or an IP address (to cover 2.)
ip -6 a
# or "ip -6 address
# or "ip -6 address show(if you do not add the option for IP (-6) or IPv4 (-4) both are shown)
You can also have an look that output and search for e.g. 127.0.0.1 or any other IP/IPv4-address
# here a demo where i show all addresses of the device "lo" (loopback)
ip a show dev lo
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft foreverThe lines beginning with inet and inet6 show that these IPs are bound to this interface, you may have many of these lines per interface:
he-ipv6: <POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1480 qdisc noqueue state UNKNOWN
link/sit 192.0.2.1 peer 192.0.2.3
inet6 2001:db8:12::1/64 scope global
valid_lft forever preferred_lft forever
inet6 2001:db8::2/64 scope global
valid_lft forever preferred_lft forever
inet6 fe80::1111:1111/128 scope link
valid_lft forever preferred_lft foreverand in a script:
address="127.0.0.1"
for i in $(grep ':' /proc/net/dev | cut -d ':' -f 1 | tr -d ' ') ; do
if $(ip address show dev $i | grep -q "${address}") ; then
echo "${address} found on interface ${i}"
fi
done(replace "127.0.0.1")
|
Ex.: an sshd is configured to only listen on wlan0. So. Besides checking the sshd_config how can I check that a daemon is listening on what inerface? netstat can do it? how? (OS: openwrt or scientific linux or openbsd)
UPDATE:
I thought sshd could be limited to an interface... but no... (192.168.1.5 is on wlan0...)
# grep ^ListenAddress /etc/ssh/sshd_config
ListenAddress 192.168.1.5:22
#
# lsof -i -n -P
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
sshd 23952 root 3u IPv4 1718551 0t0 TCP 192.168.1.5:22 (LISTEN)
#
# ss -lp | grep -i ssh
0 128 192.168.1.5:ssh *:* users:(("sshd",23952,3))
#
# netstat -lp | grep -i ssh
tcp 0 0 a.lan:ssh *:* LISTEN 23952/sshd
# | How to check that a daemon is listening on what interface? |
tcp6 simply means TCP protocol over IP v6. tcp6 0 0 dmz.local.net:www 5.140.235.6%14631:49964 ESTABLISHED 21393/apache2As from the netstat manual:tcp6: The protocol used. Here it is TCP over IPv6
0: The count of bytes not copied by the user program connected to this socket.
0: The count of bytes not acknowledged by the remote host.
Local Address
dmz.local.net:www: Address and port number of the local end of the socket. Unless the (-n) option is specified, the socket address is resolved to its canonical host name (FQDN), and the port number is translated into the corresponding service name.
5.140.235.6%14631:49964: Address and port number of the remote end of the socket.
ESTABLISHED: The state of the socket. The state ESTABLISHED means the socket has an established connection.
21393/apache2: Slash-separated pair of the process id (PID) and process name of the process that owns the socket.To sum up: your local apache2 process (pid= 21393), listening on the standard www port (80) has established a TCP (over IPv6) connection with the remote host 5.140.235.6%14631 on port 49964 (unresolved IPv6 address which is a link-local IPv6 address: an address that a computer assigns itself in order to facilitate local communications).
For more about IPv6:wikipedia IPv6 address notation
this superuser thread about % in IPv6, that is Scope ID. |
What does column 'tcp6' mean on output netstat?
Please anyone explain the follow output of netstat:
tcp6 0 0 dmz.local.net:www 5.140.235.6%14631:49964 ESTABLISHED 21393/apache2
What does tcp6 mean?
| tcp6 in the output netstat |
By default if you don't specify address to Apache Listen parameter, it handles ipv6 address using IPv4-mapped IPv6 addresses. You can take a look in Apache ipv6
The output of netstat doesn't mean Apache is not listening on IPv4 address. It's a IPv4-mapped IPv6 address.
|
I have a computer with:
Linux superhost 3.2.0-4-amd64 #1 SMP Debian 3.2.60-1+deb7u3 x86_64 GNU/LinuxIt runs Apache on port 80 on all interfaces, and it does not show up in netstat -planA inet, however it unexpectedly can be found in netstat -planA inet6:
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp6 0 0 :::5672 :::* LISTEN 2402/beam.smp
tcp6 0 0 :::111 :::* LISTEN 1825/rpcbind
tcp6 0 0 :::9200 :::* LISTEN 2235/java
tcp6 0 0 :::80 :::* LISTEN 2533/apache2
tcp6 0 0 :::34611 :::* LISTEN 1856/rpc.statd
tcp6 0 0 :::9300 :::* LISTEN 2235/java
...
tcp6 0 0 10.0.176.93:80 10.0.76.98:53704 TIME_WAIT -
tcp6 0 0 10.0.176.93:80 10.0.76.98:53700 TIME_WAIT - I can reach it by TCP4 just fine, as seen above. However, even these connections are listed under tcp6. Why?
| netstat — why are IPv4 daemons listening to ports listed only in -A inet6? |
Found an article on deprecation from 2011. It seems like the whole net-tools package was not maintained for a while and so it was deprecated. In Debian 9 it is not even installed by default. From the project page it seems like there were no updates at least since 2011.
But you can easily install netstat (and e.g. ifconfig) and keep using them. I would probably only use them for listing stuff though.
Installing on Debian 9:
apt-get install net-toolsPS: For more information you might want to see another Q&A about ifconfig deprecation (ifconfig is part of the same package): https://serverfault.com/questions/458628/should-i-quit-using-ifconfig
| I've heard many times now that it is, and I'm mostly using ss now. But I sometimes get frustrated with differences between the two, and I would love some insight.
Also, I can't be the only one who thinks of Hitler when using ss. Not a great name.
| Why is netstat deprecated? [closed] |
I noticed this issue when I check for local listening ports with ss -utln before Google brought me here.
My first thought of disabling this is to take a look at chrome://flags. And I found this: chrome://flags/#device-discovery-notifications
Disabling this so-called "device discovery" feature turns off listening of mDNS port 5353/tcp. You need to relaunch Chromium / Google Chrome to make this take effect.
|
I am using chromium browser (chrome) with pepperflashplugin in Debian. I have noticed, chromium/pepperflashplugin opens a listening port on my public interface 0.0.0.0:5353 as seen with netstat:
netstat -lptun
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
udp 0 0 0.0.0.0:5353 0.0.0.0:* 13971/libpepflashplI have been using Firefox (Iceweasel) before and I have never seen browser/flash-plugin to open ports. Indeed, I have never seen any client application opening listening ports on 0.0.0.0.
Why is chromium doing this?
Is this necessary ?
Can I disable this?
Can I start chromium with pepperflashplugin disabled ?
| chromium browser (pepperflashplugin) opening listening ports on 0.0.0.0:5353 |
A recent version of ss should also display UDP listeners in that way. You can limit to UDP with ss -unlp.
I have tried a recent Debian version where ss --version reports ss utility, iproute2-ss140804 and that does work.
On A Red Hat 5 system with ss utility, iproute2-ss061002 it doesn't. You do get more info there using ss -aunp although that also shows connected ports.
You can also try:
ss -apu state unconnected 'sport = :1812' |
I've been trying to modernise my way with Linux by, for one thing, ditching netstat for ss. I looked up my favourite command line flag for netstat in the ss man pages, and was very glad to find that netstat -lnp is more or less the same command as ss -lnp. Or so I thought...
# ss -lnp | grep 1812Turns up nothing, but
# netstat -lnp | grep 1812
udp 0 0 0.0.0.0:1812 0.0.0.0:* 11103/radiusddoes. A fact that made that particular troubleshooting unnecessarily harder.
Now I'm trying to understand how I should have used ss to verify that the daemon was listening.
Can someone please explain?
EDIT:
# ss --version
ss utility, iproute2-ss090324
# ss -aunp | grep radi
UNCONN 0 0 *:50482 *:* users:(("radiusd",11103,11))
UNCONN 0 0 127.0.0.1:18120 *:* users:(("radiusd",11103,9))
UNCONN 0 0 *:1812 *:* users:(("radiusd",11103,6))
UNCONN 0 0 *:1813 *:* users:(("radiusd",11103,7))
UNCONN 0 0 *:1814 *:* users:(("radiusd",11103,10))
# ss -lnp | grep radi
# | ss is replacing netstat, how can I get it to list ports similarly to what I am used to? |
As explained in this response to a similar question regarding aptitude and dpkg, netstat is truncating the output because when it's piped to grep, it doesn't know how wide the output should be. Solutions to this general problem depend specifically on the options to the program that's being fed into the pipe. In the case of netstat, the only choice I see is to use the --wide option, which tells it to assume the output is as wide as needed for the output. You might then want to use cut -c-100 eg. if you really only want 100 characters per line.
|
When executing netstat, I find that the command's output width is limited regardless of the console size, in contrast with other commands such as ps that seem to get adjusted.
So for example:
$ sudo netstat -natp | grep sshd
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1454/sshd
tcp 0 48 xx.xx.xx.xx:22 xx.xx.xx.xx:44182 ESTABLISHED 1147/sshd: wtower [
tcp6 0 0 :::22 :::* LISTEN 1454/sshd You can notice that the line width of the second output is short (ends at [). Is there any way so I get the proper output from netstat?
UPDATE: The package version is net-tools_1.60-24.1ubuntu2_i386 running on Ubuntu Server 12.04.5 LTS.
Unfortunately redirecting to file produces the same output.
At any console size the output is the above. At smaller sizes it just wraps each line, but still the output is the same, shortened.
| Netstat output line width limit |
Does anyone know what hbci means or refers to?HBCI stands for "Home Banking Computer Interface", see http://openhbci.sourceforge.net/. The same port number is also used by the "RemoteWare Client", at least according to http://www.networksorcery.com/enp/protocol/ip/ports03000.htm.
The reason you are seeing it is because netstat and similar utilities look up port numbers in a database that maps them to symbolic names (usually, /etc/services).
To suppress this behavior in netstat, one can pass the --numeric-ports option, or just -n which also makes some other things numeric.
| I simply open an http server from my terminal (with node) listening on port 3000, which is obviously working if I request localhost:3000 in a browser.
Now, I want to see this connection so I use netstat.
I'm supposed to see server connection on port 3000, and client connection on another port:
$ netstat -p tcp
Proto Recv-Q Send-Q Local Address Foreign Address (state)
tcp6 0 0 localhost.hbci localhost.50215 ESTABLISHED
tcp6 0 0 localhost.50215 localhost.hbci ESTABLISHED
tcp6 0 0 localhost.hbci localhost.50214 ESTABLISHED
tcp6 0 0 localhost.50214 localhost.hbci ESTABLISHED
tcp6 0 0 localhost.hbci localhost.50213 ESTABLISHED
tcp6 0 0 localhost.50213 localhost.hbci ESTABLISHED
tcp6 0 0 localhost.hbci localhost.50211 ESTABLISHED
tcp6 0 0 localhost.hbci localhost.50212 ESTABLISHED
tcp6 0 0 localhost.50212 localhost.hbci ESTABLISHED
tcp6 0 0 localhost.50211 localhost.hbci ESTABLISHED
tcp6 0 0 localhost.hbci localhost.50210 ESTABLISHED
tcp6 0 0 localhost.50210 localhost.hbci ESTABLISHEDNo entries about the server connection on port 3000. But the localhost.hbci, switching from a local to a foreign address, seems to be my server connection.
And if I type:
$ lsof -i TCP:3000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 1144 garysounigo 11u IPv6 0x6d9a12e1e288efc7 0t0 TCP *:hbci (LISTEN)I'm sure that hbci represent my port 3000.
Does anyone know something about what hbci means or refers to?
Is it a port for local server ? A protocol for s local connection?
I find anythings everywhere ( on any port.. ;) )
| TCP *:hbci (LISTEN) - What does hbci mean? [duplicate] |
UDP is a connectionless protocol. SS probably won't show one in LISTEN state, only in UCONN or ESTAB.
If I do this,
$ nc -u -l 2333Then ss will show (in a 2nd shell):
$ ss -au|grep 2333
UNCONN 0 0 *:2333 *:* If I then connect to it (3rd shell)
$ nc -u localhost 2333then SS shows:
$ ss -au|grep 2333
ESTAB 0 0 127.0.0.1:2333 127.0.0.1:58434
ESTAB 0 0 127.0.0.1:58434 127.0.0.1:2333 |
If I execute ss -lu in order to view all the listening UDP sockets, then none of the sockets are displayed. If I execute ss -au, which lists all(both listening and non-listening) UDP sockets, then "listening" sockets are displayed as UNCONN (see below).
What is the logic behind this? For example running atftpd listening for connections, should have state LISTEN not UNCONN, shouldn't it?
T60:~ # lsof -n | sed -n '1p;/UDP/p'
COMMAND PID TID USER FD TYPE DEVICE SIZE/OFF NODE NAME
avahi-dae 963 avahi 11u IPv4 9088 0t0 UDP *:mdns
avahi-dae 963 avahi 12u IPv4 9089 0t0 UDP *:44639
cupsd 1238 root 10u IPv4 8160 0t0 UDP *:ipp
dhcpcd 2072 root 7u IPv4 532052 0t0 UDP *:bootpc
dhclient6 13131 root 5u IPv6 38031 0t0 UDP *:dhcpv6-client
dhclient6 13131 root 20u IPv4 37954 0t0 UDP *:20152
dhclient6 13131 root 21u IPv6 37955 0t0 UDP *:36745
atftpd 20639 tftp 0u IPv4 344977 0t0 UDP *:tftpnetstat
T60:~ # netstat -lu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
udp 0 0 *:bootpc *:*
udp 0 0 *:tftp *:*
udp 0 0 *:44639 *:*
udp 0 0 *:ipp *:*
udp 0 0 *:20152 *:*
udp 0 0 *:mdns *:*
udp 0 0 *:36745 *:*
udp 0 0 *:dhcpv6-client *:* ss
T60:~ # ss -lu
Recv-Q Send-Q Local Address:Port Peer Address:PortT60:~ # ss -ua
State Recv-Q Send-Q Local Address:Port Peer Address:Port
UNCONN 0 0 *:bootpc *:*
UNCONN 0 0 *:tftp *:*
UNCONN 0 0 *:44639 *:*
UNCONN 0 0 *:ipp *:*
UNCONN 0 0 *:20152 *:*
UNCONN 0 0 *:mdns *:*
UNCONN 0 0 :::36745 :::*
UNCONN 0 0 :::dhcpv6-client :::*T60:~ # ss -v
ss utility, iproute2-ss110629 | why ss(8) understands listening UDP ports differently than netstat(8)? |
There are many misunderstandings in your approach. I'll go over them one by one.Sockets are not associated with a specific process. When a socket is created its reference count is 1. But through different methods such as dup2, fork, and file descriptor passing it's possible to create many references to the same socket causing its reference count to increase. Some of these references can be from an open file descriptor table, which itself can be used by many threads. Those threads may belong to the same thread group (PID) or different thread groups. When you use the -p flag for netstat it will enumerate the sockets accessible to each process and try to find a process for each known socket. If there are multiple candidate processes, there is no guarantee that it shows the process you are interested in.
/proc/<PID>/net/tcp does not only list sockets related to that process. It lists all TCPv4 sockets in the network namespace which that process belongs to. In the default configuration all processes on the system will belong to a single network namespace, so you'll see the same result with any PID. This also explains why a thread/process which doesn't use networking has contents in this file. Even if it doesn't use networking itself it still belongs to a network namespace in which other processes may use networking.
/proc/<PID>/net/tcp contains both listening and connected sockets. When you pass -l to netstat it will show you only listening sockets. To match the output closer you'd need -a rather than -l.
/proc/<PID>/net/tcp contains only TCPv4 sockets. You need to use /proc/<PID>/net/tcp6 as well to see all TCP sockets.If you are only interested in sockets in the same namespace as your own process you don't need to iterate through different PIDs. You can instead use /proc/net/tcp and /proc/net/tcp6 since /proc/net is a symlink to /proc/self/net.
|
I'm trying to implement code that enumerate all existing TCP connections per process (similar to netstat -lptn).
I prefer to implement it myself and not to rely on netstat.
In order to do that, I'm parsing data from /proc/<PID>/net/tcp.
I saw that a number of TCP connections are listed under /proc/<PID>/net/tcp but not listed by netstat -lptn command.
For example I see that /proc/1/net/tcp and /proc/2/net/tcp have several TCP connections (tried on Ubuntu 16).
As I understand, /proc/1/net/tcp is related to the /sbin/init process which should not have any TCP connection.
The /proc/2/net/tcp is related to kthreadd which also should not have any TCP connection.
| reading TCP connection list from /proc |
You can use sort to reorganize the output of netstat in any format you like.
$ netstat -anpt 2>&1 | tail -n +5 | sort -k7,7 -k 6,6This will sort the output using the 7th column first (the process name/PID) followed by the state (ESTABLISHED, LISTEN, etc.).
NOTE: The first part of the command, netstat -anpt 2>&1 | tail -n +5 .. will direct all the output that may occur on STDOUT to STDIN as well and then chop off the first 5 lines which are boilerplate output from netstat which we are uninterested in.
Example
$ netstat -anpt 2>&1 | tail -n +5 | sort -k7,7 -k 6,6
tcp 0 0 192.168.1.20:49309 192.168.1.103:631 ESTABLISHED 2077/gnome-settings
tcp 0 0 192.168.1.20:38393 204.62.14.135:443 ESTABLISHED 2260/mono
tcp 0 0 192.168.1.20:39738 74.125.192.125:5222 ESTABLISHED 2264/pidgin
tcp 0 0 192.168.1.20:40097 87.117.201.130:6667 ESTABLISHED 2264/pidgin
tcp 0 0 192.168.1.20:53920 217.168.150.38:6667 ESTABLISHED 2264/pidgin
...
tcp 1 0 192.168.1.20:50135 190.93.247.58:80 CLOSE_WAIT 24714/google-chrome
tcp 1 0 192.168.1.20:44420 192.168.1.103:631 CLOSE_WAIT 24714/google-chrome
tcp 0 0 192.168.1.20:36892 74.125.201.188:5228 ESTABLISHED 24714/google-chrome
tcp 0 0 192.168.1.20:43778 74.125.192.125:5222 ESTABLISHED 24714/google-chrome
tcp 0 0 192.168.1.20:33749 198.252.206.140:80 ESTABLISHED 24714/google-chrome
...You can use a similar approach to get the counts using various tools such as wc or uniq -c.
Changing the output
If you'd really like to get the output of netstat looking like this:
102 squid ESTABLISHED
32 httpd ESTABLISHEDYou can do some further slicing and dicing using awk & sed. This can be made more compact, but should get you started and does the job.
$ netstat -anpt 2>&1 | tail -n +5 | awk '{print $7,$6}' | sort -k1,1 -k3,3 \
| sed 's#/# #' | column -t
2264 pidgin ESTABLISHED
2264 pidgin ESTABLISHED
24714 google-chrome CLOSE_WAIT
24714 google-chrome CLOSE_WAIT
24714 google-chrome ESTABLISHED
24714 google-chrome ESTABLISHED
...
24714 google-chrome ESTABLISHED
26358 ssh ESTABLISHED
26358 ssh ESTABLISHED
26358 ssh ESTABLISHED
26358 ssh LISTEN
26358 ssh LISTEN
26358 ssh LISTENNOTE: column -t simply aligns all the output in nice columns.
Counting the connections
Finally to do what you want in terms of tallying the occurrences:
$ netstat -anpt 2>&1 | tail -n +5 | awk '{print $7,$6}' | sort -k1,1 -k3,3 \
| sed 's#/# #' | column -t | uniq -c
6 - LISTEN
8 - TIME_WAIT
1 2077 gnome-settings ESTABLISHED
1 2260 mono ESTABLISHED
10 2264 pidgin ESTABLISHED
2 24714 google-chrome CLOSE_WAIT
27 24714 google-chrome ESTABLISHED
3 26358 ssh ESTABLISHED
4 26358 ssh LISTEN
1 26359 ssh ESTABLISHED
4 3042 thunderbird ESTABLISHED
1 32472 monodevelop ESTABLISHED
2 32472 monodevelop LISTEN
1 32533 mono ESTABLISHED
1 32533 mono LISTEN
1 3284 monodevelop LISTEN
1 3365 mono LISTEN
1 4528 mono LISTEN
1 8416 dropbox ESTABLISHED
1 8416 dropbox LISTENThe first column represents the counts.
|
Is there a command similar to netstat -np but grouped by state and PID?
I'd like to know the current count of server connections in a particular state grouped by Programs.
similar to,
102 squid ESTABLISHED
32 httpd ESTABLISHEDI use RHEL5.
| Command similar to netstat -np but grouped by state and PID? |
By default sshd uses ipv4 and ipv6. You can configure the protocol sshd uses through the AddressFamily directive in /etc/ssh/sshd_config
For ipv4 & ipv6 (default)
AddressFamily anyFor ipv4 only
AddressFamily inetFor ipv6 only
AddressFamily inet6After you make any changes to sshd_config restart sshd for the changes to take effect.
|
$ netstat -nat
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:53 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN
tcp6 0 0 :::22 :::* LISTEN Why are there two records of port 22 (:::22 and 0.0.0.0:22) and why does one use protocol as tcp and the other as tcp6
This is on Ubuntu 12.04.4
| Why does SSH show protocol as tcp6 *and* tcp in netstat? |
This might help you,
ss -tupln | grep 1080 |
After doing a ssh -fND 1080 localhost, ssh will listen on port 1080 to provide the SOCKS service:
box:~$ netstat -ln|grep 1080
tcp 0 0 127.0.0.1:1080 0.0.0.0:* LISTEN
tcp6 0 0 ::1:1080 :::* LISTEN
box:~$ss seems to think otherwise:
box:~$ ss -l|grep 1080
box:~$So how can I use ss to check whether 1080 is being listened on or not?
Some more info on my setup:
box:~$ uname -a
Linux box 4.3.0-1-amd64 #1 SMP Debian 4.3.3-5 (2016-01-04) x86_64 GNU/Linuxbox:~$ ss -v
ss utility, iproute2-ss151103 | ss not showing all ports being listened on |
The point on netstat not showing the process information on some situations, for instance NFS, is that NFS is a kernel module, and as such, it does not run as a normal process, and does not have a PID.
You can regularly find threads about this situation if including NFS on your google searches:
netstat doesn't report PID/Program name for some ports
Note: for other users not using sudo, using -p needs root privileges to be able to show the related process of a port.
|
On my CentOS 7, at one point, sudo ss -plt listed a port marked as LISTENING on *:30565, but there was no information whatsoever in the process column of its row. The other listening ports were showing their owning process as usual, like users:(("sshd",pid=1381,fd=3)), but that one row did not have any process information. lsof -i :30565 or netstat -p did not yield any information either.
I haven't been able to reproduce this, and I struggle to think of a situation a "non-process" might be listening on a port (as I'm quite sure Linux does the intended cleanup work when a tcp-listening process dies). As it happens with multiple programs too, the only explanation I can think of is that this is an "intended but very rootkit-y" behaviour of CentOS, but I'm most surely missing something. What might possibly have caused this?
| "netstat -p"/"ss -p" not showing the process of a listening port |
Yes you can. Download it.
But as you don't say what flavor of linux re you using here is couple of examples:
Debian/Ubuntu related:
# What package is the netstat executable in?
apt-file search /usr/bin/netstat
# Now download the source of that package
apt-get source net-toolsCentOS/Red Hat:
yumdownloader --source net-tools |
Can I view the source code of netstat on my Linux machine?
| Source code of netstat |
The /proc/net/* files are generated by the kernel: the entries are in net/ipv4/proc.c in the kernel source, and the entry list is found in include/uapi/linux/snmp.h. It grabs the values from various MIB databases that the kernel keeps.
According to the snmp.h header file, the MIB definitions come from the following documents:RFC 1213: MIB-II
RFC 2011 (updates 1213): SNMPv2-MIB-IP
RFC 2863: Interfaces Group MIB
RFC 2465: IPv6 MIB: General Group
draft-ietf-ipv6-rfc2011-update-10.txt: MIB for IP: IP Statistics TablesActiveOpens is from RFC 1213 (page 47):
tcpActiveOpens OBJECT-TYPE
SYNTAX Counter
ACCESS read-only
STATUS mandatory
DESCRIPTION
"The number of times TCP connections have made a
direct transition to the SYN-SENT state from the
CLOSED state."
::= { tcp 5 }If you can't find the netstat entry in the RFCs, you'll have to search around.
Quite a few of the items are not listed in detail in these documents. If you want more than the brief summary, you'll have to search the kernel source for some of the entries that you described.
EmbryonicRsts is modified in net/ipv4/tcp_minisocks.c, at line 796 in Linux 4.16 at least, and appears to count invalid SYN resets on non-fast opened connections. This is probably not likely to occur unless you're in a SYN cookie flood.
|
There is a long list of stats in /proc/net/netstat and /proc/net/snmp, both of which I think come from the net-tools project. Is there any official or unofficial documentation about these fields? Or even a good source of networking terminology that would help identify them?
Some seem pretty clear:
SyncookiesSent
SyncookieFailed
TCPTimeouts
TCPKeepaliveOthers less clear:
ActiveOpens
PassiveOpensSome fully cryptic to me:
EmbryonicRsts
RcvPruned
... many more ...Update: I've found definitions in the source but still wondering where these descriptions go. Are they compiled and published anywhere?
| Is there documentation for /proc/net/netstat and /proc/net/snmp? |
The column after local address is "Foreign Address" - as these are UDP ports, and listening ports, there is no foreign address so a wildcard is shown.
I'm not sure if this would show the other end(s) if packets had been received as UDP is a connectionless protocol. Also as one-many comms is allowed a single foreign address could be misleading. So it may ALWAYS show the wildcard for udp.
|
Could anyone explain the following output of netstat -plunt?
udp 0 0 0.0.0.0:58262 0.0.0.0:* 1163/avahi-daemon:
udp 0 0 0.0.0.0:17500 0.0.0.0:* 3779/dropbox:u
udp 0 0 0.0.0.0:5353 0.0.0.0:* 1163/avahi-daemon:What does 0.0.0.0:* mean? Are all the ports being listened or something else?
| What does 0.0.0.0:* mean in netstat? |
Assume eth0 is DHCP client interface.
One option is to check the DHCP client lease files dhcpd.leases
Place and name depends on the system; on some Fedora systems, the files under /var/lib/dhclient/ are lease files, where the interesting string is like that :
option routers 192.168.1.1;Another option, which worked for me on a funtoo box: dhcpcd -U eth0
prints a nice table, ready to source in scripts
broadcast_address=192.168.1.255
dhcp_lease_time=86400
dhcp_message_type=5
dhcp_server_identifier=192.168.1.1
domain_name_servers='192.168.1.1 192.168.1.101'
ip_address=192.168.1.101
network_number=192.168.1.0
routers=192.168.1.1
subnet_cidr=24
subnet_mask=255.255.255.0There other options like dhcping, dhclient -n, according to google and manpages, but they fail on my boxes, but may work for you.
|
In my system I have eth0 (which may or may not be connected) and a modem on ppp0 (which always may be up or down). The the case where both interfaces are up and ppp0 is the default route, I'd like to find a way to determine the gateway IP actual address of eth0. I tried "netstat -rn" but in this configuration the output is:Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
xx.xx.xxx.xxx 0.0.0.0 255.255.255.255 UH 0 0 0 ppp0
192.168.98.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
127.0.0.0 0.0.0.0 255.0.0.0 U 0 0 0 lo
0.0.0.0 0.0.0.0 0.0.0.0 U 0 0 0 ppp0So how do I determine eth0's gateway address? In the above case the actual gateway address is 192.168.98.1.
| How to determine eth0 gateway address when it is not the default gateway? |
I think the clue is in the port numbers, take these two entries
smtpd 12950 postfix 9u IPv4 35762406 0t0 TCP hostname:smtp->spe.cif.ic.IP:55277 (ESTABLISHED)
smtp 13007 postfix 13u IPv4 35762309 0t0 TCP hostname:34434->fake.VVVVV.fr:smtp (ESTABLISHED)smtpd has received a connection on port smtp(25) from a high port number, whilst smtp connects to remote port smtp(25) and has a local high port number.
So -> means connected to
|
I want to know if my server establishes a connection to a remote server or if the remote server tries to reach my server. I tried to read the output of lsof and obtain this information:
lsof -i TCP:25
USER FD TYPE DEVICE SIZE/OFF NODE NAME
master 2657 root 12u IPv4 8086 0t0 TCP *:smtp (LISTEN)
smtpd 12950 postfix 6u IPv4 8086 0t0 TCP *:smtp (LISTEN)
smtpd 12950 postfix 9u IPv4 35762406 0t0 TCP hostname:smtp->spe.cif.ic.IP:55277 (ESTABLISHED)
smtp 13007 postfix 13u IPv4 35762309 0t0 TCP hostname:34434->fake.VVVVV.fr:smtp (ESTABLISHED)
smtpd 14188 postfix 6u IPv4 8086 0t0 TCP *:smtp (LISTEN)
smtpd 14188 postfix 9u IPv4 35748921 0t0 TCP hostname:smtp->XX.XX.XX.XX:55912 (ESTABLISHED)
smtpd 14897 postfix 6u IPv4 8086 0t0 TCP *:smtp (LISTEN)I'd like to know if this information means that my server tries to connect to spe.cif.ic.IP or if it's the other way around.
Is the sign -> relevant, or I should use a different command?
| How to use lsof to identify incoming TCP connections? |
netstat is translating the (default) port to the service name, it gets this mapping from /etc/services file.
So, you can get the port from /etc/services:
grep '^postgresql' /etc/servicesOr better add the -n option to netstat to prevent any (host, port, hostname) resolution and post the output in numerics:
netstat -nlYou can limit the search interface by adding -t option for only showing listening TCP sockets (similarly -u for UDP, -x for UNIX domain sockets):
netstat -nltYou can also use any standard text processing tool over the result to get desired stuffs only.
|
I want to see which port, e.g. postgresql is listening on, so I use:
netstat -l
But that is trying to be clever and prints the process name instead of the port:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 localhost:postgresql *:* LISTEN
tcp 0 0 *:31416 *:* LISTEN How can I determine which port any process is listening on with netstat?
| netstat show port number instead of process name |
One way is to say lsof -i:57010 -sTCP:ESTABLISHED. This walks the kernel's open file handle table looking for processes with an established TCP connection using that port. (Network sockets are file handles on *ix type systems.) You'd use -sTCP:LISTEN on the server side to filter out only the listener socket instead.
Because of the way lsof works, it can only see processes your user owns unless you run it as root. It's also fairly inefficient, since a typical *ix system has a lot of file handles open at any given time. The netstat method given in another answer is faster and usually has lower access requirements.
The lsof method has one great advantage, however: not all *ix type OSes have a netstat flag for including the process name in the output, whereas lsof has been ported to every *ix type OS you're likely to use. OS X's netstat is this way, for example. It has a -p option, but it does something different from netstat -p on Linux.
For an uncommon port number like the one in your question, you can typically get away without adding lsof's -s flag, because a given machine is unlikely to have programs both connecting to the port and listening on it. It can be helpful to add it with port numbers like HTTP's 80, where it is likely you'll have multiple programs using that port at once.
It's fortunate that the -s flag is optional in many situations, because that usage only works with lsof version 4.81 and newer. In older versions, -s meant something else entirely! That's a 2008 vintage change, but it can still bite unexpectedly. RHEL 5 ships with lsof 4.78, for example.
|
I have two linux servers. Let's say they are C and S.
C is client of S
On my S machine, I type.$ netstat -an | grep ESTABLISHED
tcp 0 0 192.168.1.220:3306 C:57010 ESTABLISHEDThen I can know C is connecting now.
In the C machine, I'd also like to know the process name which is opening the port 57010 and connecting the S server.
How can I do that? Of course I have root permission of C.
| How can I know the process name which is opening a tcp port? |
There are two standard library calls; getservbyname(3) and getservbyport(3). These allow programs to convert a name (e.g. telnet) to a port (23), or from a port back to a name.
The typical implementation uses /etc/services as the authoritative source, but this can be changed by the services entry in nsswitch.conf.
The command getent can be used to do some lookups, including service entries.
e.g. to convert from port to name
% getent services 80
http 80/tcp www www-httpThis tells me that port 80/tcp is mapped to "http" as the service name, but also has aliases "www" and "www-http".
Similarly to go from name to port
% getent services https
https 443/tcpWe can see https is on port 443/tcp.
These service names are just the registered values for these ports. They don't correspond to processes (it could be apache, nginx, a python script...) and it doesn't guarantee the process uses these (eg apache could listen on port 12345 if configured to do so).
As far as I know, the standard netstat and ss commands will provide either names or ports, not both. But you could write a simple program that took the output from ss and add the port->name mapping to each line.
|
Hi I feel like this is an obvious question but I haven't been able to get a good answer so far. Given the name of the service (which I know running on localhost) is there any networking command line tool like (netstat/ss) which will tell me what port that service is running at? Ideally something like:
$ some-program --service-name='mysql' localhost
'mysql' is running at localhost:3306I feel like there are solutions out there but non of them address it adequately. For example I have considered the following two ss commands:ss -tuln with output:Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
udp UNCONN 0 0 127.0.0.53%lo:53 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:21119 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:37766 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:54399 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:5353 0.0.0.0:*
udp UNCONN 0 0 [::]:51755 [::]:*
udp UNCONN 0 0 [::]:5353 [::]:*
udp UNCONN 0 0 *:1716 *:*
tcp LISTEN 0 100 127.0.0.1:25 0.0.0.0:*
tcp LISTEN 0 70 127.0.0.1:33060 0.0.0.0:*
tcp LISTEN 0 64 0.0.0.0:59687 0.0.0.0:*
tcp LISTEN 0 151 127.0.0.1:3306 0.0.0.0:*andss -tul with output:Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
udp UNCONN 0 0 0.0.0.0:36308 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:36570 0.0.0.0:*
udp UNCONN 0 0 127.0.0.53%lo:domain 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:41124 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:21119 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:37766 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:54399 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:mdns 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:54522 0.0.0.0:*
udp UNCONN 0 0 [::]:51755 [::]:*
udp UNCONN 0 0 [::]:mdns [::]:*
udp UNCONN 0 0 *:1716 *:*
tcp LISTEN 0 100 127.0.0.1:smtp 0.0.0.0:*
tcp LISTEN 0 70 127.0.0.1:33060 0.0.0.0:*
tcp LISTEN 0 64 0.0.0.0:59687 0.0.0.0:*
tcp LISTEN 0 151 127.0.0.1:mysql 0.0.0.0:*The first command's output lists the port numbers that are listening while the second command's output is able to resolve them to the services running at the ports. But I can't somehow "combine" the two outputs where I can have the port number mapped to the service running, side by side. For example the rows:
tcp LISTEN 0 151 127.0.0.1:mysql 0.0.0.0:*and
tcp LISTEN 0 151 127.0.0.1:3306 0.0.0.0:*would be "combined" to give "127.0.0.1:3306 (mysql)" or something to that effect. I only know the above mapping because I googled what the default MySQL port is.
Is there a way to do this? It must be said that I am only learning to use these networking tools so any guidance is much appreciated.
| Given a service name, get its port number? |
First you need to make sure that your machine has the necessary locale set up. You can see available locales with locale -a. For example, on my system:
$ locale -a
C
C.UTF-8
el_GR.utf8
en_US.utf8
fr_FR.utf8
POSIXAs you can see above, I don't have the Portuguese locale. On my Debian, I can create it by running sudo dpkg-reconfigure locales, and choosing the relevant locale:
Package configuration
┌──────────────────────────┤ Configuring locales ├──────────────────────────┐
│ Locales are a framework to switch between multiple languages and allow │
│ users to use their language, country, characters, collation order, etc. │
│ │
│ Please choose which locales to generate. UTF-8 locales should be chosen │
│ by default, particularly for new installations. Other character sets may │
│ be useful for backwards compatibility with older systems and software. │
│ │
│ Locales to be generated: │
│ │
│ [ ] pt_BR.UTF-8 UTF-8 ↑ │
│ [ ] pt_PT ISO-8859-1 ▒ │
│ [*] pt_PT.UTF-8 UTF-8 ▮ │
│ [ ] pt_PT@euro ISO-8859-15 ▒ │
│ [ ] quz_PE UTF-8 ↓ │
│ │
│ │
│ <Ok> <Cancel> │
│ │
└───────────────────────────────────────────────────────────────────────────┘ After hitting Enter, you should get:
$ sudo dpkg-reconfigure locales
Generating locales (this might take a while)...
el_GR.UTF-8... done
en_US.UTF-8... done
fr_FR.UTF-8... done
pt_PT.UTF-8... done
Generation complete.If you are not using a Debian-based distribution, you will need to do this manually:Add the relevant locale name to /etc/locale.gen. For example:
pt_PT.UTF-8 UTF-8Run locale-genAfter the above steps (either the manual approach or the dpkg-reconfigre locales one), locale -a will also list the Portuguese locale:
$ locale -a
C
C.UTF-8
el_GR.utf8
en_US.utf8
fr_FR.utf8
POSIX
pt_PT.utf8Now, you can choose what language output is displayed in:
$ LC_ALL=el_GR.utf8 date
Τετ 14 Οκτ 2015 12:34:28 μμ EEST
$ LC_ALL=fr_FR.utf8 date
mercredi 14 octobre 2015, 12:35:07 (UTC+0300)
$ LC_ALL=pt_PT.utf8 date
Qua Out 14 12:35:11 EEST 2015However, whether or not a particular program is capable of printing output in the selected locale will depend on whether it has been translated; on whether the package ships with the relevant .mo translation file. In the case of netstat, this is /usr/share/locale/${LANG%_*}/LC_MESSAGES/net-tools.mo. On my Debian, the French locale has it but the Portuguese one does not:
$ ls /usr/share/locale/{fr,pt}/LC_MESSAGES/net*
ls: cannot access /usr/share/locale/pt/LC_MESSAGES/net*: No such file or directory
/usr/share/locale/fr/LC_MESSAGES/net-tools.moThis is why I can run netstat in French:
$ LC_ALL=fr_FR.utf8 netstat -apn | head -n2
(Tous les processus ne peuvent être identifiés, les infos sur les processus
non possédés ne seront pas affichées, vous devez être root pour les voir toutes.)
Connexions Internet actives (serveurs et établies)
Proto Recv-Q Send-Q Adresse locale Adresse distante Etat PID/Program nameBut not in Portuguese:
$ LC_ALL=pt_PT.utf8 netstat -apn | head -n2
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name |
I have a program here, that depends on the output of netstat. More concrete: netstat -apn.
Here is an example of a normal output.
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN -A client of mine has some other output (as an example):
Proto Recv-Q Send-Q Endereço Local Endereço Remoto Estado PID/Program name
tcp 0 0 0.0.0.0:111 0.0.0.0:* OUÇA -I want to test my software with a changed output of netstat, like the output of the client.
So the question is: What should I do to change the output language of netstat, so I can reproduce the errors, the client gets?
I already tried to change the language with export LANG=pt_PT, but the output didn't change.
| Language in netstat output |
The manpage and netstat --help both say [--tcp|-t] [--udp|-u] in the synopsis. That's more than a hint - this syntax pretty clearly states that -t is the same as --tcp and that -u is the same as --udp. You're right though that the manpage doesn't document --tcp and --udp.
netstat --help shows that --tcp and --udp are two of the several socket selectors that you can use, see the <Socket> line:
host ~ # netstat --help
usage: netstat [-vWeenNcCF] [<Af>] -r netstat {-V|--version|-h|--help}
netstat [-vWnNcaeol] [<Socket> ...]
netstat { [-vWeenNac] -i | [-cWnNe] -M | -s } -r, --route display routing table
-i, --interfaces display interface table
-g, --groups display multicast group memberships
-s, --statistics display networking statistics (like SNMP)
-M, --masquerade display masqueraded connections -v, --verbose be verbose
-W, --wide don't truncate IP addresses
-n, --numeric don't resolve names
--numeric-hosts don't resolve host names
--numeric-ports don't resolve port names
--numeric-users don't resolve user names
-N, --symbolic resolve hardware names
-e, --extend display other/more information
-p, --programs display PID/Program name for sockets
-c, --continuous continuous listing -l, --listening display listening server sockets
-a, --all, --listening display all sockets (default: connected)
-o, --timers display timers
-F, --fib display Forwarding Information Base (default)
-C, --cache display routing cache instead of FIB <Socket>={-t|--tcp} {-u|--udp} {-w|--raw} {-x|--unix} --ax25 --ipx --netrom
<AF>=Use '-6|-4' or '-A <af>' or '--<af>'; default: inet
List of possible address families (which support routing):
inet (DARPA Internet) inet6 (IPv6) ax25 (AMPR AX.25)
netrom (AMPR NET/ROM) ipx (Novell IPX) ddp (Appletalk DDP)
x25 (CCITT X.25) |
I use the following command to find open ports on my servers:
$ netstat -ntulpI've probably found that on some random website over the years. However, I cannot find where -t or -u are documented. It certainly isn't in the man page. The man page does allude the their existence, and possibly hints that they are synonyms for -tcp and -udp (also undocumented, though easy enough to infer meaning for) respectively.
Though it seems that -t and -u are synonyms for -tcp and -udp, where is this documented?
| Where are netstat's -t and -u flags documented? |
We can make INPUT policy drop to block everything and allow specific ports only
# allow established sessions to receive traffic
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# allow your application port
iptables -I INPUT -p tcp --dport 42605 -j ACCEPT
# allow SSH
iptables -I INPUT -p tcp --dport 22 -j ACCEPT
# Allow Ping
iptables -A INPUT -p icmp --icmp-type 0 -m state --state ESTABLISHED,RELATED -j ACCEPT
# allow localhost
iptables -A INPUT -i lo -j ACCEPT
# block everything else
iptables -A INPUT -j DROPAnother question, would this be the right way to test, or maybe I
should use "netstat" command to see which port has connection
established with the other ip?Yes, you can check netstat -antop | grep app_port and you can also use strace :
strace -f -e trace=network -s 10000 PROCESS ARGUMENTSTo monitor an existing process with a known pid:
strace -p $( pgrep application_name) -f -e trace=network -s 10000 |
We have two apps running (on top of linux) and both communicates through port 42605. I wanted to quickly verify if this is the only port that's been used for communication between them. I tried below rule, but it doesn't seems to work. So, just wanted to get this clarified, if I am doing it wrong.
Following is the sequence of commands i ran
iptables -I INPUT -j REJECT
iptables -I INPUT -p tcp --dport 42605 -j ACCEPT
iptables -I INPUT -p icmp -j ACCEPT
iptables -I OUTPUT -p tcp --dport 42605 -j ACCEPTSo, this will get added in reverse order since I am inserting it.
I wanted to allow incoming and outgoing communications from and to 42605. Does the above rule looks good or am I doing it wrong?
Another question, would this be the right way to test, or maybe I should use "netstat" command to see which port has connection established with the other ip?
| Iptables rule to allow only one port and block others |
If you are on Linux and can handle having ss installed:
ss -o state established '( dport = :5222 )'|awk -F"[\t :]+" 'NR!=1{ ip[$5]+=1 } END{ for (i in ip){n++};print n }'If you would like the awk explained just let me know.
|
Say I want to know how many unique clients are connected to port 5222 on a server.
Can you find a way better/faster/stronger than this?
netstat -nt | grep ':5222.*ESTABLISHED' | awk '{ print $5 }' \
| grep -Po '[0-9]{1,3}(\.[0-9]{1,3}){3}' | uniq | wc -lI know this is a too simple regex for a internet address, but seems unecessary to check for well formed addresses, as netstat will probably output only valid ones.
Can someone come to a netstat -nt | awk { awesomeness }?
A netstat -nt | awk { simplicity }| uniq | wc -l, maybe?
| How to list all unique ip address currently connected to a specific port? |
By default dovecot run pop , imap , pop3 and imaps on the following ports:
110: pop
143: imap
995: pop3s
993: imapsinstall dovecot-pop3d then copy dovecot.socket to /etc/systemd
sudo cp /lib/systemd/system/dovecot.socket /etc/systemd/system/
sudo systemctl reenable dovecot.socketModify dovecot.socket:
sudo sed -i '/:143$/s/^/#/' /etc/systemd/system/dovecot.socketRestart the service:
sudo systemctl stop dovecot.service
sudo systemctl start dovecot.socket
sudo systemctl daemon-reloadCheck the status:
sudo systemctl status dovecot.socket |
When I do netstat -tanup as root on my Debian host, process 1/init is displayed for port 993. How is this possible ? I never saw such behavior.
The command systemctl list-sockets shows the correct service dovecot associated to port 993.
EDIT: I noticed another strange thing: Sytemd reports that davecot is listening on port 143 (imap) and dovecot is configured to not listen on port 143. I get a warning in the logs about that: dovecot: master: Error: systemd listens on port 143, but it's not configured in Dovecot. Closing.: 2 Time(s) | Netstat display wrong process associated to listening port |
I believe netstat -ntp will only show client (nonlistening) sockets in the Local address column.
The -l flag should cause netstat to list server (listening) sockets only, and with -a you should get both and then you can differentiate based on STATEs.
|
I have a socket connection between a client process and a server process, both running on my machine. There are two entries shown for the connection as,
sudo netstat -ntp | grep 56442
tcp 1 0 127.0.0.1:56442 127.0.0.1:8002 CLOSE_WAIT 8276/python
tcp 0 0 127.0.0.1:8002 127.0.0.1:56442 FIN_WAIT2 -How can I figure out which is the server in this case?
I know that the TCP server is running on port 8002, and a client connects to the listening server from port 56442.
I am trying to figure out a way to distinguish between server and client, by looking at the netstat output entries.
And why doesn't the process id/description appear when the socket is in FIN_WAIT2 state?
| Distinguish TCP server from client within netstat output |
I figured out a way. On Linux the ss program is kind of like netstat on steroids - it provides much more information, including the amount of data pending in receive buffers for AF_UNIX sockets. I like ss -axfor my purposes. Man page: http://man7.org/linux/man-pages/man8/ss.8.html
See also my answer here:
How to see the amount of pending data on a unix domain socket?
Also: Intro to SS (some details not found on man page - particularly filters)
|
netstat -a reports Recv-Q (amount of unread data pending for a reading application) for AF_INET sockets, but not AF_UNIX sockets (at least not for SOCK_DGRAM).
Does anybody know a way to obtain this information for AF_UNIX sockets from outside of the process itself?
Barring reporting the amount, is there a way to tell if there is any unread data pending for the application.
| How to report receive queue size for AF_UNIX sockets |
On Linux you can look through the /proc filesystem specifically for a given PID under /proc/<pid>/fd. All the file descriptors (fd) are listed there per process.
Example
$ ls -l /proc/27634/fd/
total 0
lrwx------ 1 root root 64 Mar 17 20:09 0 -> /dev/null
lrwx------ 1 root root 64 Mar 17 20:09 1 -> /dev/null
lrwx------ 1 root root 64 Mar 17 20:10 10 -> /dev/ptmx
lrwx------ 1 root root 64 Mar 17 20:10 12 -> /dev/ptmx
lrwx------ 1 root root 64 Mar 17 20:10 13 -> /dev/ptmx
lrwx------ 1 root root 64 Mar 17 20:09 2 -> /dev/null
lr-x------ 1 root root 64 Mar 17 20:09 3 -> socket:[430396]
l-wx------ 1 root root 64 Mar 17 20:09 4 -> socket:[430437]
lrwx------ 1 root root 64 Mar 17 20:09 5 -> pipe:[430440]
l-wx------ 1 root root 64 Mar 17 20:10 6 -> pipe:[430440]
lrwx------ 1 root root 64 Mar 17 20:10 7 -> socket:[430443]
lrwx------ 1 root root 64 Mar 17 20:10 8 -> socket:[430444]
lrwx------ 1 root root 64 Mar 17 20:10 9 -> socket:[430446]Everything listed there as socket:[....] is a socket.
|
If I have no permission to use lsof, how do I get them for a process with pid already known? Thanks
I know netstat -l -p command print out active unix domain sockets, but it seems it's not updating ? after I closed the socket, it still shows up in netstat command result.
| How do I get active unix domain sockets for a specific pid if I can't use lsof command? |
Consider using SystemTap. It is dynamic instrumenting engine that dynamically patches kernel so you can track any in-kernel event such as opening a socket. It is actively developed by RedHat so it is supported in CentOS.
Installing
To install SystemTap on CentOS 6: Enable debuginfo repository:
sed -i 's/^enabled=0/enabled=1/' /etc/yum.repos.d/CentOS-Debuginfo.repoInstall SystemTap:
yum install systemtapInstall debuginfo packages for kernel. It can be done manually, but there is a tool that can do it automatically:
stap-prepTracing
SystemTap has not tapset probe for TCP connection, but you may directly bind to kernel functions! You can also do it on socket level.
I.e. create script called conn.stp:
probe kernel.function("tcp_v4_connect") {
printf("connect [%s:%d] -> %s:%d\n", execname(), pid(),
ip_ntop(@cast($uaddr, "struct sockaddr_in")->sin_addr->s_addr),
ntohs(@cast($uaddr, "struct sockaddr_in")->sin_port));
}This will give you the following output:
# stap conn.stp
connect [nc:2552] -> 192.168.24.18:50000
connect [nc:2554] -> 192.168.24.18:50000
connect [nc:2556] -> 192.168.24.18:50000However tracking disconnection events seem to be more trickier.
|
Finding the PID of an established connection is trivial using netstat or lsof. However, I have a process which is creating a connection ever 60 seconds to our database and locking it up by maxing out the failed connection attempt limit. I can increase the failed connection limit to something extremely high on the database, or I can try to track down what is making the connection, and I have chosen the latter.
Based on tcpdump/wireshark, I can see that what is happening is that a connection is established and then the connecting server immediately closes the connection before the server can even respond. What I don't know is why.
The first step is to find out what PID is opening the connection. Unfortunately, this seems easier said than done. The problem is that when a connection goes into TIME_WAIT state, it is no longer associated with a PID. Since my connection has a lifetime of less than a tenth of a second, is there any way to record this information?
netstat and lsof appear to be able to poll every second, but this simply isn't fast enough with the connection attempt I am dealing with. Is there a hook that I can connect to to dump this information to a log? Or is my only option to brute force it with a loop and some coding?
I use CentOS 6.
| log PID of each connection attempt |
strace -e trace=connect -f yourprogramor using a dump file
strace -o yourprogram.strace -e trace=connect -f yourprogram |
I have a program that tries to connect to a server on start-up on a unknown port. I need to find out which port the program accesses to enable a ssh tunnel.
I tried netstat but since the connection fails I don't find any useful information.
| Find which ports a program access |
224.0.0.251 is Multicast DNS, and it use the port 5353 (as you noticed). Many operating systems use it to discover new devices/printers/routers with zero or nearly zero configuration. E.g. if you want to send a page to be print to your printer, with e.g. the address my-printer.local, your operating system uses such port to look for the device which is named my-printer
|
I read some tutorials,they say that netstat is deprecated. I tried ss command. THis is the output
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
icmp6 UNCONN 0 0 *:58 *:*
udp UNCONN 0 0 224.0.0.251:5353 0.0.0.0:*
udp UNCONN 0 0 224.0.0.251:5353 0.0.0.0:*
udp UNCONN 0 0 224.0.0.251:5353 0.0.0.0:*
udp UNCONN 0 0 224.0.0.251:5353 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:5353 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:40886 0.0.0.0:*
udp UNCONN 0 0 127.0.0.53%lo:53 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:631 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:17500 0.0.0.0:*
udp UNCONN 0 0 [::]:5353 [::]:*
udp UNCONN 0 0 [::]:55606 [::]:*
udp UNCONN 0 0 *:41016 *:*
udp UNCONN 0 0 *:1716 *:* ss -at at port 5353 shows
ss -aut '( dport = :5353 or sport = :5353 )'
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
udp UNCONN 0 0 224.0.0.251:mdns 0.0.0.0:*
udp UNCONN 0 0 224.0.0.251:mdns 0.0.0.0:*
udp UNCONN 0 0 224.0.0.251:mdns 0.0.0.0:*
udp UNCONN 0 0 224.0.0.251:mdns 0.0.0.0:*
udp UNCONN 0 0 224.0.0.251:mdns 0.0.0.0:*
udp UNCONN 0 0 0.0.0.0:mdns 0.0.0.0:*
udp UNCONN 0 0 [::]:mdns [::]:* Can someone explain how to interpret it?
| What does address 224.0.0.251:5353 represent? |
ss does show you connections that have not yet been resolved by arp. They are in state SYN-SENT. The problem is that such a state is only held for a few seconds then the connection fails, so you may not see it. You could try rapid polling for it with
while ! ss -p state syn-sent | grep 1.1.1.100; do sleep .1; doneOne way to extend the time in this state is to set an arbitrary hard-wired mac address for the IP address in your arp table. Then a connect will take over 30 seconds to timeout, and will be easier to see with ss.
For example, with my eth0 at 192.168.1.1
$ socat tcp:192.168.1.100:80 -
$ arp -i eth0 -n | grep 192.168.1.100
192.168.1.100 (incomplete) eth0setting the mac address makes the socat easily visible
$ sudo arp -i eth0 -s 192.168.1.100 80:ef:00:ff:ff:ff
$ socat tcp:192.168.1.100:80 - &
$ ss -p state syn-sent
Netid Recv-Q Send-Q Local Address:Port Peer Address:Port
tcp 0 1 192.168.1.1:46608 192.168.1.100:http users:(("socat",pid=20230,fd=3)) |
I have a machine that runs a network intensive application that spawns many processes. I noticed recently that the machine is producing ARP requests looking for an IP address that does not exist. I would like to trace down which process on the box is causing the ARP requests to be generated for the sake of troubleshooting (so I can know which part of the application is looking for this non-existant IP).
IP's have been changed but they aren't important anyhow.
I discovered these ARP requests by running tcpdump on another machine on the same network:
# tcpdump -i eth0 arp -t -n
ARP, Request who-has 1.1.1.100 tell 1.1.1.1, length 46There isn't meant to be a device with the address 1.1.1.100, so I want to find what process on 1.1.1.1 is looking for it.
I tried using ss -np | grep 1.1.1.100 as well as netstat -np | grep 1.1.1.100 (netstat is considered deprecated in place of ss for those curious, ss has most of the same options and is meant to perform the same functions). Neither of these return any results, likely because ss and netstat list open sockets, and the ARP request would pre-date a socket being created.
So how can I discern what process causes an ARP request?
| How does one determine the process causing an ARP request? |
vncserver -list only looks at files in ~/.vnc/. There should be a file in your ~/.vnc/ directory ending with .pid. Make sure that the numeric PID in that file (29811) is actually a running process. It is quite possible that the Xvnc process is not running, but exited in such a way that it didn't clean up the .pid file. You can also clean it up by running vncserver -kill :1. This will clean up any other socket files that might be remaining.
|
I'm on CentOS 7 with TigerVNC installed. I have started it up (I think), but I can't connect to it.
Here's what leads me to think it's running:
$ vncserver -listTigerVNC server sessions:X DISPLAY # PROCESS ID
:1 29811But netstat doesn't list it anywhere:
$ netstat -tpln
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 957/sshd
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1277/master
tcp6 0 0 :::22 :::* LISTEN 957/sshdNot sure if it's relevant or not, but here are my iptables:
$ iptables nvL
Chain INPUT (policy ACCEPT 6112 packets, 538K bytes)
pkts bytes target prot opt in out source destination
6 304 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5901Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destinationChain OUTPUT (policy ACCEPT 810 packets, 156K bytes)
pkts bytes target prot opt in out source destination(I attempted to add a rule for 5901 thinking that maybe it was related to why I didn't see vncserver in netstat, but after changing that rule and starting vncserver, nothing changed as far as I can tell.)
| TigerVNC is running, but not listening on any port? |
Until something more suitable is made available, here's an answer that tries in an absolutely non-industrial way to find processes that used bind(2) on a TCP socket, but then did neither listen(2) nor connect(2), and can also display what's the bound TCP address.
Requires getfattr found in a package named attr in most distributions plus kernel >= 3.7 to filter out non-TCP sockets, and a minimal installation of gdb (eg on Debian: gdb-minimal). Doesn't require a development environment. Should be run as the root user (or else it will find only the same users' information, but this won't even work accross containers). See Caveats at the end.Components:A first shell script mimics a part of what would lsof do but only for this specific case. Searches all processes for socket FD. For sockets with the property TCP or TCPv6 (which is available as a file meta-attribute system.sockprotoname using getfattr, as found with lsof that would use getxattr(2) in such manner to at least display it's a TCP socket), check if the (sockfs pseudo-filesystem's) inode can be found in their respective network namespace's tcp or tcp6 proc file and if not displays the pid, fd and inode as candidate 3-uple. This script alone will find and list "defective" processes.
findbadtcpprocs.sh:
#!/bin/shfind /proc -mindepth 1 -maxdepth 1 -name '[1-9]*' |
xargs -I{} find {}/fd -follow -type s 2>/dev/null |
while read procfd; do
type=$(getfattr --absolute --only-values -L -n system.sockprotoname $procfd | tr '\0' '\n')
if [ "$type" = "TCP" -o "$type" = "TCPv6" ]; then
inode=$(stat -L -c %i $procfd)
pid=$(echo $procfd | cut -d/ -f3)
if awk '$10 == inode { exit 1 }' inode=$inode /proc/$pid/net/tcp /proc/$pid/net/tcp6; then
fd=$(echo $procfd | cut -d/ -f5)
echo $pid $fd $inode
fi
fi
done This script can be used standalone to just find candidate processes without additional information.Then a gdb script which must be given the right fd information. It attaches on a candidate process and will (first allocate some memory in order to) run getsockname(2), display the bound socket (and free allocated resources) an release the process.
getsockname.gdb:
set $malloc=(void *(*)(long long)) malloc
set $ntohs=(unsigned short(*)(unsigned short)) ntohs
p $malloc(64)
p $malloc(4)
set *(long *)$2=64
p (int) getsockname($fd,$1,$2)
set logging file /dev/stdout
set logging on
if *((short *) $1) == 2
set $ip=(unsigned char *) ($1+4)
printf "%hu.%hu.%hu.%hu",$ip[0],$ip[1],$ip[2],$ip[3]
else
if *((short *) $1) == 10
set $ip6=(unsigned short *) ($1+8)
printf "[%hx:%hx:%hx:%hx:%hx:%hx:%hx:%hx]",$ntohs($ip6[0]),$ntohs($ip6[1]),$ntohs($ip6[2]),$ntohs($ip6[3]),$ntohs($ip6[4]),$ntohs($ip6[5]),$ntohs($ip6[6]),$ntohs($ip6[7])
end
end
printf ":%hu\n",$ntohs(*(unsigned short *)($1+2))
set logging off
call (void) free($2)
call (void) free($1)
quitFinally a glue script uses both previous scripts for easy operation. It will avoid uselessly attaching to multiple processes (or threads) sharing the same socket.
result.sh:
#!/bin/sholdinode=-1
./findbadtcpprocs.sh | sort -s -n -k 3 | while read pid fd inode; do
printf '%d\t%d\t%d\t' $pid $fd $inode
if [ $inode -ne $oldinode ]; then
socketname=$(gdb -batch-silent -p $pid -ex 'set $fd'=$fd -x ./getsockname.gdb 2>/dev/null) || socketname=FAIL
oldinode=$inode
fi
printf '%s\n' "$socketname"
doneJust running this will provide all:
chmod a+rx findbadtcpprocs.sh result.sh
./result.shAs a bonus a simple reproducer in C source code that will create two processes using the same TCP socket, without using listen(2) on it. Usage: gcc -o badtcpbind badtcpbind.c and ./badtcpbind 5555
badtcpbind.c:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>#include <strings.h>
#include <stdlib.h>
#include <unistd.h>int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in myaddr;
if (argc < 2) {
exit(2);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit(1);
}
bzero(&myaddr, sizeof myaddr);
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = INADDR_ANY;
myaddr.sin_port = htons(atoi(argv[1]));
if (bind(sockfd, (struct sockaddr *) &myaddr, sizeof myaddr) < 0) {
perror("bind");
exit(1);
}#if 0
listen(sockfd,5);
#endif fork();
sleep(9999);
}example:
# ./badtcpbind 5555 &
[1] 330845
# ./result.sh
108762 20 303507 0.0.0.0:0
330845 3 586443 0.0.0.0:5555
330846 3 586443 0.0.0.0:5555(Yes for some unknown reason, a libvirtd process appears here to create a TCP socket which doesn't get used and is caught in the first line of the results).Caveats:a language better than shell should probably be used to allow more readability and efficiency.certainly even more racy than lsof.attaching to a running process the way is done here has issues:doesn't work on a statically linked binary (malloc() function or some symbol definitions aren't available then).
as no debug information is available, most functions are explicitly scoped and this might not run in all environments without change (tested on amd64 architecture with kernel 5.10.x, on Debian bullseye, Debian 10 and CentOS 7 userspaces).
likewise might not as-is work on a binary linked with an other libc than usual glibc.
is intrusive and might crash fragile (especially multi-threaded) applications. Checks aren't done (eg: malloc(3)'s or getsockname(2)'s failure).the last script considers sockfs inodes to be globally (rather than per-network-namespace) unique, which I didn't attempt to prove but keeps the script simpler. |
When a faulty application calls bind() with a TCP socket to a port P but does not follow with listen(), the port P is not listed among open ports, i.e. netstat or ss or ls /proc/net/tcp do not show it, but the port is occupied and no other application can use it. Is there a reasonable way to find such applications and such ports?
| How to find applications/ports that do bind() but don't do listen()? |
It is the output of the clear command …
You ran clear. clear produced these control sequences. (They are merely in a different order on my machine.) % clear | cat -v ; echo
^[[2J^[[H^[[3J
%
On an ECMA-48 terminal or terminal emulator these control sequences erase the display and position the cursor.% clear | console-decode-ecma48
ED 2
CUP 0
ED 3
%
But the watch command interprets the standard outputs of the processes that it runs, and does not understand any ECMA-48 control sequences apart from one. It only understands some of the TTY-37 control characters from 1968 and (if the -c flag is used) the SGR control sequence from ECMA-48.
Everything else it passes to ncurses, which prints control characters in caret notation. But because of a bug in watch, the second character of a caret notation string is then immediately overwritten, and what should have been ^[[ comes out as ^[ in watch's output.
… and only the clear command.
The shell script is not quoted at all:
watch -n 10 clear > /dev/pts/0 ; netstat -tupn 2>/dev/null | grep -v 3306 > /dev/pts/0
So this is two pipelines, sequentially:
watch -n 10 clear > /dev/pts/0
netstat -tupn 2>/dev/null | grep -v 3306 > /dev/pts/0
The redirection happens before the commands are run, and in two cases is redirecting standard output to the pseudo-terminal that it was open to anyway. They are effectively no-ops:
watch -n 10 clear
netstat -tupn 2>/dev/null | grep -v 3306
Your machine is doing exactly what you told it to do.
So you are watching the output of just the clear command, repeatedly, whose output isn't being processed as control sequences but simply printed in broken caret notation.
Exit watch to run your netstat command once. ☺
|
I am on a Debian system fresh installed, logged in via ssh on /dev/pts/0, and have entered the following command
watch -n 10 clear > /dev/pts/0 ; netstat -tupn 2>/dev/null | grep -v 3306 > /dev/pts/0and what I get looks like this
Every 10.0s: clear Thu Jan 30 17:42:01 2020^[3;J^[H^[2JWhy is this linux box hating me ???
| What is this : ^[3;J^[H^[2J? |
They're covered here in the guide: Linux Network Administrators Guide
Chapter 5. Configuring TCP/IP Networking.
excerptThe last column shows the flags that have been set for this interface. These characters are one-character versions of the long flag names that are printed when you display the interface configuration with ifconfig:B = A broadcast address has been set.
L = This interface is a loopback device.
M = Supports multicast
O = ARP is turned off for this interface.
P = This is a point-to-point connection.
R = Interface is running.
U = Interface is up. |
Can anyone explain for me what each option in Flg means?
[root@apple ~]# netstat -i
Kernel Interface table
Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg
eth0 1500 0 110512 0 0 0 6660 0 0 0 BMRU
eth1 1500 0 110713 0 0 0 4533 0 0 0 BMRU
eth2 1500 0 733 0 0 0 17 0 0 0 BMRU
lo 16436 0 45 0 0 0 45 0 0 0 LRUAnd are there any more?
| Understand netstat -i flgs |
Once the SSH connection is established, you’ll see a listening socket on port 9000:
$ ss -o state listening 'sport = 9000'
Netid Recv-Q Send-Q Local Address:Port Peer Address:Port
tcp 0 128 127.0.0.1:9000 *:*
tcp 0 128 ::1:9000 :::*You won’t see a connection to google.com until a connection is established to port 9000; run
$ nc localhost 9000then in another terminal you’ll see something like
$ ss -o state established 'dport = 80'
Netid Recv-Q Send-Q Local Address:Port Peer Address:Port
tcp 0 0 10.10.10.2:34948 216.58.204.142:httpwith a peer address belonging to Google.
|
After I run
$ ssh -L 9000:google.com:80 testme@localhosthow can I verify that the port forwarding is established by checking the sockets (internet and unix domain sockets)?
Thanks.
| How can I verify that the port forwarding is established by checking the sockets? |
You can also do a text-processing to your current output to match the port. Just add sed -e 's/.*:/:/g'
#!/bin/bash
ntstat=`netstat -tulpn | grep ":53 " | grep LISTEN | awk {'print $4'} | sed -e 's/.*:/:/g'`
port=":53 "#Just to echo for testing
echo $ntstat
echo $portif [[ "$ntstat" == "$port" ]]
then
echo " X Service at port number $port"
else
echo " Port is not listing "
fi Please note that I added a space right after the port number in order to avoid other ports containing 53
Since this are bash operators, you must want to put the shebang #!/bin/bash at the very top of your script so when you execute your script as ./portlisten.sh, it will take the interpreter as /bin/bash, would be the same if you execute your script as $ bash portlisten.sh
|
I got a task to do.
I have to search whether, are there running services on below ports.
ports 53 & 55
If not I have to send alerts.
Please correct my logic and syntax in below code for one port
ntstat=`netstat -tulpn | grep :53 | grep LISTEN | awk {'print $4'}`
port="*:53"#Just to echo for testing
echo $ntstat
echo $portif [[ "$ntstat" == "$port" ]];
then
echo " X Service at port number $port"
else
echo " Port is not listing "
fiOutput :
127.0.1.1:53
*:53
Port is not listing I am struggling to match strings (127.0.1.1:53 to *:53)
| script to verify running services on specific ports |
Use
netstat -anp | grep ':6016'
That will give you the pid of the process connected to the port. Then use
ps aux | grep <the pid from the previous command>
to get the username that the process is running as.
|
I wanted to know which user is running a particular port no.
For e.g.
netstat -an | grep ':6016'which user is resposible for "6016" port no.
| How to check which user is responsible for a utilizing a particular port? |
Let us look into the performance diagram to understand the various layers in which netstat command is useful for debugging. Ethernet
netstat -in command is used in this layer where -i flag is used to display a table of all network interfaces, or the specified iface.
IP
netstat -an command is used in this layer where -a flag is used to show both listening and non-listening (for TCP this means established connections) sockets.
TCP/UDP
netstat -at is used to display either TCP or UDP connections. TCP and UDP protocols are used in the transport layer.
Sockets
netstat -p is used to show which processes are using which sockets.
|
netstat command is useful to,Print network connections, routing tables, interface statistics,
masquerade connections, and multicast memberships.Now, I was reading about the Linux performance which is depicted in a nice pictorial view from here.
How is netstat command used in various levels of networking as depicted in the performance diagram in the referenced question?
| How does netstat command fit in various layers of TCP/IP model in the performance diagram? |
if you convert your psudo code to sh, here is a test for your if
netstat -anp|grep EST|sed 's/^..p6\? \+[^ ]\+ \+[^ ]\+ \+[^ ]\+ \+\([^ ]\+\) \+.*$/\1/'|grep -q 8.8.8.8 && echo connectedso you need a while loop and a sleep 10m and a pmset 0 but as my osx box is in storage it would be a good idea to check my re.
|
An application I use downloads data from a specific server, and I need it to sleep after the download has finished and the socket is closed.
However downloads take place at random days, the app that downloads checks for updates and only downloads if there is one
Proto Recv-Q Send-Q Local Address Foreign Address (state)
tcp4 0 0 192.168.1.29.51005 8.8.8.8.80 ESTABLISHEDPretend 8.8.8.8 is server where data is downloaded from.
Is there a way to prevent the computer sleeping while there is HTTP session to a specific server in progress?
Now please excuse my pseduo script, but it's the best way I could try
netstat -anp tcp
IF Foreign Address = 8.8.8.8 & state = ESTABLISHED
then
WAIT AND CHECK IN 10 MINUTES
else
pmset sleepnow
fi | OS X: how to keep the computer from sleeping during a http connection |
Up to FreeBSD 8.x (at least as of 8.4-RELEASE) it was possible to use the -t option with netstat -i/-I (show the state of all network interfaces/a specific interface).
From FreeBSD 8.4-RELEASE netstat man:
If -t is also present, show the contents of watchdog timers.This indeed had disappeared from FreeBSD 9.x (see FreeBSD 9.2-RELEASE netstat man).
We can only conclude that it is not possible anymore to check the value of these timers through netstat (if ever these timers have meaning with the 9.x releases).
By the way, -t had no meaning with -n. So I guess it was not reporting any error because the syntax checker was a bit too permissive but it was adding nothing to your netstat output.
|
I was using the following command on my previous dedicated server with the same version of the FreeBSD installation:
# uname -a
FreeBSD 9.2-RELEASE FreeBSD 9.2-RELEASE #0 r255898: Thu Sep 26 22:50:31 UTC 2013 [emailprotected]:/usr/obj/usr/src/sys/GENERIC amd64The command is following:
netstat -ntu -f inetOutput:
netstat: illegal option -- tWhy doesn't it work anymore? I don't have an access to my previous dedicated server so I can't use the man to check the differences.
| netstat command doesn't work anymore on the new dedicated server |
client-server GUI programs
Like several other GUI programs nowadays, since 2008 lxterminal has attempted to display all terminal emulator windows from a single process, one per X display per user. To do this, it attempts to connect to an existing socket by the sort of name that you are seeing, that incorporates the display name and your user name. If the connection succeeds, it simply dumps its current directory and argument vector down the socket and exits. It does not use file descriptor passing to pass along an open file descriptor to its current directory directly, but passes it by name.
If the connection fails, it attempts to itself become the listening server on that socket. It reads messages comprising a current directory and an argument vector, and opens up a new GUI terminal emulation window for each read, as if it were its own current directory and argument vector.The visible effect of this is that the first lxterminal program that you invoke (and leave running) operates synchronously, whereas the second and subsequent ones do not. To observe this, start with no lxterminal instances running, run a different terminal emulator, and invoke lxterminal & sleep 1 ; lxterminal from a shell. The shell will return to the prompt after 1 second, and show only 1 lxterminal job left running.
rxvt has a similar capability, but one has to explicitly invoke the urxvtd server, and explicitly run the urxvtc client. Running plain urxvt does not attempt any client-server shenanighans.
GNOME Terminal only works this way, in contrast. It always passes the argument vector over to a server process and then exits. There is, moreover, just the one server process per user, handling all displays (and bugs in the way that this mechanism initializes, to boot).
insecurity
The creation of files and sockets in /tmp with predictable names is a well-known security concern, and lxterminal shares it. Users can pre-create sockets in the predictable places that lxterminals run by other users on the same machine will attempt to talk to.
rxvt, in contrast, uses a non-group-writable non-other-writable subdirectory of each user's home directory. Another possibility for fixing this problem with lxterminal that equally would not allow other users the access to replace one's sockets with theirs would be having the sockets in /run/user/username/lxterminal.
(GNOME Terminal uses the user-level Desktop Bus to communicate between clients and its server. Nowadays the AF_LOCAL socket for that lives in /run/user/username/ where it cannot be supplanted by other unprivileged users.)
bugs
One of the problems that has plagued GNOME Terminal is that it takes up a lot of open file descriptors in the single server process for each instance of a terminal emulation. It used to be 16; and is now down to a "mere" 8.
lxterminal uses 2, one of which is a leaked open file descriptor for the socket connection from the client process. Open and close enough terminal emulations, and eventually lxterminal will run out of available file descriptors. The following, starting with no lxterminal instances running, used up all of the server's available file descriptors in just over a minute on one of my machines: (ulimit -H -n 1024 ; lxterminal) &
seq 0 1024 | while read -r i ; do lxterminal -e /usr/bin/true ; done
Further readingcan't kill gedit process from its PID
Run true multiple process instances of gnome-terminal
Fred Chien (2008-06-16). Add missing files for process sharing. 1f69f854d8ab1377888e18c759f11eae99da75b9. lxde/lxterminal. GitHub.
Fred Chien (2008-06-16). add process sharing support. 074ec09b779c0265a316d37742d2957146bcb141. lxde/lxterminal. GitHub. |
Can you explain the following lines in the netstat output?
Active UNIX domain sockets (w/o servers)
Proto RefCnt Flags Type State I-Node Pathunix 2 [ ] STREAM CONNECTED 37133819 /tmp/.lxterminal-socket:0-xralf
unix 2 [ ] STREAM CONNECTED 37109191 /tmp/.lxterminal-socket:0-xralf | lxterminal in the netstat output |
Why I can't see the Machine B in connections?because it's acting as a router, not an endpoint of the connection.and what shall I do to see it?To show connections tracked by the stateful firewall, run conntrack.
http://conntrack-tools.netfilter.org/manual.html#conntrack
If you did not have a stateful firewall, you would have to simply capture and interpret packets. wireshark works well.
|
I have 2 machines
A 192.168.0.40 (CentOS)
B 192.168.0.41 (Debian)Gateway 192.168.0.2Now I did set a port forwarding using firewallD, from
A port 2245
to
B port 22Connection established from client 192.168.0.1 to Machine B trough Machine A
Running netstat on machine A
# netstat -tulpaneoutput:
# netstat -tulpane
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program name
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 0 16330 1/systemd
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 0 20510 1273/sshd
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 0 21452 1841/master
tcp 0 0 192.168.0.40:22 192.168.0.1:64870 ESTABLISHED 0 142436 4598/sshd: root@
tcp 0 0 192.168.0.40:22 192.168.0.1:59846 ESTABLISHED 0 22169 2480/sshd: root
tcp 0 64 192.168.0.40:22 192.168.0.1:65139 ESTABLISHED 0 146378 4782/sshd: root@
tcp 0 0 192.168.0.40:22 192.168.0.1:65095 ESTABLISHED 0 145904 4756/sshd: root@
tcp 0 0 192.168.0.40:22 192.168.0.1:65024 ESTABLISHED 0 145298 4704/sshd: root@
tcp6 0 0 :::111 :::* LISTEN 0 16329 1/systemd
tcp6 0 0 :::22 :::* LISTEN 0 20519 1273/sshd
tcp6 0 0 ::1:25 :::* LISTEN 0 21453 1841/master
udp 0 0 127.0.0.1:323 0.0.0.0:* 997 16978 782/chronyd
udp 0 0 0.0.0.0:922 0.0.0.0:* 0 41344 2868/rpcbind
udp 0 0 0.0.0.0:111 0.0.0.0:* 0 41343 2868/rpcbind
udp6 0 0 ::1:323 :::* 997 16979 782/chronyd
udp6 0 0 :::922 :::* 0 41346 2868/rpcbind
udp6 0 0 :::111 :::* 0 41345 2868/rpcbindQuestion: Why I can't see the Machine B in connections ? and what shall I do to see it ?
| netstat, listing connections correctly |
ip route get is what you're looking for; maybe it's ip route show to, depending on whether you checking should be allowed to change the routing state.
See man ip-route for more details.
|
Is there a way to determine which netdev or IP link interface that a given IP address will route over … in bash/shell language?
This is not about what an IP address is, given a network device name.
Given a destination IP address, bash would automagically determine (with OS assist from its internal IP route table, netstat -i -n) in printing the network device name.
| Which interface does a specific IP address will get routed over? |
Try auditctl, it will help. Enabling below rule can flood your system so use just form debugging.
auditctl -a exit,always -S execvereference : https://linux.die.net/man/8/auditctl
|
I've noticed one of the headless computers in my network is constantly polling the VNC port on another computer. My problem is, that when I see the port from which it has connected (with tcpdump) and try to find the process with netstat -anp|grep PORT, the process is already killed and nothing is found (the process seems to live for less than a millisecond).
Is there something similar to tcpdump that would report process names & PIDs? Or some smart way of doing strace to capture the program?
| Find the short-lived process that is polling my port? |
A little bit of digging this is the stats collector. Apparently stats are posted on local loopback (aka localhost) UDP. See here: http://www.neilconway.org/talks/hacking/ottawa/ottawa_slides.pdf . Essentially the different (backend) subprocesses of PostgreSQL are using this UDP port to send statistics to the stats collector. What you are seeing is the "listening" socket waiting to receive messages.
Port 57504 is an Ephemeral port. Meaning nobody picked it, it's randomly assigned at runtime. This is noted here: https://www.postgresql.org/message-id/[emailprotected]
Note that UDP is very different to TCP because it doesn't care about connections. UDP sockets behave much more like a mailbox; accepting messages from whatever and sending wherever each one is addressed. So the remote host and remote port can often be ignored.
UDP also doesn't care about whether packets are received or not. I suspect that UDP was chosen because the backend will never wait for the stats collector even if the stats collector gets flooded.
|
$ sudo netstat -ap | grep postg
tcp 0 0 localhost:postgresql 0.0.0.0:* LISTEN 1567/postgres
udp 0 0 localhost:57504 localhost:57504 ESTABLISHED 1567/postgres
unix 2 [ ACC ] STREAM LISTENING 27116 1567/postgres /var/run/postgresql/.s.PGSQL.5432Why does postgresql server have a localhost:57504 to localhost:57504 UDP "connection"? What does that mean?
Thanks.
| Why does postgresql server have a `localhost:57504` to `localhost:57504` UDP "connection"? |
According to this page, an HTTP session starts with an HTTP request to the server and ends with the server's answer. There may be several request-answer pairs in a TCP session, but sequentially, not at the same time. So, by this definition, you should have:
number of TCP sessions >= number of HTTP sessions(it may be > because a TCP session may be kept open once the answer was received from the HTTP server)
That said, what your log file shows are no HTTP sessions. Those are application sessions. Since HTTP is a stateless protocol, your HTTP server sets a cookie in the user's browser so that when they come back, the application can continue from where it stopped. BTW, F865432C-b5wcRmaXMZhSPU0h6aDdPmiUdv8 is probably the content of the cookie set in the browser.
Each cookie corresponds to an open session. There are data associated to each cookie; they are stored on disk, on the server. To prevent the disk from filling, your HTTP server (more exactly your application) should periodically clean up its cookie jar to remove dead sessions (cookies that have not been received from a browser for a certain period of time).
So, when your application tells you there are 600+ active sessions, what it is telling you is that there are 600+ cookies and associated data on disk, not that there are 600+ simultaneous TCP connections.
If that figure grows continuously, that means that the cookies are not garbage collected: i.e. nothing is cleaning the obsolete session data on the server side.
|
I have a software that has an HTTP server listening on port 20001 and running on a Unix machine. The logfile of the HTTP server says it currently has 600+ active HTTP connections, however netstat -an | grep 20001 on the same machine where the server is running, shows that there are only 2 TCP connections currently open. The Server was provided by a different company and they are blaming our client for the big amount of HTTP sessions. I believe they are just not closing the sessions properly on their end.
As far as I know
number of active HTTP sessions = number of open TCP connections on the listening TCP port
Is this correct? If not, then when is this not the case? EDIT
Here's an example of the information that are available in the log file:
New Session F865432C-3enOjJetUTlIoBEtfYS9yNM0l+c
New Session F865432C-HJ71n4/nCda5o3WaxqlmKNUZH48
New Session F865432C-VOWUYv/wtr7QXvxGqWPFyr/JI1o
New Session F865432C-icsmvyEcsmhM0zbzPTAepfQWc4U
New Session F865432C-K+iPSJswA85YnAJNEzSa9VIdpAQ
New Session F865432C-6L5Rp+net1JEgZeX2QSiLLW9U2g
New Session F865432C-WnVQC/9ROqO50LacYDorNgB+PVk
New Session F865432C-X81QIytjaLCtLioVvqRTJYOHqtk
New Session F865432C-qIkjOoMbmr9FVWDZuZwdBA//rxs
New Session F865432C-N05q4gAjPJll6qRqxbFK09C6fNc
New Session F865432C-JC3B3mkuCnJTDFML2tTv7FPdpw8
New Session F865432C-UOGwlKaQmOawOFnBIIPRoU91GWI
New Session F865432C-Z5dWyXkfx7SsLKmujrl/3vfPYh8
New Session F865432C-w9iKm2QkDQeqZynM7hUtk/t/5Yg
New Session F865432C-uwYNGT7HcOLvuUv9F/KPCYnx3WU
New Session F865432C-b5wcRmaXMZhSPU0h6aDdPmiUdv8
New Session F865432C-I6uVQ914c7ZT+rnD5/LxA593pHg
New Session F865432C-HhUrc/IkIbM+kYXOW3sb9SqvYuo
End Session F865432C-n2VSOhW0ewjf2RnIyu2z5TkN+I8
End Session F865432C-dtvl9+4n7U+CBtS4oYAdKv4XSgM
New Session F865432C-0WCqPy9jx/ThzjoMk60wAtzRDeI
New Session F865432C-FUpkDVUqS8Zbj7CTy0Pak8/R5AE
New Session F865432C-/Nr/q60cezrsSCXaE/aJDHiAkGM
New Session F865432C-oie/wfNvpglo6UTOPNDpobkE5bI
New Session F865432C-FUO7GmbEm7gfRDmt1YRQFUgnQmg
End Session F865432C-d5jf2n9HlEheraUDu0bKR9FXb5w
End Session F865432C-d9ev8S+du/IcBr8GRyVyeWONdy4
End Session F865432C-s/d3x+vZKQ8Tnp1tHp0hfpmE6Is
End Session F865432C-xuOj1wPjVa/SFn5Sx3qvFZHW1Uo
End Session F865432C-pdZgBzd4aurZzj6it48AkA+kkbU
End Session F865432C-BW8/9/Nxp83drQh19AV96dH1SGE
New Session F865432C-2AOjAIe6lHTChy1uk2hqhM7WNRg
New Session F865432C-KkIUP6Fa0HNjyrfhfhlNvBq6Rv4
New Session F865432C-aSRpOiGNQxmW48QwanqzCQ+/ixU
New Session F865432C-KujVjcb0npH1ODXkGdLXKu70Qmo
New Session F865432C-GXB9itx4CmV9I4sUYi2y6V4qw+UAs you can no doubt notice, there are far more "New Sessions" than "End Sessions"!
| number of HTTP sessions=number of TCP Sessions? |
In case the comments to the question were not clear enough, I am adding an answer here, along with a few Pointers not mentioned in those comments.
"Why doesn't Tomcat doesn't show up when I grep netstat's output for 8080 ?"
Short Answer :
Because Port Number 8080 is getting converted to string http_alt, which will not match the grep pattern.
Details :
From https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers , we can see that Port 8080 is Officially "HTTP alternate (http_alt)—commonly used for Web proxy and caching server, or for running a Web server as a non-root user".
Basically, netstat will show "http-alt" for Port 8080 with Default Display.
When using netstat -n, the Port numbers (like 8080 for http-alt) will be shown, & you will be able to grep it. Process ID of the listening Process will be shown when running netstat with -p.
So use netstat -pa | grep http-alt or netstat -pan | grep :8080 to see the tomcat Entry.
Alternately, use lsof -P | grep :8080 which will also show the Process ID & Process Name owning the socket which is listening on Port 8080.
Here -P will prevent Port Numbers getting converted to strings (like 8080 for http-alt)
Another alternative is nmap $SERVER or namp localhost, which will show all open ports including 8080, when tomcat is running fine.
|
I am doing the following to determine if Tomcat is running:
$ whoami
voops
voops@esavo00:~/apache-tomcat-7.0.57/bin#
$ ps -ef | grep -i tomcat | grep -v grep
voops 8973 1 0 Apr22 ? 00:00:40 /usr/local/jdk1.7.0_67/bin/java -Djava.util.logging.config.file=/home/voops/apache-tomcat-7.0.57/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.endorsed.dirs=/home/voops/apache-tomcat-7.0.57/endorsed -classpath /home/voops/apache-tomcat-7.0.57/bin/bootstrap.jar:/home/voops/apache-tomcat-7.0.57/bin/tomcat-juli.jar -Dcatalina.base=/home/voops/apache-tomcat-7.0.57 -Dcatalina.home=/home/voops/apache-tomcat-7.0.57 -Djava.io.tmpdir=/home/voops/apache-tomcat-7.0.57/temp org.apache.catalina.startup.Bootstrap startMy reading of the above is that tomcat is running as a process owned by the currently logged-in user (voops). I then do a:
$ netstat -a | grep 8080.. but nothing is grepped.
My server.xml file declares the following element:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />This is what netstat -an | grep 8080 shows:
$ netstat -an | grep 8080
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN
tcp 1 0 131.176.161.23:44535 131.176.161.23:8080 CLOSE_WAIT
tcp 1 0 131.176.161.23:54600 131.176.161.23:8080 CLOSE_WAIT
tcp 1 0 131.176.161.23:51667 131.176.161.23:8080 CLOSE_WAIT
tcp 1 0 131.176.161.23:50348 131.176.161.23:8080 CLOSE_WAIT
... 5 more lines similar to the one above | Why doesn't Tomcat show up when I grep netstat's output for 8080? |
This one is per interface and I am looking per socket.Then use just netstat i.e.
uname -r
5.10type netstat
netstat is hashed (/usr/bin/netstat)netstat
TCP: IPv4
Local Address Remote Address Swind Send-Q Rwind Recv-Q State
-------------------- -------------------- ----- ------ ----- ------ -----------
localhost.53206 localhost.64711 49152 0 49191 0 TIME_WAIT
host1.ssh host2.net.16952 32767 0 49640 0 ESTABLISHED
host1.ssh host3.13515 63712 0 49232 0 ESTABLISHED
localhost.53206 localhost.64712 49152 0 49191 0 TIME_WAIT
...In case you want to relate the ports to process ids, then the opensource lsof utility is also available for Solaris. Alternatively, if losf isn't available, similar functionality should be possible using a script to combine netstat and fuser.
|
Is there a way to get a per-socket send and receive Queues utilization on Solaris similar to the way that Linux' netstat displays it?
Example on Linux:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:19072 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:19008 0.0.0.0:* LISTEN | Per Socket network Buffer queues utilization |
screen processes don’t maintain socket connections while they’re running; they open and close socket connections as needed when they have messages to send. Thus, when you run screen -r to reconnect to an existing session, it connects to the existing process using a socket, negotiates various settings, and when it’s good to go, attaches to the appropriate terminal, and closes the socket.
That means that when you run netstat, unless you happen to do so exactly when two screen processes are communicating (which doesn’t happen all that often), you won’t see an open socket connecting two screen processes.
|
From https://unix.stackexchange.com/a/485290/674Further down in the netstat output is UNIX sockets:
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags Type State I-Node PID/Program name Path
<snip>
unix 2 [ ACC ] STREAM LISTENING 21936 1/systemd /run/dbus/system_bus_socket
<snip>
unix 3 [ ] STREAM CONNECTED 28918 648/dbus-daemon /run/dbus/system_bus_socketWe can see that both of these processes are using the UNIX socket at
/run/dbus/system_bus_socket. So if you knew one of the processes,
looking at this, you should be able to determine the other end.Does that mean any pair of server and client processes based on Unix domain socket should appear in the output of netstat like the one above? In other words, should netstat always show both server and client processes?
GNU Screen also runs as server and client processes based on Unix domain socket, so should they appear in the output of netstat? Why does netstat in fact not show Screen client but only Screen server process like the one below,
$ sudo netstat -ap | grep -i screen
unix 2 [ ACC ] STREAM LISTENING 4533106 27525/SCREEN /run/screen/S-t/27525.testwhile ps shows both?
$ ps aux | grep -i screen
t 19686 0.0 0.0 45096 3292 pts/7 S+ 22:19 0:00 screen -r test
t 27525 0.0 0.0 45780 3292 ? Ss 07:22 0:00 SCREEN -S testThanks.
| Why doesn't `netstat` show Screen client but only Screen server process? |
The raw socket is opened only to read information like statistics from the netatop kernel module, using getsockopt() (eww). There is no code to read or write raw packets with this socket.
https://github.com/Atoptool/atop/blob/v2.3.0/netatopif.c
|
I install atop on Debian 9. It runs as a monitoring daemon.
Why is it listening on a raw socket? Raw sockets are used to generate arbitrary IPv4 packets or capture all packets read all packets for a given IP sub-protocol! But I don't think my atop and its logs show any information from reading packets. I don't even use netatop - and that would require a kernel module, which is not included in Debian. And I would be extremely surprised if any of the atop features involve sending raw IP packets.
$ sudo netstat -l --raw -ep
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program name
raw 0 0 0.0.0.0:255 0.0.0.0:* 7 root 2427667 7353/atop$ sudo ss -l --raw -p
State Recv-Q Send-Q Local Address:Port Peer Address:Port
UNCONN 0 0 *:ipproto-255 *:* users:(("atop",pid=7353,fd=4)) | Why does atop open a raw socket? |
Using awk:
netstat -an | grep ':25' | grep -v '127.0.0.1\|::1' | wc -l | awk '{if($0==0) print "compliant"; else print "non-compliant"}'will print complaint if output $0 is 0
else print non-complaint |
My goal is to ensure that email connections are limited to outbound only
So I have two shell commands one is
netstat -an | grep ':25' | grep -v '127.0.0.1' | wc -lwhich prints out 1
The command up above is finding all instances of port 25 besides localhost but does not exclude ipv6
The other command is
netstat -an | grep ':25' | grep -v '127.0.0.1\|::1' | wc -lwhich prints out 0
This command up above is finding all instances of port 25 and excluding localhost and ipv6
I need an if else that compares the two and says if it comes back 0 print out compliant else print out non-compliant
What is the best approach in doing that through either ansible or shell?
| Using a if/else statement in shell for netsat |
The part after the colon is the port number, and it's not always displayed as a number since there's a list of well-known ports uses in /etc/services, so you don't have to remember if 22 is ssh or telnet. (The reverse works as well – you can say telnet localhost http and it will understand http as meaning "port 80".) The netstat option --numeric-ports will turn this off.
As to the IPs, it's possible that you've just looked at a point in time where most connections are indeed to your own machine. netstat will do a reverse lookup to determine a more human-friendly name to display, and localhost is usually hardcoded in /etc/hosts as the name for 127.0.0.1. The netstat option --numeric-hosts will turn this off.
|
I never learned network programming and this kind of stuff properly.
Only know very basic stuff like IP address and just a vague concept of what ports and TCP/IP are.
Here, I connected to my lab's server:and I just got curious about this whole network stuff and tried command netstat
I understand that these are lists of all ports that are on/off on the server.
One thing I don't get is why the 'foreign address' part are shown as 'localhost:xxxxx'
and not something like '101.239.49.1' for the ports that are 'ESTABLISHED'
Also could you explain what the 'x11-ssh-offset' means?
I'm guessing that this port is used for ssh communication with other computers.
why on earth is it called 'offset'?
P.S. Would be great if you could give me some keywords that would help me get in the right direction to study such issues.
| Why is the 'foreign address' not IP address but something like this? |
According to netstat/unix.c those fields are coming from unp->unp_refs and unp->unp_nextref as defined in sys/unpcb.h:
/*
* A socket may be referenced by a number of sockets (e.g. several
* sockets may be connected to a datagram socket.) These sockets
* are in a linked list starting with unp_refs, linked through
* unp_nextref and null-terminated. Note that a socket may be referenced
* by a number of other sockets and may also reference a socket (not
* necessarily one which is referencing it). This generates
* the need for unp_refs and unp_nextref to be separate fields.
*\ struct unpcb *unp_refs; /* referencing socket linked list */
struct unpcb *unp_nextref; /* link in unp_refs list */ |
On old 43BSD...
netstat -f unix
Active UNIX domain sockets
Address Type Recv-Q Send-Q Inode Conn Refs Nextref Addr
801ca38c dgram 0 0 8008b5c0 0 0 0 /dev/log
801cc10c stream 0 0 8008e690 0 0 0 /dev/printerAddress #socket address
type #type: stream or dgram
Inode #Inode?
Conn #sockets connections
Refs #?
Nextref #?
Addr #socket fileAnyone know what does it mean "Refs" and "Nextref".
As I know Refs is referred to routing, but in sockets there is no routing as I know.
| Old 43BSD and netstat output |
For a normal user that's normal behavior. To be able to associate the socket to a process, at some point, /proc/<pid>/fd/ must be read by ss. Only the same user or a privileged process (including running as root) has access to this.
Here's an strace excerpt about what is happening outside of Docker.
# runuser -u test -- sh -c 'echo $$; exec socat tcp4-listen:5555,reuseaddr -'
445406and beside:
user@host$ strace ss -tlnp sport == 5555 2>&1 |egrep -w '445406|^LISTEN'
openat(AT_FDCWD, "/proc/445406/attr/current", O_RDONLY|O_CLOEXEC) = 4
openat(AT_FDCWD, "/proc/445406/fd/", O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_DIRECTORY) = -1 EACCES (Permission denied)
LISTEN 0 5 0.0.0.0:5555 0.0.0.0:* The unconstrained root user wouldn't get EACCESS, would have access to needed information and would be able to display the PID in the end.
But Docker doesn't run as normal root user: some capabilities (a capability is a piece of root "powers". root by default has all of them) were removed. And because of this root in the container gets the same error as a normal user, doesn't have access to the needed information to associate the socket to a process.
root@1589d8b38814:/# apt install libcap2-bin
[...]
oot@1589d8b38814:/# cat /proc/$$/status|grep ^Cap
CapInh: 00000000a80425fb
CapPrm: 00000000a80425fb
CapEff: 00000000a80425fb
CapBnd: 00000000a80425fb
CapAmb: 0000000000000000
root@1589d8b38814:/# capsh --decode=00000000a80425fb
0x00000000a80425fb=cap_chown,cap_dac_override,cap_fowner,cap_fsetid,
cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,
cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcapWhile the actual root user or when running the Docker container in privileged mode (--privileged):
root@cce7fc1de1c3:/# cat /proc/$$/status |grep ^Cap
CapInh: 0000003fffffffff
CapPrm: 0000003fffffffff
CapEff: 0000003fffffffff
CapBnd: 0000003fffffffff
CapAmb: 0000000000000000
root@cce7fc1de1c3:/# capsh --decode=0000003fffffffff
0x0000003fffffffff=cap_chown,cap_dac_override,cap_dac_read_search,
cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,
cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,
cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,
cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,
cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,
cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,
cap_mac_override,cap_mac_admin,cap_syslog,cap_wake_alarm,
cap_block_suspend,cap_audit_readMuch more.
Here dropping cap_sys_ptrace (which affects access in /proc) is enough to derail it. Note that an unprivileged Docker container doesn't give cap_sys_ptrace to its root user.
With socat running as nobody with pid 392 and a privileged docker root user beside:
root@df29c4a57b3f:/# capsh --inh= --caps= -- -c 'ss -tlnp sport == 5555'
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 5 0.0.0.0:5555 0.0.0.0:* users:(("socat",pid=392,fd=5))
root@df29c4a57b3f:/# capsh --drop=cap_sys_ptrace --inh= --caps= -- -c 'ss -tlnp sport == 5555'
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 5 0.0.0.0:5555 0.0.0.0:* |
Is it normal behavior, or a bug, that when I run ss -nltp, I only see the process/pid information if the user I am running ss -nltp as is the same user as the listening process?
$ docker run -it --rm tianon/network-toolbox
root@bc058746626a:/# apt update
...
root@bc058746626a:/# apt install gosu
...
root@bc058746626a:/# nc -l 4444
[... check ss in another terminal]
^C
root@bc058746626a:/# gosu nobody nc -l 4444
....$ docker exec -it admiring_keller bash
$ # both running as root
root@bc058746626a:/# ss -nltp
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 1 0.0.0.0:4444 0.0.0.0:* users:(("nc",pid=325,fd=3))
$ # process running as nobody, ss as root
root@bc058746626a:/# ss -nltp
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 1 0.0.0.0:4444 0.0.0.0:*
$ # process still as nobody , ss as nobody
root@bc058746626a:/# gosu nobody ss -nltp
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 1 0.0.0.0:4444 0.0.0.0:* users:(("nc",pid=343,fd=3))
root@bc058746626a:/# exit
$ # process still as nobody , ss as nobody
$ docker exec -it --user nobody admiring_keller bash
nobody@bc058746626a:/$ ss -nltp
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 1 0.0.0.0:4444 0.0.0.0:* users:(("nc",pid=343,fd=3))
nobody@bc058746626a:/$ ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 4764 4124 pts/0 SNs 16:42 0:00 bash --login -i
nobody 343 0.0 0.0 3204 864 pts/0 SN+ 16:45 0:00 nc -l 4444
nobody 369 0.0 0.0 3872 3152 pts/1 SNs 16:50 0:00 bash
nobody 377 0.0 0.0 7644 2708 pts/1 RN+ 16:54 0:00 ps auxRelated: https://stackoverflow.com/questions/68085747/why-would-a-process-not-be-associated-with-a-port-when-using-gosu
| iproute2 ss - not showing process/pid information if user is not the same user as listening process? |
Using lsof command. Usage:
sudo lsof -ni tcp | grep <port>
And the 2nd column is PID.
|
My loacl server IP is 192.168.122.100, and remote server IP is 192.168.122.50. I need to kill all processes which connect to 192.168.122.50:56666. By executing ss comand, I found there are three TCP connections has been established. But I don't konw which process are using these sockets. How can I find out the PID of these socket?
Thank you in advance!
| How can I confirm which process is connect to remote port? |
Listing the open files with -i should show you the ports in use
lsof -iIf there's too much output
lsof -i | grep squidWorks with Linux & OS X
|
I've recently starting playing around with the Squid caching server on my OS X based computer. I'm curious if there's a way to tell which port Squid is running on using netstat or other standard unix commands.
That is, I know Squid runs by default on port 3128, but if I didn't know this or someone had started Squid listening on a different port via a configuration file I couldn't access or find, would there be a way to determine which port is was listening on.
Some rudimentary googling turning up the following netstat command for machines running Linux
$ netstat -plantBut running this on OS X threw an error
$ netstat -plant
netstat: lant: unknown or uninstrumented protocolI assume this is some BSD/Linux difference, but not knowing my networking well enough, I don't have the ability to figure out what the correct BSD invocation would be.
OS 10.10 if that matters.
| What Port is Squid Running on in OS X/BSD |
First, the etime field indicates when the process is started. This does not necessarily means that a connection is bound to it for that time.
Next, maybe that some network address translation is being used? If so, please grep for the portnumber on the remote host: netstat -natup|grep 40740 to see what that returns.
|
On the first host,
root@xxx:~# netstat -natup | grep xxx
tcp 0 0 10.2.5.3:40740 xxx:10051 ESTABLISHED 1482/zabbix_proxy:we can see that a connection has been established with the remote host.
root@xxx:~# ps -eo uid,pid,etime | grep 1482
106 1482 18-17:10:17The connection has been established for what appears to be ~18 days. When I SSH to the remote host and run:
root@xxx:~# netstat -natup | grep 10.2.5.3there are absolutely no entries at all!
How is this possible?
| Asymmetric ESTABLISHED session in netstat |
netstat itself does not support such filtering.
You probably have to do something like:
sudo netstat -lp --inet | grep " $pid/" |
How can I have the following command below just show/filter based on the PID's I'm looking for?
sudo netstat -lp --inetThe results come back as this
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 *:1508 *:* LISTEN 7609/kodi.bin
tcp 0 0 *:38565 *:* LISTEN 18079/Plex Plug-in
tcp 0 0 *:59240 *:* LISTEN 24656/Plex Plug-in
tcp 0 0 *:46185 *:* LISTEN 18427/Plex Plug-in
tcp 0 0 *:netbios-ssn *:* LISTEN 989/smbd
tcp 0 0 *:34061 *:* LISTEN 25066/Plex Plug-in
tcp 0 0 *:59310 *:* LISTEN 18190/Plex Plug-in
tcp 0 0 *:50383 *:* LISTEN 18243/Plex Plug-in
tcp 0 0 *:48336 *:* LISTEN 18081/Plex Plug-in
tcp 0 0 *:32400 *:* LISTEN 17990/Plex Media Se
tcp 0 0 *:1136 *:* LISTEN 7609/kodi.bin
tcp 0 0 localhost:http-alt *:* LISTEN 21149/syncthing I just want the lines with the PID 7609/kodi.bin in them. so the final output would look like the example below.
tcp 0 0 *:1508 *:* LISTEN 7609/kodi.bin
tcp 0 0 *:1136 *:* LISTEN 7609/kodi.bin | How to do a netstat that will only filter based on pid |
Is there a service running on that port after you've opened it? The command netstat -tulpn | less will only show you the ports of daemons that are actually listening on TCP ports.
Example
Nothing's initially running:
$ sudo netstat -tulpn | grep :80
$Start up Apache:
$ sudo /etc/init.d/httpd start
Starting httpd: [ OK ]
$Check again:
$ sudo netstat -tulpn | grep :80
tcp 0 0 :::80 :::* LISTEN 31260/httpd Now we see it. Stop the service:
$ sudo /etc/init.d/httpd stop
Stopping httpd: [ OK ]
$Now it's gone again.
$ sudo netstat -tulpn | grep :80
$ |
I'm trying top open a port on my CentOS machine:
I edit the /etc/sysconfig/iptables file and add my rule:
-A INPUT -p TCP -m state --state NEW -m tcp --dport 143 -j ACCEPTThen I restart the iptable service
# service iptables restartBut when I'm checking the open ports the one I declared doesn't appear
netstat -tulpn | less | Open a port in my CentOS |
Probably, you need to add appropriate route table entries to reach local intranet server via 10.131.60.1, not via ppp0. Consult with your system administrator if you don't know exactly which addresses should be accessed via local gateway.
|
I've got a corporate VPN, which I use to access the Internet. When it's on, I cannot reach the servers inside the corporate network anymore, so I think there are some problems with the gateway setup. Here is the netstat -rn output when the VPN is turned off:
Destination Gateway Genmask Flags MSS Window irtt Iface
91.218.225.31 10.131.60.1 255.255.255.255 UGH 0 0 0 eth1_rename
10.131.60.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1_rename
169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth1_rename
0.0.0.0 10.131.60.1 0.0.0.0 UG 0 0 0 eth1_renameHere it is with the VPN turned on:
Destination Gateway Genmask Flags MSS Window irtt Iface
10.7.4.0 0.0.0.0 255.255.255.255 UH 0 0 0 ppp0
91.218.225.31 10.131.60.1 255.255.255.255 UGH 0 0 0 eth1_rename
91.218.225.31 10.131.60.1 255.255.255.255 UGH 0 0 0 eth1_rename
10.131.60.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1_rename
169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth1_rename
0.0.0.0 0.0.0.0 0.0.0.0 U 0 0 0 ppp0ppp0 is the VPN device.
How can I make both the Internet and LAN routing work when the VPN is enabled?
| VPN and gateway problems |
There are two or three separate problems.
dynamic gw IP
It would be overkill to use a routing protocol for this (unless you are using one already for other reasons). I would try to change the configuration of gw/eth0 to static. If that is not possible then you could create a user gw on hostA which gets sudo permission for setting the route to that network. Every time gw gets a new IP it could connect via SSH to hostA and run that command (maybe via ForcedCommand).
routing on gw
Routing is not configured (correctly) on gw. You must enable it at all via net.ipv4.ip_forward = 0 (man sysctl) and allow the respective connections in the firewall, see iptables -nvL FORWARD.
routing on the VMs in 192.168.3.0
The VMs which are connected to gw/eth1 must have gw configured as default gateway. If that is not the case then gw must do SNAT towards this network (iptables).
|
Having the following topology:
hostA(virbr0: 192.168.122.1) -- TAP interface -- (eth0: 192.168.122.85) gw (eth1: 192.168.3.51) --- (LAN: 192.168.3.0/24)
gw : QEMU VM Guest, that is acting as a gateway for other QEMU VM Guests, which are connected to it via eth1 interface. gw is connected to the QEMU Host via the Linux TAP Interface, using interface eth0. The TAB Interface is assigning IP to the eth0 dynamically.
hostA : QEMU VM Host
root@hostA:~$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.16.254.134 netmask 255.255.255.0 broadcast 172.16.254.255
inet6 fe80::20c:29ff:fe25:1670 prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:25:16:70 txqueuelen 1000 (Ethernet)
RX packets 18116 bytes 1361094 (1.3 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 14579 bytes 5334119 (5.3 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0gns3tap0-0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet6 fe80::50bd:d3ff:fe1a:e55 prefixlen 64 scopeid 0x20<link>
ether 52:bd:d3:1a:0e:55 txqueuelen 1000 (Ethernet)
RX packets 353 bytes 28543 (28.5 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 3348 bytes 183399 (183.3 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 662311 bytes 99203163 (99.2 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 662311 bytes 99203163 (99.2 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0virbr0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255
ether 52:54:00:62:0a:c5 txqueuelen 1000 (Ethernet)
RX packets 353 bytes 23601 (23.6 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 379 bytes 28629 (28.6 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0gw:~# ifconfig
eth0 Link encap:Ethernet HWaddr 0C:FE:27:0C:E4:00
inet addr:192.168.122.85 Bcast:192.168.122.255 Mask:255.255.255.0
inet6 addr: fe80::efe:27ff:fe0c:e400/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:379 errors:3150 dropped:0 overruns:0 frame:3150
TX packets:353 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:31851 (31.1 KiB) TX bytes:28543 (27.8 KiB)eth1 Link encap:Ethernet HWaddr 0C:FE:27:0C:E4:01
inet addr:192.168.3.51 Bcast:0.0.0.0 Mask:255.255.255.0
inet6 addr: fe80::efe:27ff:fe0c:e401/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:302 errors:0 dropped:0 overruns:0 frame:0
TX packets:300 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:25796 (25.1 KiB) TX bytes:24782 (24.2 KiB)
gw:~# netstat -nr
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
0.0.0.0 192.168.122.1 0.0.0.0 UG 0 0 0 eth0
192.168.3.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1
192.168.122.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0The goal to have a reachability from hostA to the VMs of the internal LAN, 192.168.3.0/24
The following routing configuration is working:
root@hostA:~$ sudo route add -net 192.168.3.0 netmask 255.255.255.0 gw 192.168.122.85
root@hostA:~$ netstat -nr
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
0.0.0.0 172.16.254.2 0.0.0.0 UG 0 0 0 eth0
172.16.254.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 docker0
192.168.3.0 192.168.122.85 255.255.255.0 UG 0 0 0 virbr0
192.168.122.0 0.0.0.0 255.255.255.0 U 0 0 0 virbr0
root@hostA:~$ ping 192.168.3.102
PING 192.168.3.102 (192.168.3.102) 56(84) bytes of data.
64 bytes from 192.168.3.102: icmp_seq=1 ttl=63 time=3.07 ms
^C
--- 192.168.3.102 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 3.071/3.071/3.071/0.000 ms
root@hostA:~$ ping 192.168.3.103
PING 192.168.3.103 (192.168.3.103) 56(84) bytes of data.
64 bytes from 192.168.3.103: icmp_seq=1 ttl=63 time=3.03 ms
64 bytes from 192.168.3.103: icmp_seq=2 ttl=63 time=2.99 ms
^C
--- 192.168.3.103 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
rtt min/avg/max/mdev = 2.997/3.014/3.032/0.057 msHowever, since, the Linux TAP is assigning the IPs to the eth0 dynamically, it is needed to have the route, that will not use the IP Address of the next router as the next hop, but, the local IP of the exit interface, similar to the following:root@hostA:~$ route add -net 192.168.0.0 netmask 255.255.0.0 gw 192.168.122.1 dev virbr0
root@hostA:~$ netstat -nr
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
0.0.0.0 172.16.254.2 0.0.0.0 UG 0 0 0 eth0
172.16.254.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 docker0
192.168.0.0 192.168.122.1 255.255.0.0 UG 0 0 0 virbr0
192.168.122.0 0.0.0.0 255.255.255.0 U 0 0 0 virbrroot@hostA:~$ ping -c 1 192.168.122.85
PING 192.168.122.85 (192.168.122.85) 56(84) bytes of data.
64 bytes from 192.168.122.85: icmp_seq=1 ttl=64 time=0.585 ms--- 192.168.122.85 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.585/0.585/0.585/0.000 ms
root@hostA:~$ ping -c 1 192.168.3.51
PING 192.168.3.51 (192.168.3.51) 56(84) bytes of data.
64 bytes from 192.168.3.51: icmp_seq=1 ttl=64 time=0.956 ms--- 192.168.3.51 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.956/0.956/0.956/0.000 msroot@hostA:~$ ping -c 1 192.168.3.102
PING 192.168.3.102 (192.168.3.102) 56(84) bytes of data.
From 192.168.122.1 icmp_seq=1 Destination Host Unreachable--- 192.168.3.102 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0msroot@hostA:~$ ping -c 1 192.168.3.103
PING 192.168.3.103 (192.168.3.103) 56(84) bytes of data.
From 192.168.122.1 icmp_seq=1 Destination Host Unreachable--- 192.168.3.103 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0msAs seen, when using above route configuration, the hostA is able to reach the eth1 interface, but, not able to reach any other VMs in the internal LAN (192.168.3.0/24). However, the internal LAN hosts itself are able to reach the hostA.
Here is the iptables configs:
root@hostA:~$ sudo iptables -nvL FORWARD
Chain FORWARD (policy ACCEPT 21 packets, 1624 bytes)
pkts bytes target prot opt in out source destination
197 15616 DOCKER-USER all -- * * 0.0.0.0/0 0.0.0.0/0
197 15616 DOCKER-ISOLATION-STAGE-1 all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- * docker0 0.0.0.0/0 0.0.0.0/0 ctstate RELATED,ESTABLISHED
0 0 DOCKER all -- * docker0 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- docker0 !docker0 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- docker0 docker0 0.0.0.0/0 0.0.0.0/0
88 7346 ACCEPT all -- * virbr0 0.0.0.0/0 192.168.122.0/24 ctstate RELATED,ESTABLISHED
88 6646 ACCEPT all -- virbr0 * 192.168.122.0/24 0.0.0.0/0
0 0 ACCEPT all -- virbr0 virbr0 0.0.0.0/0 0.0.0.0/0gw:~# iptables -nvL FORWARD
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 ACCEPT all -- eth1 eth0 192.168.122.0/24 0.0.0.0/0 ctstate NEW
0 0 ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0 ctstate RELATED,ESTABLISHED
gw:~# sysctl -a | grep ipv4.ip_forward
net.ipv4.ip_forward = 1dns:~# ifconfig
eth0 Link encap:Ethernet HWaddr 0C:FE:27:0C:76:00
inet addr:192.168.3.103 Bcast:0.0.0.0 Mask:255.255.255.0
inet6 addr: fe80::efe:27ff:fe0c:7600/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:18638 errors:0 dropped:0 overruns:0 frame:0
TX packets:18634 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1543312 (1.4 MiB) TX bytes:1705846 (1.6 MiB)dns:~# netstat -nr
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
0.0.0.0 192.168.3.51 0.0.0.0 UG 0 0 0 eth0
192.168.3.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0Questions:Is there something missing for the configuration?Is there a way to configure the working route entry, that will use the local IP of the exit interface, as the next-hop IP? | Configure static routing for the virbr0 using local interface as next hop |
For Solaris you can use pfiles <pid> to see which network ports are opened by a certain process. Using a for-loop on /proc/* you can use pfiles on each running process to lookup the port you are after. Drawback is that you will need to be root on Solaris 10, or be able to become privileged (pfexec pfiles) on Solaris 11 to get the info.
If you are able to become root on the Solaris host you should be able to use something like:
PORT=22; for PID in /proc/*; do pfiles ${PID} |grep "port: ${PORT}" && echo ${PID}; doneThis will iterate through /proc/*, filter for the specified port and if a match is found, the process ID (/proc/####) is shown on the next line.
|
I'm diagnosing an old Solaris 10 build and during port scans I've found an open port that's not on the approved list for this server.
I've tried various combinations of netstat switches but I can't seem to get the right output that gives me the associated service name or PID of the open port.
The feature set of netstat on this build seems to be limited compared to later solaris versions and other unix operating systems. netstat -tulpn for example doesn't work.
I also can't install lsof due to security restrictions.
Any ideas?
| Solaris 10 - Find service attached to listening port |
How (where) can I find out information about them, First you have to find out which program is bound to each port. Unfortunately, there is no single standard way to do that which will work on all *ix type systems, and your question doesn't specify one.
Some versions of netstat have a flag which will include the associated program name on each output line. For instance, --program in Linux or -b on Windows.
If your netstat doesn't have such a flag (e.g. OS X), you will have to find another method that works on your system. lsof -i, /proc spelunking, etc.what is their purpose in the system Once you have the program name in hand, man progname will usually give you enough information to answer that question yourself.[can I] kill them? You will figure that out once you know what each server is doing.
A single answer here is not the right place for a list of all the things you can kill. There are simply too many possibilities. If you're unsure about a given program after reading its documentation, you can post another question here asking about it. Some things are fairly obvious (e.g. sshd), others more obscure (e.g. avahi).Which of them can be insecure and which are safe?It's rare for a program to be running by default on a new *ix system which is absolutely insecure.
(In the bad old days, that wasn't the case. You'd often see systems running telnetd, non-chrooted ftpd, the r* commands...)
Any non-default background TCP listener should be something you or another trusted admin installed, so presumably you've already come to grips with any safety concerns.
There are gray areas here. You might have a server running which is not absolutely insecure, but which is conditionally insecure. Maybe it's not locked down properly, maybe it has unpatched bugs, etc. That's the stuff of entire computer security careers, though, not something suitable for answering here in a single question. Lacking that experience, Google is probably your best first resort. If you don't find what you need there, you can post a new question here about a particular server.
|
In the output of
netstat -a | grep LISTENthere are usually a lot of processes. How (where) can I find out information about them, what is their purpose in the system and if I can kill them? Which of them can be insecure and which are safe?
| How can I identify processes that use network facilities, and can they be killed? |
You machine is listening to port 22. Here's the line:
tcp6 0 0 :::22 :::* LISTEN The socket is listening for both IPv6 and IPv4 connections.
|
I am able to ssh to the machine.
But my machine not shown as listening on port 22.
Below is what I see.
It show as listening on port 53, 21, 8080, 8443 etc. But no entry for 22(ssh).
My machine IP is 10.8.113.30. OS is windriver linux.
Why is this?
netstat -antu | grep LISTEN
tcp 0 0 127.0.0.1:8083 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:8084 0.0.0.0:* LISTEN
tcp 0 0 10.8.113.30:8021 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:8021 0.0.0.0:* LISTEN
tcp 0 0 10.8.113.30:21 0.0.0.0:* LISTEN
tcp 0 0 10.8.113.30:53 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:53 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:3128 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:953 0.0.0.0:* LISTEN
tcp 0 0 10.8.113.30:8443 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:8123 0.0.0.0:* LISTEN
tcp 0 0 10.8.113.30:8128 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:8128 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:25255 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:5000 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:5001 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:6379 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:5580 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:5581 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN
tcp 0 0 10.8.113.30:8080 0.0.0.0:* LISTEN
tcp 0 0 10.8.113.30:81 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:81 0.0.0.0:* LISTEN
tcp6 0 0 ::1:8021 :::* LISTEN
tcp6 0 0 :::53 :::* LISTEN
tcp6 0 0 :::22 :::* LISTEN
tcp6 0 0 :::3128 :::* LISTEN
tcp6 0 0 ::1:8128 :::* LISTEN
tcp6 0 0 127.0.0.1:18081 :::* LISTEN
tcp6 0 0 :::80 :::* LISTEN
tcp6 0 0 ::1:81 :::* LISTEN | Netstat doesn't show my machine IP as listening on port 22 |
Give this tested version a try:
netstat -tn 2>/dev/null | awk '/:80 / {print $5}' | sed 's/.*::ffff://' | sed 's/:.*//' | sor t | uniq -c | sort -nr |\
while read index ipaddress ; do \
printf "%s " "${index}" ;\
getent hosts "${ipaddress}" ;\
if [ $? -eq 2 ]; then \
printf "%s\n" "${ipaddress}" ;\
fi ;\
doneIt is using the standard getent to query the hosts database in order to retrieve the hostname given its ip address.
The test:
5 81.133.113.200 host81-133-113-200.in-addr.btopenworld.com
4 80.229.142.126 garnerhome.plus.com
2 94.136.36.29 mail.e-trackit.co.uk
2 92.19.231.69 host-92-19-231-69.static.as13285.net
2 85.159.56.230
2 83.70.246.152 83-70-246-152-dynamic.b-ras1.prp.dublin.eircom.net
2 81.131.118.236 host81-131-118-236.range81-131.btcentralplus.com
2 185.106.92.42
1 92.19.232.88 host-92-19-232-88.static.as13285.net
... |
I'm using netstat to collect information about connected IP's. And I have the following format:
netstat -tn 2>/dev/null | awk '/:80 / {print $5}' | sed 's/.*::ffff://' | sed 's/:.*//' | sor t | uniq -c | sort -nr
5 81.133.113.200
4 80.229.142.126
2 94.136.36.29
2 92.19.231.69
2 85.159.56.230
2 83.70.246.152
2 81.131.118.236
2 185.106.92.42
1 92.19.232.88
1 86.47.113.169
1 86.168.206.46
1 79.77.175.210
1 46.19.141.238
1 206.221.184.2
1 192.198.95.6What I was trying to accomplish is to match an IP to a hostname.
So if i have name=$(IPADDRESSNAME) stored somewhere and name matches ip address 81.133.113.200
I would like it to print in a format like that:
5 81.133.113.200 - IPADDRESSNAME
4 80.229.142.126
2 94.136.36.29
2 92.19.231.69I have been reading column to try and do this, But I am unsure how to combine both column with a match on the address.
I am running this from with a Bash script, So I would be storing the hostnames in there.
I was thinking something like:
string=$(netstat -tn 2>/dev/null | awk '/:80 / {print $5}' | sed 's/.*::ffff://' | sed 's/:.*//' | sort | uniq -c | sort -nr)
if [[ $string == "81.133.113.200" ]]
then
echo "Its XXXXXXXX HOST";
fiSomething kind of like this, Although this does not work, The logic is what am after but in-line.
| Bash: How to print additional column matching IP Address to Name |
The output is truncated, that was a connection to proxy14.fedoraproject.org, probably for an automated check for updates.
ss -rtwould show you the full host name.
|
To get to this point I had a Fedora workstation 34 install- iso about a week old - ran update, rebooted, click Install Fedora 35 as it was on offer from gnome Software. Hadn't even opened Firefox yet. Didn't install anything else.
I ran netstat just to see what was happening by default.
There were a couple established connections to Cloudflare addresses which had no additional whois info to go on, ok
and one to an oscp-router.gno (assuming thats Gnome extensions),
But this one really stands out:
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 25 0 fedora:58440 proxy14.fedorapro:https CLOSE_WAITWhy did Fedora connect to proxy14.fedorapro ?
I can't find any information about this. fedorapro.com is a parked domain.
| Fresh Fedora 35 - what are these active internet connections doing? |
It's likely that one of the ports from the 720 list was simply removed in-between those runs; there should be no substantive difference in the number of outputs with or without -n.
You're seeing different output with the grep 2049 because the -n flag specifically shows "numerical addresses instead of trying to determine symbolic host, port names"; if you had grepped for ":nfs" instead of "2049" in the second example, you would have seen corresponding results.
|
man netstat says--numeric, -n
Show numerical addresses instead of trying to determine symbolic host,
port or user names.Does netstat output additional sockets with -n than without -n?
Or does netstat output the same set of sockets with -n as without -n?
They don't seem to output the same set of sockets:
$ sudo netstat -ap | wc -l
720
$ sudo netstat -anp | wc -l
719-n seems to output sockets not shown otherwise:
$ sudo netstat -ap | grep 2049
$ sudo netstat -anp | grep 2049
tcp 0 0 0.0.0.0:2049 0.0.0.0:* LISTEN -
tcp6 0 0 :::2049 :::* LISTEN -
udp 0 0 0.0.0.0:2049 0.0.0.0:* -
udp6 0 0 :::2049 :::* | Does `netstat` output different sockets with and without -n? |
A simple ps shows only your own processes, not system processes or other users' processes. ps allows options to show more processes, e.g. ps ax or ps -e or ps -A.
ps -a doesn't show the process systemd-resolve because it's not associated with a terminal. See man ps for details.
|
I have a machine in my organization that I sshed and received a terminal.
When I run netstat -ntlp I received:
[root@webtl1 ~]# netstat -ntlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:5355 0.0.0.0:* LISTEN 527/systemd-resolve
tcp6 0 0 :::5355 :::* LISTEN 527/systemd-resolve
tcp6 0 0 :::22 :::* LISTEN 1/systemd When I run ps -a I received:
[root@webtl1 ~]# ps -a
PID TTY TIME CMD
1165 pts/0 00:00:00 ps I don't see the process systemd-resolve.
But if I run ps -p 527 I do see it:
[root@webtl1 ~]# ps -p 527
PID TTY TIME CMD
527 ? 00:00:00 systemd-resolve Why I don't see it with ps -a ?
| Process appear by "netstat" but doesn't appear by "ps -a" |
xlsclients is a simple application which is listing the WM_CLIENT_MACHINE and WM_COMMAND properties set on top windows (ie. windows which are children of the root window or have a WM_STATE property).
That's about everything that it does. There's no magic.
For instance, I'm using my own window manager which has opened an InputOnly (invisible) window as child of the root window, to use it for ewmh's wm check. If I set those two properties on it, the expected thing will happen ;-)
$ xprop -id 0x400001 -f WM_CLIENT_MACHINE 8s -set WM_CLIENT_MACHINE kgbvax
$ xprop -id 0x400001 -set WM_COMMAND /sbin/reboot
$ $ xlsclients
kgbvax /sbin/reboot
...But to answer your question:how do a terminal emulator process and a window manager (e.g. openbox) process communicate? Is a terminal emulator process a client of a window manager process, based on Unix domain socket?They're both clients of the X11 server, and they usually communicate by sending client messages with XSendEvent(3) and setting properties on windows. The protocol is described in icccm and ewmh. Notice that a client does not "have" a window; any client can do any operation on any window, including but not limited to setting and getting any property off it.
| In APUE (see the figure below), how do a terminal emulator process and a window manager
(e.g. openbox) process communicate? Is a temrinal emulator process
a client of a window manager process, based on Unix domain socket?
What is the relation of X server process to a terminal emulator process and a window manager process? Specifically:
xlsclients output contains lxterminal. Does that means that a
terminal emulator process is a client of X server?
$ xlsclients -a | grep -i lxterminal
ocean lxterminalxlsclients output doesn't contain a window manager process. Does that means that a window manager process is not a client of X server?
$ xlsclients -a | grep -i openbox
$ | What is the server-client relationship between a terminal emulator, a window manager and a X server processes? |
Whenever you do not recognize a port by name, you can grep for the name in /etc/services to see that the name is defined there. On my Linux systems, smakynet is TCP/UDP 122.
grep smakynet /etc/servicesUse man netstat to learn about which switches can be used to reveal more information. In this case, use switches that will help find more information about process IDs.
netstat -tulpn | grep smakynetNow you can see which process uses the port. You will get output like the following example.
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN 1565/cupsdAbove, cupsd was opened with PID 1565; it is using TCP port 631.
This should help to identify which program is using the port. I do not know why smakynet is listed in /etc/services; though, to hazard a guess, it could be an ancient protocol or perhaps it was registered with IANA and never developed.
So, which program did you find that uses the smakynet port on which O/S?
|
after logging into a server, I used netstat to check out the ports of this server and wanted to find which port was communicating with me
My IP is 143.248.143.198 and my search results are like below:
[kwagjj@James5 ~]$ netstat | grep 143.248.143.198
tcp 0 52 James5:smakynet 143.248.143.198:49690 ESTABLISHED
[kwagjj@James5 ~]$ netstat | smakynet
smakynet: Command not found.
[kwagjj@James5 ~]$ netstat | grep smakynet
tcp 0 0 James5:smakynet 143.248.143.199:49573 ESTABLISHED
tcp 0 0 James5:smakynet 143.248.143.198:49690 ESTABLISHED
tcp 0 0 James5:smakynet 143.248.143.212:51070 ESTABLISHED
tcp 0 0 James5:smakynet 143.248.143.210:9693 ESTABLISHED
tcp 0 0 James5:smakynet 143.248.143.217:azeti ESTABLISHED
tcp 0 0 James5:smakynet 143.248.143.216:51892 ESTABLISHED
tcp 0 0 James5:smakynet 143.248.143.210:10599 ESTABLISHEDI tried to see if James5:smakynet lead to some other port but it looks like my side of the port is only communicating with 'James5:smakynet'.
Does anyone know what this 'smakynet' is?
What does this do?
I googled it but it didn't give me any proper info.
| what is 'smakynet' in the netstat result? |
It's still not clear to me whether you want to implement netstat -a -t -u or the outer join of /etc/services and netstat -a -t -u, or something else, but here are some ideas that may help:TCP and UDP port numbers range from 1 to 65536. The /etc/services file that you mentioned lists a subset of the well-known ports and registered ports. A larger list is at the IANA Service Name and Transport Protocol Port Number Registry. You can use getservent() to retrieve each record listed in /etc/services.
On Linux, you can get a list of all the sockets that are in listen, connecting, connected, or partially closed state, and their local and remote addresses and ports, by reading the files /proc/net/tcp, /proc/net/tcp6, /proc/net/udp, and /proc/net/udp6. The output of netstat -a -t -u -n is almost exactly the same as these files, just a lot prettier. The addresses, port numbers, and states are in hex. The pretty version of the state field can be produced by using the names in /usr/include/netinet/tcp.h: enum
{
TCP_ESTABLISHED = 1,
TCP_SYN_SENT,
TCP_SYN_RECV,
TCP_FIN_WAIT1,
TCP_FIN_WAIT2,
TCP_TIME_WAIT,
TCP_CLOSE,
TCP_CLOSE_WAIT,
TCP_LAST_ACK,
TCP_LISTEN,
TCP_CLOSING
};On FreeBSD, you would call sysctlbyname("net.inet.tcp.pcblist",...), which retrieves an array of xtcpcb structs. It's probably best to look at the netstat source code to see how to interpret those structures. |
I hope it is possible to get the necessary details of each network port from /etc/services. If I have to develop a C++ program to get the status of each port how should I start it? I am not allowed to call netstat, ss or anything similar from my program. Is there some files in the filesystem from which I can get the information?
| Status of network ports |
In netstat, you won't see PIDs if it is a kernel process. Also, like @Mathias Weidner was suggesting, you won't see the PID if the user invoking netstat isn't privileged enough.
|
After using netstat -lnp I wonder how comes some of the result don't show any PID/Program name? Should I be worried? See below:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:33223 0.0.0.0:* LISTEN 31952/dart
tcp 0 0 127.0.0.1:5037 0.0.0.0:* LISTEN 13351/adb
tcp 0 0 127.0.0.1:41741 0.0.0.0:* LISTEN -
tcp 0 0 127.0.0.1:5939 0.0.0.0:* LISTEN -
tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN -
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN -
tcp 0 0 127.0.0.1:5433 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:25 0.0.0.0:* LISTEN -
tcp 0 0 127.0.0.1:5434 0.0.0.0:* LISTEN -
tcp6 0 0 ::1:33223 :::* LISTEN 31952/dart
tcp6 0 0 127.0.0.1:63342 :::* LISTEN 1061/java
tcp6 0 0 ::1:631 :::* LISTEN -
tcp6 0 0 127.0.0.1:8599 :::* LISTEN 1061/java
tcp6 0 0 :::25 :::* LISTEN -
tcp6 0 0 127.0.0.1:6942 :::* LISTEN 1061/java
udp 0 0 224.0.0.251:5353 0.0.0.0:* 26664/chrome
udp 0 0 224.0.0.251:5353 0.0.0.0:* 26664/chrome
udp 0 0 224.0.0.251:5353 0.0.0.0:* 26705/chrome --type
udp 0 0 127.0.0.53:53 0.0.0.0:* -
udp 0 0 0.0.0.0:68 0.0.0.0:* -
udp 0 0 0.0.0.0:631 0.0.0.0:* -
raw6 0 0 :::58 :::* 7 - I have identified some of them:Port _621: Printing
Port 5939: Teamviewer
Port 5433 and 5434: PostgresQL | netstat -lnp outputing results without PID |
255 is the value of IPPROTO_RAW. It means this socket allows sending all types of IPv4 packets. (It cannot receive packets). The program has to provide a full IPv4 header.
For comparison, the raw socket with *:icmp allows sending and receiving IPv4 packets which use the ICMP protocol.
These details are specific to Linux. The exact behaviour of raw sockets varies between different Unix variants and versions.
http://man7.org/linux/man-pages/man7/raw.7.html
The IPv4 protocol field has 255 possible values.
https://en.wikipedia.org/wiki/List_of_IP_protocol_numbersThat said, I found this particular IPPRPROTO_RAW socket was not being used to send packets:
Why does atop open a raw socket?
|
What does ss mean by *:ipproto-255, in the local address/port column?
$ sudo ss -ap | grep -vE "^(nl |u_)"
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
p_raw UNCONN 0 0 *:eth0 * users:(("lldpd",pid=742,fd=11))
raw UNCONN 0 0 *:icmp *:* users:(("ping",pid=9077,fd=3))
raw UNCONN 0 0 *:ipproto-255 *:* users:(("atop",pid=7353,fd=4))
raw UNCONN 0 0 :::ipv6-icmp :::* users:(("ping",pid=9077,fd=4))
udp UNCONN 0 0 *:syslog *:* users:(("rsyslogd",pid=495,fd=5))
...If you want to know what it looks like in netstat, it shows up as 0.0.0.0:255.
$ sudo netstat -l --raw -ep
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program name
raw 0 0 0.0.0.0:255 0.0.0.0:* 7 root 2427667 7353/atop | ss shows a raw socket. What does it mean that it is listening on "*:ipproto-255"? |
In fact you shouldn't be worry.
netstat -a will show every socket (open, listenning, closed...) wo there's probably only your listening ssh deamon plus your current connection.
In your specific case, I would use lsof -i TCP:22 which is in my opinion far more readable.
lsof -i TCP:22
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
sshd 9760 root 3r IPv4 20888000 0t0 TCP internalIP:ssh->RemoteIP:58828 (ESTABLISHED)
sshd 9765 another 3u IPv4 20888000 0t0 TCP InternalIP:ssh->RemoteIP:58828 (ESTABLISHED)
sshd 10348 root 3u IPv4 12609613 0t0 TCP *:ssh (LISTEN)
sshd 10348 root 4u IPv6 12609615 0t0 TCP *:ssh (LISTEN) enter code hereIn this output you can see the two open connection and the 2 listenning in IPv4 and IPv6.
Edit 1:
If you're using sudo, it will be virtually like having 2 SSH connections opened. And using who show you will only see your username and not the root logged-in. If you have done a sudo su -:
who
username pts/0 2017-04-04 13:19 (MY_PUB_IP)
sudo su -
:~# who
username pts/0 2017-04-04 13:19 (MY_PUB_IP)
:~# |
I've just run the command on my server
netstat -atnpIt shows 2 established connection via SSH Port, but when I run the command
wIt shows only 1 shell user. Is there anything I need to worry about? If so, what could it be? & how to find out about what it's about?
| Shows One Shell User, But More Connection Via SSH Port |
Haven't you answered your own question? When there are unaccepted connections the application gets sluggish. If you're wondering whether that behavior is expected then, yes, it is. If incoming connections are queuing the the amount of time spent in the queue increases the request latency for the client leading to the sluggish response you described. To fix the problem you need to either decrease the number of incoming connections (usually not an option) or add resources to the application. The latter can be accomplished either by increasing the resources available to the system in general or (and this is often the better option) adding nodes in a load balancing cluster.
|
What information can I gather from netstat listen queues?
Looking at the man page I can see that using "-L" in netstat it shows me the size of listen queues.
It tells me information about each column:1st number of unaccepted connections
2nd number of unaccepted incomplete connections
3rd number of maximum queued connectionsI notice that whenever the 1st column tends to increment higher, my application tends to become less responsive and Nagios checks for open socket connections start to fail.
Is it typical/expected to have a non-zero number of unaccepted TCP connections? Or is this an indication of an application problem?
Example (with $port being an actual port number):
netstat -La | grep $port
tcp4 22/0/128 *.$portTypically when the application is responsive the output looks like:
tcp4 0/0/128 *.$port | Netstat Listen Queues |
If you are looking at this from the host, you're in the initial network namespace rather than in the container's network namespace: these connections or states are not seen because they are not handled by the initial network namespace's network stack. When following an entry in the process directory in /proc, this entry is seen from the process point of view ... sometimes, so will sometimes display the relevant namespace information, but tools are not meant to use this.
So you have to switch to the studied process' network namespace first.
It's as simple as (with the root user):
nsenter -t XXX --net -- ss -tnOr to find the process(es) (as seen in the initial pid namespace, not the container's):
nsenter -t XXX --net -- ss -tnp state CLOSE-WAITNormally one would search per pod (or container in other techonogies) rather than per process. Various container technologies allow to retrieve a PID process from the container name (eg: LXC's lxc-info -Hp -n containername or Docker's docker inspect --format '{{.State.Pid}}' containername ), but I don't know if and how this information is available with Kubernetes if the backend is not Docker.
Also for some tools it's a bit more difficult than this, because for example /sys should be remounted for /sys/class/net to reflect the new network namespace's interfaces view: now there would be two namespaces to change: target process' namespace and temporary mount namespace (to not damage the initial, nor use the target that might not have the required commands). Anyway, the ss command is operating purely on sockets and wouldn't need this.
For example the obsolete brctl show command would require this to work properly:
nsenter -t XXX --net -- unshare --mount -- sh -c 'mount -t sysfs sysfs /sys; brctl show' |
Debugging a tcp: out of memory error, I found that a process (from a container) has a lot of connection on CLOSE_WAIT status aka 08 when I cat /proc/XXX/net/tcp
But neither netstat or ss were showing those leaked connections.133: 0E03540A:9D9C 804CC2AD:01BB 08 00000000:00059D7A 00:00000000 00000000 0 0 316215 1 ffff8f677201df00 20 4 0 10 -1
134: 0E03540A:8316 80A7E940:01BB 08 00000000:00000000 00:00000000 00000000 0 0 255647 1 ffff8f67c9592600 20 4 1 10 -1
135: 0E03540A:8874 808C7D4A:01BB 08 00000000:00037EED 00:00000000 00000000 0 0 331603 1 ffff8f68e37a7200 20 4 1 10 -1
136: 0E03540A:E226 804CC2AD:01BB 08 00000000:0005E30B 00:00000000 00000000 0 0 215782 1 ffff8f67bd1edf00 20 4 0 10 -1
137: 0E03540A:DAEC 804CC2AD:01BB 08 00000000:0005B41A 00:00000000 00000000 0 0 216048 1 ffff8f67daf9af80 20 4 0 10 -1
138: 0E03540A:9AEA 8005FB8E:01BB 08 00000000:000D6360 00:00000000 00000000 0 0 243082 1 ffff8f67db637200 20 4 30 10 -1
140: 0E03540A:BAE4 800FB16C:01BB 08 00000000:000D8432 00:00000000 00000000 0 0 245062 1 ffff8f67640f8980 20 4 1 10 -1
141: 0E03540A:9754 804CC2AD:01BB 08 00000000:00003186 00:00000000 00000000 0 0 298890 1 ffff8f676e1a5f00 20 4 1 10 -1
142: 0E03540A:C6FC 800FB16C:01BB 08 00000000:000658C9 00:00000000 00000000 0 0 299343 1 ffff8f68dcef5580 20 4 0 10 -1
143: 0E03540A:CB24 804CC2AD:01BB 08 00000000:0005BBB4 00:00000000 00000000 0 0 316285 1 ffff8f6772019300 20 4 1 10 -1
144: 0E03540A:8204 80A7E940:01BB 08 00000000:0005DD3A 00:00000000 00000000 0 0 217390 1 ffff8f67dbc20000 20 4 0 10 -1
145: 0E03540A:8BC8 80016642:01BB 08 00000000:00059847 00:00000000 00000000 0 0 275095 1 ffff8f67b6d7a600 20 4 1 10 -1
146: 0E03540A:C612 8005FB8E:01BB 08 00000000:0003EC48 00:00000000 00000000 0 0 252281 1 ffff8f67cf014280 20 4 1 10 -1Why netstat is not showing those connection and how to get them without digging into each process details ?
| CLOSE_WAIT not visible on the kubernetes node |
I think it might a bug in your application, maybe you can keep it under control if you restart the application before running out of the maximum number of open files / sockets, or increase any artificial limits set by ulimit.
Try looking for a bug report, for example:https://issues.apache.org/jira/browse/YARN-9336
https://issues.apache.org/jira/browse/YARN-4754
https://issues.apache.org/jira/browse/YARN-10207Or report one yourself (if this is your application). For a discussion of this type of issue, see: https://stackoverflow.com/questions/15912370/how-do-i-remove-a-close-wait-socket-connection
|
when we perform the following cli on our rhel machine we get more then 600 CLOSE_WAIT lines
lsof -i tcp:8088 | grep CLOSE_WAIT
java 31100 yarn 385u IPv4 208022048 0t0 TCP master02.hgti.com:radan-http->master02.hgti.com:56504 (CLOSE_WAIT)
java 31100 yarn 407u IPv4 208210692 0t0 TCP master02.hgti.com:radan-http->master02.hgti.com:58918 (CLOSE_WAIT)
java 31100 yarn 408u IPv4 206182798 0t0 TCP master02.hgti.com:radan-http->master02.hgti.com:36538 (CLOSE_WAIT)
java 31100 yarn 410u IPv4 208447279 0t0 TCP master02.hgti.com:radan-http->master02.hgti.com:60972 (CLOSE_WAIT)
java 31100 yarn 412u IPv4 208287324 0t0 TCP master02.hgti.com:radan-http->master02.hgti.com:59820 (CLOSE_WAIT)
java 31100 yarn 413u IPv4 206107964 0t0 TCP master02.hgti.com:radan-http->master02.hgti.com:35704 (CLOSE_WAIT)
.
.
.
.
.as I know During the communication between the server and the client, the closed_wait caused by the socket failure of the server occurs
so any chance to do some settings from Linux side? in order to minimize the close wait sessions?
or its should be only solution from application side?
reference - https://www.programmersought.com/article/74221875444/
| rhel + any best practice to minimize the CLOSE_WAIT sessions from linux side |
Although kludgy, you can try this:
$ netstat -natp 2> /dev/null | awk 'NR==2 {printf("%s\t%s %s\t%s %s\t%s %s\n",$1,$4,$5,$6,$7,$9,$10)}
NR>=3 {OFS="\t";print($1,$4,$5,$7)}'EDIT
... and, for the sake of completion if you need the port column separate from its IP direction in your final output, you can introduce a finer grained formatting in awk, like so:
$ netstat -natp 2>/dev/null | awk '
NR==2 {printf("%s\t%8s %s\tPort\t%8s %s\tPort\t%s\n",$1,$4,$5,$6,$7,$9)}
NR>=3 {$8=$7;
idx=match($5,":[^:]+$");
$7=substr($5,idx+1);
$6=substr($5,1,idx-1);
idx=match($4,":[^:]+$");
$5=substr($4,idx+1);
$4=substr($4,1,idx-1);
printf("%s\t%16s\t%s\t%16s\t%s\t%s\n",$1,$4,$5,$6,$7,$8)}
'
Proto Local Address Port Foreign Address Port PID/Program
tcp 0.0.0.0 22 0.0.0.0 * -
tcp 127.0.0.1 631 0.0.0.0 * -
tcp 127.0.0.1 25 0.0.0.0 * -
tcp 0.0.0.0 445 0.0.0.0 * -
tcp 127.0.0.1 12150 0.0.0.0 * -
tcp 0.0.0.0 139 0.0.0.0 * -
tcp 127.0.0.1 37580 127.0.0.1 12150 2962/firefox
tcp 127.0.0.1 12150 127.0.0.1 40684 -
[...]
tcp 127.0.0.1 12150 127.0.0.1 47646 -
tcp 127.0.0.1 12150 127.0.0.1 48982 -
tcp 127.0.0.1 12150 127.0.0.1 1414 -
tcp6 :: 22 :: * -
tcp6 ::1 631 :: * -
tcp6 :: 445 :: * -
tcp6 :: 139 :: * -Tested with Gawk (GNU Awk) v5.1.0, where above sample output is from a random box lying about near me.
Differences with my earlier answer are:for each record's fields 4 and 5, check the position (idx) of the last : character in the string. Whatever comes after that is the port. The beginning of the string is the IP. That goes for both IPv4 and IPv6 IP strings. This is useful in separating IP and port number in 127.0.0.1:12345 and also in ::1:432 for instance.
lose the OFS="\t" to specify the output field separator in the second awk block and add integer widths in appropriate places between % and s in the printf formatting strings in both awk blocks. |
I am trying to retrieve Local Address-port with port number in different block used by each IP-address in Foreign Address and PID/Program name) from the following and store it in a file:
I used:
netstat -natp | grep '^[a-z0-9P]*'after that I want to ignore Recv-Q and Send-Q block and take Local Address with its port number and Foreign Address and then again ignore State and take PID/Program name.
Which regexp will be help full for me? Also, it will be more helpful if I am able keep both port numbers in different block after each address.
This is What I have:
$ netstat -natp | grep '^[a-z0-9P]*'
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN -
tcp 0 0 127.0.0.1:5939 0.0.0.0:* LISTEN -
tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN -
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:7071 0.0.0.0:* LISTEN -
tcp 0 0 192.168.42.157:37960 106.10.218.42:443 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:35636 117.18.237.29:80 ESTABLISHED 21019/firefox
tcp 1 32 192.168.42.157:40444 5.39.93.71:443 CLOSING -
tcp 0 0 192.168.42.157:35626 52.27.200.224:443 TIME_WAIT -
tcp 0 0 192.168.42.157:43004 122.252.255.200:80 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:35734 117.18.237.29:80 TIME_WAIT -
tcp 0 0 192.168.42.157:35776 52.27.200.224:443 TIME_WAIT -
tcp 0 0 192.168.42.157:41690 54.182.1.219:443 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:56472 54.182.0.97:443 ESTABLISHED 21019/firefox
tcp 1 32 192.168.42.157:48390 198.252.206.25:443 CLOSING -
tcp 0 0 192.168.42.157:37322 34.107.221.82:80 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:57724 204.79.197.204:443 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:43142 23.57.14.17:443 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:46286 13.227.138.58:443 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:55576 112.133.250.163:443 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:52328 151.101.120.193:443 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:35736 52.39.214.89:443 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:57252 99.83.135.170:443 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:48394 198.252.206.25:443 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:45020 54.182.0.113:443 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:50396 27.123.42.205:443 ESTABLISHED 21019/firefox
tcp 1 32 192.168.42.157:48092 198.252.206.25:443 CLOSING -
tcp 0 0 192.168.42.157:55798 142.250.192.99:80 TIME_WAIT -
tcp 0 0 192.168.42.157:34190 157.240.16.52:443 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:37320 34.107.221.82:80 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:44806 54.87.110.85:443 ESTABLISHED 21019/firefox
tcp 0 0 192.168.42.157:51202 103.229.10.173:443 ESTABLISHED 21019/firefox This is what I want:
Prot Local Address PortofLocalA Foreign Address PortofForeignA PID/Program name and all its o/p below it
| How I can grep data with some spaces and ignoring block? |
In TCP/IP, there is no such thing as "an open port that is not used by anything". Any port that is not currently being used is going to be closed. In addition to that, iptables or any firewall can block certain ports from some or all traffic.
(I really hate the talk of "opening a port" in firewalls, because it feeds a misconception on how TCP and UDP ports work. A port can be unblocked in a firewall, but then you actually need some program or kernel-level service to actually use it, and it will open the port as part of the normal procedures of using the port.)
From the Xrdp(8) man page:-p, --port
Specify TCP port to listen to. This overrides port setting in xrdp.ini file.From the xrdp.ini(5) man page:port=port
Specify TCP port to listen on for incoming connections. The default for RDP is 3389.So Xrdp uses the port specified with the -p option if that option is used, or the port specified in the xrdp.ini configuration file if option -p is not used. If neither of them is specified, it uses port 3389, which is the same port Windows uses for the RDP protocol.
Most outgoing connections and any applications that don't specify a local port number for their TCP/UDP sockets will by default get a local port number in the range specified by the sysctl setting net.ipv4.ip_local_port_range. In RHEL/CentOS 7, this range defaults to port numbers 32768..60999.
(Each TCP or UDP connection will have both a local and a remote port number: outgoing connections usually only specify the remote port number and let the OS determine the local one, and ports opened for listening for incoming connections normally only specify the local port number.)
You can exclude specific ports and/or port ranges from this automatic allocation using the sysctl setting net.ipv4.ip_local_reserved_ports. For example, if you need to reserve ports 40000 and 40001 for some particular use, you can do it with:
sysctl -w net.ipv4.ip_local_reserved_ports=40000,40001This exclusion from automatic allocation will take effect immediately. To make it persistent, edit /etc/sysctl.conf and add this line to it:
net.ipv4.ip_local_reserved_ports=40000,40001Any program that explicitly specifies (= binds to) a port that has been reserved in this way will still get it as normal; this reservation will only override the automatic allocation of port numbers.
You cannot really do much else; if a regular user process requests a specific port number that is >1023 and is not currently in use by something else, the operating system will grant that request. (To use ports in the 0..1023 range, a process must run as root, or if a Linux distribution uses more fine-grained privileges, it needs to have the CAP_NET_BIND_SERVICE capability.)
However, you may be able to use iptables rules to make that port unusable to anything except the specific purpose, depending on what that purpose is. For example, you could restrict incoming/outgoing connections to that port to only those that fit the specific purpose, or use iptables -m owner --uid-owner <username> to restrict it to be useful for a specific user only, with a pair of rules like this:
iptables -A OUTPUT -m tcp -p tcp --sport 3389 -m owner --uid-owner specified-user -j ACCEPT
iptables -A OUTPUT -m tcp -p tcp --sport 3389 -j REJECT (The first rule will match the port and the intended user, and will ACCEPT the traffic and end rule processing for it; if that rule did not match, the second rule will match the port only, and will REJECT the outgoing traffic of anyone that is not the intended user of that port.)
This will not necessarily prevent other users from trying to use the port, but will make it so that the port will always fail to connect for them, so hopefully they will stop trying to use it.
|
I'm admin for some devs and they requested that a port on a machine be clear for a specific purpose. When one of the devs went to use that port, it was in use. An netstat -p showed that xrdp/Xnvc was using it. I tried to have the user jump off and back on to see if it would use another port, but it kept using that one.
From my reading, Xrdp chooses random, open port. I can figure out how to blacklist that port from the service.
The system: CentOS 7, using iptables instead of firewalld
| How to block a service (xrdp) from using a specific port? |
From TCP Variables:The tcp_reordering variable tells the kernel how much a TCP packet may
be reordered in a stream without assuming that the packet was lost
somewhere on the way.tcp_reordering may be changed via net.ipv4.tcp_reordering variable of sysctl. By default this value is 3.
If you change net.ipv4.tcp_reordering variable, then ss --info will print all connections with values which are differs from 3. Fragment of iproute2 source:
. . .
if (s->reordering != 3)
printf(" reordering:%d", s->reordering);
. . . |
ss --info returns information about tcp connections. It produces a line simliar to the following (some fields removed for formatting)
tcp ESTAB 0 0 192.168.1.177:60236 54.70.141.88:https
cubic wscale:7,7 rto:204 rtt:0.918/0.419 reordering:59
What exactly does the reordering number mean in this example?
| What does the reordering field of ss --info mean? |
The server code calls accept() only once. Thus, only the first connection attempt is effectively accepted and the remaining client connections are kept on a connection request queue which lives in the kernel space. The next client connection will be retrieved from the queue when accept() is called again.
No process owns client connections while they remain in kernel space, because multiple processes or threads may legally accept connections from an unique pair of address and port if they enable SO_REUSEPORT option on all participating socket descriptors.
You can test the SO_REUSEPORT option by yourself by adding the following code snippet before the bind() call and running more than one server. You will figure that the kernel will distribute requests among them.
{
int enabled = -1;
if (setsockopt (sockd, SOL_SOCKET, SO_REUSEPORT,
(void*) &enabled, sizeof (enabled)) < 0) {
perror ("setsockopt");
}
}Reference from man 2 accept:The accept(sockfd) system call is used with connection-based socket types (SOCK_STREAM, SOCK_SEQPACKET). It extracts the first connection request on the queue of pending connections for the listening socket, sockfd, creates a new connected socket, and returns a new file descriptor referring to that socket. The newly created socket is not in the listening state. The original socket sockfd is unaffected by this call.Reference from man 7 socket:SO_REUSEPORT (since Linux 3.9)
Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. This option must be set on each socket (including the first socket) prior to calling bind(2) on the socket. To prevent port hijacking, all of the processes binding to the same address must have the same effective UID. This option can be employed with both TCP and UDP sockets.
For TCP sockets, this option allows accept(2) load distribution in a multi-threaded server to be improved by using a distinct listener socket for each thread. This provides improved load distribution as compared to traditional techniques such using a single accept(2)ing thread that distributes connections, or having multiple threads that compete to accept(2) from the same socket.
For UDP sockets, the use of this option can provide better distribution of incoming datagrams to multiple processes (or threads) as compared to the traditional technique of having multiple processes compete to receive datagrams on the same socket. |
i am testing stuff with sockets and i encountered that strange case :
i coded i very simple tcp server in c, i made it block after accept(), just to see what happen when accepting multiple connection attempts at the same time :
Here is an excerpt of code of the server :
//listen()
if( (listen(sock,5)) == -1) {
perror("listen");
exit(-1);
}//accept()
if( (cli = accept(sock, (struct sockaddr *) &client, &len)) == 1 ){
perror("accept");
exit(-1);
}printf("entrez un int : ");
scanf("%d",&toto);when the server asks the user to enter an integer, i try to connect multiple clients with telnet.
Fort the first one, evrything is ok :
root@[...] :/home/[...]/workspace/sockets# netstat -antp | grep 10003
tcp 0 0 0.0.0.0:10003 0.0.0.0:* LISTEN 25832/toto
tcp 0 0 127.0.0.1:10003 127.0.0.1:51166 ESTABLISHED 25832/toto
tcp 0 0 127.0.0.1:51166 127.0.0.1:10003 ESTABLISHED 25845/telnetbut then after the first one, even though i am root, there are some connections i can't see the process owning it and its pid :
root@[...] :/home/[...]/workspace/sockets# netstat -antp | grep 10003
tcp 0 0 0.0.0.0:10003 0.0.0.0:* LISTEN 25832/toto
tcp 0 0 127.0.0.1:10003 127.0.0.1:51166 ESTABLISHED 25832/toto
tcp 0 0 127.0.0.1:51166 127.0.0.1:10003 ESTABLISHED 25845/telnet
tcp 0 0 127.0.0.1:10003 127.0.0.1:51168 ESTABLISHED -
tcp 0 0 127.0.0.1:51168 127.0.0.1:10003 ESTABLISHED 25852/telneta third one :
root@[...] :/home/[...]/workspace/sockets# netstat -antp | grep 10003
tcp 0 0 0.0.0.0:10003 0.0.0.0:* LISTEN 25832/toto
tcp 0 0 127.0.0.1:10003 127.0.0.1:51166 ESTABLISHED 25832/toto
tcp 0 0 127.0.0.1:51166 127.0.0.1:10003 ESTABLISHED 25845/telnet
tcp 0 0 127.0.0.1:10003 127.0.0.1:51172 ESTABLISHED -
tcp 0 0 127.0.0.1:10003 127.0.0.1:51168 ESTABLISHED -
tcp 0 0 127.0.0.1:51168 127.0.0.1:10003 ESTABLISHED 25852/telnet
tcp 0 0 127.0.0.1:51172 127.0.0.1:10003 ESTABLISHED 25860/telnetI tried again a few days later with netstat -antpe as root and here is what i got :
root@[...] :/home/[...]/workspace/sockets# netstat -antpe | grep 10003
tcp 0 0 0.0.0.0:10003 0.0.0.0:* LISTEN 1000 327680 22399/toto
tcp 0 0 127.0.0.1:33286 127.0.0.1:10003 ESTABLISHED 1000 417202 22884/telnet
tcp 0 0 127.0.0.1:10003 127.0.0.1:33046 ESTABLISHED 0 0 -
tcp 0 0 127.0.0.1:10003 127.0.0.1:33286 ESTABLISHED 0 0 -
tcp 0 0 127.0.0.1:33044 127.0.0.1:10003 ESTABLISHED 1000 332810 22402/telnet
tcp 0 0 127.0.0.1:33046 127.0.0.1:10003 ESTABLISHED 1000 331200 22410/telnet
tcp 0 0 127.0.0.1:10003 127.0.0.1:33044 ESTABLISHED 1000 332801 22399/totohow comes a process or a connection can have an inode of 0 ? Can someone explain me what is going on ?
| sudo netstat -antp not showing PID |
The netstat output explains it fairly well:(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)Just run it as root (e.g. sudo netstat -np)
|
Some program was connected from my local ip 111.111.111.111 with 130.239.18.176:80,how to get the pid number?
netstat -np
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 111.111.111.111:46243 52.89.80.240:443 TIME_WAIT -
tcp 0 1 111.111.111.111:36553 173.239.79.210:443 SYN_SENT 2630/firefox-esr
tcp 0 0 111.111.111.111:48470 130.239.18.176:80 ESTABLISHED -
tcp 0 1 111.111.111.111:36552 173.239.79.210:443 SYN_SENT 2630/firefox-esr
tcp 0 1 111.111.111.111:34202 74.125.204.101:80 SYN_SENT 2630/firefox-esr
tcp 0 0 111.111.111.111:52243 203.208.48.79:443 ESTABLISHED 2630/firefox-esr
tcp 0 1 111.111.111.111:46521 74.125.203.93:443 SYN_SENT 2630/firefox-esr
tcp 0 1 111.111.111.111:34200 74.125.204.101:80 SYN_SENT 2630/firefox-esr
tcp 0 0 111.111.111.111:48424 130.239.18.176:80 ESTABLISHED -
tcp 0 0 111.111.111.111:46238 52.89.80.240:443 TIME_WAIT -
tcp 0 1 111.111.111.111:46523 74.125.203.93:443 SYN_SENT 2630/firefox-esr
tcp 0 0 111.111.111.111:34204 74.125.204.101:80 TIME_WAIT -
tcp 0 0 111.111.111.111:33700 104.24.98.177:443 ESTABLISHED 2630/firefox-esr
tcp 0 1 111.111.111.111:34206 74.125.204.101:80 SYN_SENT 2630/firefox-esr
tcp 0 0 127.0.0.1:49941 127.0.0.1:80 ESTABLISHED 2630/firefox-esr | How to get the pid number which connect to external ip? |
As far as your browser is concerned, it's connected to 74.125.141.104. A DNAT doesn't change that fact. If you DNAT port 80 coming from the internet to port 80 on an internal webserver at e.g. 10.201.87.80, would you expect netstat on the remote system to show 10.201.87.80 as the remote IP or your external IP?
PS: 10.201.87.64:599449 is impossible, port numbers are 65535 or less (16 bits).
|
So, here I have a basic setup with SOCKS5 proxy listening on, oh, say 8123
I redirect TCP to the proxy via iptables
From iptables perspective everything looks peachy,
iptables -t nat -v -L shows
DNAT tcp -- any any anywhere anywhere to:127.0.01:8123From the "practical" perspective it's working (Google's account activity, geoip websites and http://ipleak.net/ specifically are showing proxy's external IP)
So it would seem the proxy is working as intended.
However, if I try to do a netstat, I see things like
tcp 0 0 10.201.87.64:59949 74.125.141.104:443 ESTABLISHED [browser's PID]74.125.141.104:443 is google.
What I would have expected netstat to show is the proxy's listening IP (localhost) instead of the remote server's (google's) IP.
Is the browser "leaking" past the iptable rule for some reason (and if so, why do google's account details show a connection from the proxy's external IP) ?
Or is it netstat being weird and oblivious to the fact that DNAT is taking place?
| Unexpected netstat output in DNAT conditions |
Add this sed command at the end of your pipe. It does a greeding search until last . and delete it and all digits that follow it.
... | sed -e 's/^\(.*\)\.[0-9]*/\1/'It yields:
tcp4 0 0 61.129.65.176.80 123.120.207.172 ESTABLISHED
tcp4 491 0 61.129.65.176.80 171.250.180.211 ESTABLISHED
tcp4 286 0 61.129.65.176.80 123.120.207.172 ESTABLISHED
tcp4 299 0 61.129.65.176.80 211.8.128.46 ESTABLISHED
tcp4 0 0 61.129.65.176.80 123.139.147.112 ESTABLISHED
tcp4 361 0 61.129.65.176.80 239.187.139.47 ESTABLISHED
tcp4 509 0 61.129.65.176.80 74.74.87.36 ESTABLISHED
tcp4 324 0 61.129.65.176.80 75.30.126.198 ESTABLISHED
tcp4 508 0 61.129.65.176.80 149.78.116.66 ESTABLISHED
tcp4 321 0 61.129.65.176.80 48.150.75.171 ESTABLISHED |
I would like to get netstat to not display port numbers on the foreign address so I can run some statistics on it. This is for a FreeBSD system.
The following is a example of the output.
<root>:/# netstat -an | grep .80 |head
tcp4 0 0 61.129.65.176.80 123.120.207.172.51972 ESTABLISHED
tcp4 491 0 61.129.65.176.80 171.250.180.211.51000 ESTABLISHED
tcp4 286 0 61.129.65.176.80 123.120.207.17210399 ESTABLISHED
tcp4 299 0 61.129.65.176.80 211.8.128.46.35458 ESTABLISHED
tcp4 0 0 61.129.65.176.80 123.139.147.112.62778 ESTABLISHED
tcp4 361 0 61.129.65.176.80 239.187.139.47.17607 ESTABLISHED
tcp4 509 0 61.129.65.176.80 74.74.87.36.7822 ESTABLISHED
tcp4 324 0 61.129.65.176.80 75.30.126.198.60721 ESTABLISHED
tcp4 508 0 61.129.65.176.80 149.78.116.66.12120 ESTABLISHED
tcp4 321 0 61.129.65.176.80 48.150.75.171.2617 ESTABLISHED
<root>:/# | Have netstat not display port numbers for foreign address |
From the point of view of the general networking stack, there is no local connection involved so no associated socket (so ss won't report anything), and as routing requires no associated state, it doesn't have to be known and isn't.
But to do NAT, such state must be memorized so all further packets get translated (including reply packets being "un-translated") the same. This is done by Netfilter and its conntrack facility in charge of tracking such connection states. conntrack is part of Netfilter and is the facility used by both iptables and nftables: whatever the backend in use by firewalld NAT is always tracked by conntrack.
The conntrack command (which in most Linux distributions, is usually made available with either the conntrack-tools package or the conntrack package) can query the (in-kernel memory) conntrack table. With an adequate filter: --dst-nat , it will display only connections which underwent a DNAT transformation: entries where the reply source is different from the query destination.
To display all such tracked connections currently in use (run as root):
conntrack -L --dst-natTo monitor events about their state changes:
conntrack -E --dst-natThis command can't display the rules creating such transformations since they are not themselves part of the conntrack state, but define the future behavior for such state. These rules are part of the firewall rules in chains hooking as NAT. Depending on firewalld's backend (iptables or nftables), the result of this command done on a default setup:
firewall-cmd --add-forward-port=port=5555:proto=tcp:toport=6666:toaddr=10.3.3.2Could be seenwith iptables backend in a chain in the nat table:
# iptables -t nat -S | grep -w 5555
-A PRE_public_allow -p tcp -m tcp --dport 5555 -j DNAT --to-destination 10.3.3.2:6666with nftables backend likewise with a chain with a similar name in the inet firewalld table, called from a base chain hooking with the nat type:
# nft list chain inet firewalld nat_PRE_public_allow
table inet firewalld {
chain nat_PRE_public_allow {
meta nfproto ipv4 tcp dport 5555 dnat ip to 10.3.3.2:6666
}
}The fact that it's actually "opened" would be more difficult to check: one should just trust firewalld to have done what's needed for this. The current implementation of firewalld does this in a generic way by querying the conntrack facility:with iptables backend, this is done by adding the DNAT state to allowed states in each built-in chain also having DROP rules. So this will appear (together with other allowed states) as:
-A <built-in> -m conntrack --ctstate RELATED,ESTABLISHED,DNAT -j ACCEPTUsually with nftables backend, this is done by using in each base chain that would also contain drop rules:
ct status dnat acceptBoth cases do the same: if the packet (along other possibilities) underwent a DNAT transformation (which can only have happened as result of the ruleset and thus of what is defined in firewalld), then accept it. Without having to duplicate again which specific port was allowed.
Older firewalld versions might have used firewall marks instead of conntrack's state to act as memory to do the same.
|
I have forwarded a port using firewalld, and everything is functioning properly. However, the 'netstat' and 'ss' commands do not display the port opened by firewalld, nor do they show the connections. Since the forwarding is handled at the kernel level, 'netstat' and 'ss' won't reveal the connections or port status. I would like to know how to list the connections and check if the port is open without relying on 'nmap.' I would appreciate it if you could explain this.
| How to list the connections of the port forwarded by firewalld? |
netstat does a reverse DNS lookup to display a hostname instead of an IP. You can disable reverse DNS lookup with the -n option.
Try this:
$ sudo netstat -anp |
I ssh to my ubuntu server and run sudo netstat -a -p and I get this:
tcp 0 0 ip-172-31-25-123.us:ssh mailDOTjjtoursDOTcom:54531 ESTABLISHED 1516/sshd: ubuntu [And when I use my other ssh client, it shows another jjtoursDOTcom in there.
I use putty and bitvise.
Why does it show that domain name?
(I replaced dots . with DOT in domain names)
| confused by netstat result |
I recommend to simulate the allegedly broken connections with socat (a command line tool that establish arbitrary byte streams).
Try to listen on the ports with
socat - TCP-Listen:9001for a tcp connection that listens on port 9001 or
socat - UDP-Listen:9001for a udp connection.
Examine if netstat -p (or alternatively sockstat) shows the connection that socat established. If so, you should investigate your code further and maybe post a source code related question on stackoverflow.com.
In the other case, please let us know!
|
I have some code I'm testing. Program A listens on a predefined socket for program B to connect to and for my testing I'm running 32 instances of the programs A and B. I've written my script to tell program A to listen to port 9001-9032 and put in the configuration files for each instance of program B the corresponding port to connect to.
When I run the script which starts up program A and B and run netstat -tnap I find that of all the ports 9001-9032 the only port actually used is 9001 which is used by another program (my mistake!). When I grep for program A, I find each instance is listening on a seemingly completely random ports that have no relationship to the ports 90** they should be listening on. However, my program B, which should be connecting to ports 9001-9032, is able to find and connect to each instance of program A despite A apparently not listening on the ports it's B should be trying to connect to. I'm rather confused as to how that's possible.
If that isn't confusing enough my 32 program and only the 32 one (listening on 9032) dies at startup with an error that the address was refused when it tries to bind to the port. I tried changing the programs to listen on ports 15001-15032 just to see what would happen and I still got the exact same behavior; all programs seem to be listening on random ports and the 32 program can't establish a connection.
Can anyone explain why my ports are behaving the way the are? Am I misunderstanding some part of netstat or Linux ports?
| Netstat shows programs running on different ports then they should |
0.0.0.0:22 in local address column means ssh daemon listen on all local ip.
So, if you have 2 IPs (say 192.168.0.10 and 90.87.65.123), your ssh daemon will listen on both IPs (and, of course on 127.0.0.1). So you can connect to it with both
$ ssh [emailprotected]
$ ssh [emailprotected]assuming your computer knows the way to both networks.
If insteed of 0.0.0.0:22, it has been written 192.168.0.10:22, you could have connect with
$ ssh [emailprotected]but not with
$ ssh [emailprotected]In short, it has nothing to do with witch IP can connect but where listens the local daemon
|
Under the column "local address" of netstat:
0.0.0.0:22 means that access to port 22 is allowed from any ip addresses.
which ip addresses? ip addresses within my local network or outside my local network.
if 0.0.0.0:22 refers only to ip addresses within my local network, why I can connect to a server from my home computer which has IP address outside the local network of the server.
What does exactly 0.0.0.0:22 mean in terms of which IP addresses can connect to port 22.
| what does mean 0.0.0.0:22 under the column local address of netstat command? |
Well I think you should first understand the command netstat before applying awk and cut in the output.
netstat -ntu will display all the udp and tcp connections including tcp6.
So when you are trying to apply awk & cut on the output of netstat command
netstat -ntu | awk '{print $5}' | cut -d: -f1the cut command then chose ":" as the delimiter and display the first field.
A tcp v4 connection looks like this
12.34.56.78:80
A tcp v6 connection looks like this in netstat output
::1:631
now when you apply cut with delimiter ":" the output of tcp v4 connection will show you the ip address, but output of tcp v6 will be a blank line.
And applying sort|uniq -c will count the blank lines.
If you want to list out all tcp established connections to your web server, try this
netstat -npa | grep pid_of_your_web_server | grep ESTABLISHED | awk '{print $5}' | awk -F ':' '{print $1}' | sort | uniq -c Or all tcp connections related to your web server
netstat -npa | grep pid_of_your_web_server | grep tcp | grep -v LISTEN | awk '{print $5}' | awk -F ':' '{print $1}' | sort | uniq -cto take a total count of all , without grouping
netstat -npa | grep pid_of_your_web_server | grep tcp | grep -v LISTEN | wc -l |
I have a question about linux netstat usage and output results. I'm trying to solve a dilema about why my server is facing communications delays and bottle neck issues, So I started digging and studying and one of the things I needed to know is a full connections list grouped per ip address and count number of stablished connections, so I first got this:
[root@ip-localhost ec2-user]# netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n ...
9 77.70.115.30
14 54.211.25.39
198 172.31.30.153951
The question, If I make the summatory of the listed quantity of connections per ip I'm not getting a total of 3951, that number also raise to over 44K so, what the final line number without ip address represents? file descriptors? possible internal kernel connections? opened sockets forgot for the system?
I have also a summary of the connetions :
[root@ip-localhost ec2-user]# netstat -ant | awk '{print $6}' | sort | uniq -c | sort -n
1 established)
1 Foreign
4 FIN_WAIT1
8 SYN_SENT
57 LISTEN
67 SYN_RECV
180 TIME_WAIT
1040 LAST_ACK
6323 CLOSE_WAIT
7209 ESTABLISHED ```
note: I had to insert the full output due to get to the point that listed connections aren't totalized at the end of the netstat output. thanks
| netstat shows over 44K connections without ip address, what's that? |