Show network connections of a process

monitoringnetworkingprocess

Is there a way to show the connections of a process? Something like that:

show PID

in which show is a command to do this, and PID is the ID of the process.
The output that I want is composed of all the connections of the process (in real-time). For example, if the process tries to connect to 173.194.112.151 the output is 173.194.112.151.

A more specific example with Firefox:

show `pidof firefox`

and with Firefox I go at first to google.com, then to unix.stackexchange.com and finally to 192.30.252.129. The output, when I close the browser, must be:

google.com
stackexchange.com
192.30.252.129

(Obviously with the browser this output is not realistic, because there are a lot of other related connections, but this is only an example.)

Best Answer

You're looking for strace! I found this answer on askubuntu, but it's valid for Unix:

To start and monitor an new process:

strace -f -e trace=network -s 10000 PROCESS ARGUMENTS

To monitor an existing process with a known PID:

strace -p $PID -f -e trace=network -s 10000

Otherwise, but that's specific to Linux, you can run the process in an isolated network namespace and use wireshark to monitor the traffic. This will probably be more convenient than reading the strace log:

  • create a test network namespace:

    ip netns add test
    
  • create a pair of virtual network interfaces (veth-a and veth-b):

    ip link add veth-a type veth peer name veth-b
    
  • change the active namespace of the veth-a interface:

    ip link set veth-a netns test
    
  • configure the IP addresses of the virtual interfaces:

    ip netns exec test ifconfig veth-a up 192.168.163.1 netmask 255.255.255.0
    ifconfig veth-b up 192.168.163.254 netmask 255.255.255.0
    
  • configure the routing in the test namespace:

    ip netns exec test route add default gw 192.168.163.254 dev veth-a
    
  • activate ip_forward and establish a NAT rule to forward the traffic coming in from the namespace you created (you have to adjust the network interface and SNAT ip address):

    echo 1 > /proc/sys/net/ipv4/ip_forward
    iptables -t nat -A POSTROUTING -s 192.168.163.0/24 -o YOURNETWORKINTERFACE -j SNAT --to-source YOURIPADDRESS
    

    (You can also use the MASQUERADE rule if you prefer)

  • finally, you can run the process you want to analyze in the new namespace, and wireshark too:

    ip netns exec test thebinarytotest
    ip netns exec test wireshark
    

    You'll have to monitor the veth-a interface.

Related Question