-3

I am a newbie in programming and to improve my programming skills i started working on this small project and got stuck. Project is about capturing the keys that are been hit by the user(more like a keylogger) and store them in a text format. i was able to do that in windows but not in linux. Preferred language is C, shell scripting.

Any help is appreciated.

I able to get a keystrokes on terminal but not on other application.

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<termios.h>
#include<unistd.h>
#include<fcntl.h>
int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}
main( int argc, char** argv )
{
char *input = argv[0];
int nomor = argc;
pid_t pid = 0;
int x=0;
while(1)
{
if(kbhit()){
//clearing the buffer
char ch = getchar();
printf("you hit keyboard and key = %c\n", ch);
}
}
}
  • 1
    possible duplicate of [Capturing Keystrokes in GNU/Linux in C](http://stackoverflow.com/questions/1485116/capturing-keystrokes-in-gnu-linux-in-c) – lulyon Sep 08 '13 at 13:51
  • i tried. All i can get is keystrokes from only terminal and not from other application. – user2758951 Sep 08 '13 at 13:53
  • show us what you tried so far – Farouq Jouti Sep 08 '13 at 13:55
  • @lulyon : i came across that question. i woukd really appreciate if you can tell me what should be the argument for that program?? n can also provide some information about device(variable used in that program) – user2758951 Sep 08 '13 at 13:58
  • @user2758951 You probably have notice aemus's answer in the link. Try replace argv[0] with /dev/input/event0 for keyboard. Or event1, event2...event31. – lulyon Sep 08 '13 at 14:14
  • I tried that but m not getting anything. – user2758951 Sep 08 '13 at 14:23
  • c'mom guys, i know you think that this is some silly question. but c'mom, help me out here. Atleast tell me what should i do to solve this problem?? – user2758951 Sep 08 '13 at 14:24

1 Answers1

1

Capturing keys in "all situations" in Linux is nearly impossible.

The reason is that key handling on the console is completely different from key handling on the X Window system.

If you only want to capture keys while the X Window system is active (when Linux runs using a GUI) you should use "XQueryKeymap". You need to create a handle to the X server (the Linux GUI) using "XOpenDisplay". Then you can use "XQueryKeymap" to check which of the keys is currently down. Unfortunately it is not easy to get the ASCII codes of these keys!

Martin Rosenau
  • 17,897
  • 3
  • 19
  • 38