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
You don’t even need
strtok()to do this, since all you care about is the first string of characters before a space. Usestrchr()to locate the first space, set it toNUL, and you’re done:You could actually collapse it a little bit by doing this:
Instead of:
But that’s not quite as clear, and it would be harder to do proper error checking.