July 29, 2012

Getting IP address of server stream socket of local process

    If you need to get IP address which is assigned to some socket created by local process, you can run following command for shell:
lsof -i | grep -m 1 process_name | awk '{print $9}' | awk -F: '{print $1}'
    Let's see how it works step by step.

1
Running
lsof -i
    gives the listing of all Internet and x.25 (HP-UX) network files.

2
Running
lsof -i | grep -m 1 process_name
    gives the listing 1 file specified for target process. For example, process name is "firefox". The result will be:
firefox  2287 oblalex   50u  IPv4 247178      0t0  TCP 192.168.1.33:56695->93.184.220.20:http (CLOSE_WAIT)
3
Running
lsof -i | grep -m 1 process_name | awk '{print $9}'
    gives source address and destination address with protocol name. In our example it will be:
192.168.1.33:56695->93.184.220.20:http
4
Finally, running
lsof -i | grep -m 1 process_name | awk '{print $9}' | awk -F: '{print $1}'
    gives the final result by splitting string with ":" separator and selecting source address:
192.168.1.33

No comments:

Post a Comment