Determining clients IP address by service and PID

Search Keys: network

Attached is a simple program that you may add to your collection of stuff for OSR5. I wrote this thing several years ago for use with a program where I needed to know a client's IP address, given the TCP service on which they were connected and the program's PID (to differentiate when more than one session was open on the same service). I recently cleaned it up so it could be used from the command line.

The command line syntax is:



    getrip <service> <PID>
 

where <service> is a TCP service defined in /etc/services (port numbers will not work) and <PID> is the process ID of a program that is serving a client attached to >service>. If both <service> and <PID> are found to be attached together, getrip will print the remote client's IP address to STDOUT and return 0 to the caller. Otherwise, getrip will return 1 to the caller and print suitable diagnostics to STDERR.

Example:

    getrip telnet 12345
 

A copyright statement will be displayed if you type what getrip. Invoking getrip with no arguments will display some help. Recommended perms are 755 and ownership should be bin:bin. The lsof utility must be present on the system and accessible in the execution environment.

source getrip.c
SCO coff getrip_coff
SCO ELF getrip

/*

get IP addr associated with port & PID -- 10/1999, wjb

grip port pid

remote IP printed on STDOUT

*/

#include <stdio.h>

#define S_BUF           192
#define S_IPADDR        15
#define S_PORT          16

char    *iam;

void    usage(void);

/*===========================================================================*/

void main(int argc,char *argv[]) {

    // argv[1] = port
    // argv[2] = caller's PID

        FILE    *f_lsof;
        char    *lsofcmd="lsof -n -T -w -i tcp:";
        int     bp=0;
        int     ip=0;
        int     oc;
        char    buffer[S_BUF+1];        // input buffer
        char    ipaddr[S_IPADDR+1];     // IP address

    iam=argv[0];

    if (argc != 3) {
        usage();
    };

    sprintf(buffer,"%s%s | grep %s | grep 0u",
        lsofcmd,argv[1],argv[2]);               // construct pipe command
    if ((f_lsof=popen(buffer,"r")) == NULL) {
        fprintf(stderr,"%s: couldn't pipe to lsof",iam);
        exit(1);
    };
    while ((oc=getc(f_lsof)) != EOF && (oc != '\n')) {
        *(buffer+bp++)=oc;
    };
    *(buffer+bp)=0;
    pclose(f_lsof);
    if (bp == 0) {
        fprintf(stderr,
            "%s: %s: no such process attached to %s\n",
            iam,argv[2],argv[1]);
        exit(1);
    };
    bp=0;
    while (*(buffer+bp)) {
        if (*(buffer+bp++) == '>') {
            while (*(buffer+bp)) {
                if (*(buffer+bp) == ':') {
                    *(ipaddr+ip)=0;
                    printf("%s\n",ipaddr);
                    exit(0);
                };
                *(ipaddr+ip++)=*(buffer+bp++);
            };
        };
    };
    fprintf(stderr,"%s: lsof output grabled: can't get IP address for %s\n",
        iam,argv[1]);
    exit(1);
}
/*===========================================================================*/

/* display usage help */

void usage(void) {
    fprintf(stderr,"usage: %s port PID\n\n",iam);
    fprintf(stderr,"%s%s%s%s%s%s%s",
        "    port  TCP port to interrogate, such as SMTP or POP3\n",
        "    PID   process ID of process bound to TCP port\n\n",
        "IP address, if any, is written to STDOUT.  Returns 0 if a matching\n",
        "IP address is found, 1 if not.\n\n",
        "The `lsof' utility must be installed on your system in order for\n",
        "this program to function.  `lsof' may be downloaded from SCO's\n",
        "Skunkware FTP site (ftp2.sco.com).\n");
    exit(1);
}
/*===========================================================================*/

/* copyright declaration for `what' command */

const char *what[]={
           "@(#)get remote IP address on TCP port V1.0 -- 10/16/1999",
           "@(#)                                  V1.1 -- 02/27/2004",
           "@(#)",
           "@(#)type `getrip' w/no arguments for command line usage",
           "@(#)",
           "@(#)Copyright (C)1985-2004 by BCS Technology Limited.  All rights",
           "@(#)reserved.  Permission granted to use, copy and/or  distribute",
           "@(#)this software,  providing proper attribution is given and all",
           "@(#)copyright notices remain intact.  This software is  *NOT*  in",
           "@(#)the public domain and has not been GPLed.",
           "@(#)",
           "@(#)!!! CAUTION:  USE AT YOUR OWN RISK !!!",
           "@(#)",
           "@(#)BCS Technology Limited does  not  accept  responsibility  for",
           "@(#)anything bad that might occur as a result of using this soft-",
           "@(#)ware.  Again, USE AT YOUR OWN RISK!",
           "@(#)"
        };
/*===========================================================================*/
 


Got something to add? Send me email.





(OLDER) <- More Stuff -> (NEWER)    (NEWEST)   

Printer Friendly Version

-> -> Determining clients IP address by service andPID




Increase ad revenue 50-250% with Ezoic


More Articles by © BigDumbDinosaur




---November 21, 2004

That code should work on any Unix/Linux that has lsof (most modern Unixes do) and since it is basically just parsing lsof's output, you could easily rewrite it in sh or perl or almost anything..

--TonyLawrence

"...you could easily rewrite it in sh or perl..."

You could, but writing in C gives you many opportunities to decipher the cryptic diagnostics that the compiler belches out when you screw up. <Grin> Besides, if I don't write something in C now and then, I'll forget how to do it and might end up having to resort to using Visual Basic.

Anyhow, eventually I'll get around to writing getrip so it doesn't requires lsof -- just as soon as I get about 500 other programming projects out of the way. Would you believe one of them is for the Commodore 64? Which speaking of diagnostics, watching the 6502 assembler cough its cookies when it hits some bad source code is really entertaining...

--BigDumbDinosaur




Kerio Samepage


Have you tried Searching this site?

Unix/Linux/Mac OS X support by phone, email or on-site: Support Rates

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more.

Contact us





May you live long enough to regret your opinions - (Tony Lawrence)

It's more fun to be a pirate than to join the navy. (Steve Jobs)








This post tagged: