Search code examples
cipprintfcut

How to printf() only the first part of a string


I have written a small program in C to get IP from remote user who log into SSH session

Code :

int main (){
    char * getIP ;
    getIP = getenv ("SSH_CLIENT");
    printf ("%s", getIP);
    printf("\n");
    return 0;
}

It works great and on output I have

shell# ./a.out

192.168.1.33 39840 22

But I would like to print only the IP address and not the rest of the string. I can't figure out how cut the string to print only the first part (255.255.255.255)

I search whole day solution but without success :/

Thanks for any help : )

UPDATE !

I discovered that instead SSH_CLIENT you can use REMOTEHOST : )
But Larsks solution is very helpful and worth remembering


Solution

  • You don't even need strtok() to do this, since all you care about is the first string of characters before a space. Use strchr() to locate the first space, set it to NUL, and you're done:

    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    int main (){
        char *getIP, *mark;
        int i;
        getIP = getenv ("SSH_CLIENT");
    
        // get the location of the first space character
        mark = strchr(getIP, ' ');
    
        // set it to 0 (ascii NUL)
        *mark = 0;
        printf ("%s\n", getIP);
        return 0;
    }
    

    You could actually collapse it a little bit by doing this:

    *(strchr(getIP, ' ')) = 0;
    

    Instead of:

    mark = strchr(getIP, ' ');
    *mark = 0;
    

    But that's not quite as clear, and it would be harder to do proper error checking.