Skip to content

Instantly share code, notes, and snippets.

@pawitp
Created October 21, 2012 01:44
Show Gist options
  • Save pawitp/3925413 to your computer and use it in GitHub Desktop.
Save pawitp/3925413 to your computer and use it in GitHub Desktop.
UInput Event Injector (Inject Event into Android via kernel)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/input.h>
#include <linux/uinput.h>
#define die(str, args...) do { \
perror(str); \
exit(EXIT_FAILURE); \
} while(0)
static void send_event(int fd, uint16_t type, uint16_t code, int32_t value) {
struct input_event event;
int err;
memset(&event, 0, sizeof(event));
event.type = type;
event.code = code;
event.value = value;
gettimeofday(&event.time, NULL);
if (write(fd, &event, sizeof(event)) < 0) {
die("event sent error: %s", strerror(errno));
}
}
int main()
{
int fd;
struct uinput_user_dev uidev;
int i;
uint16_t type, code;
int32_t value;
fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
if (fd < 0)
die("error: open");
// Keyboard
if (ioctl(fd, UI_SET_EVBIT, EV_KEY) < 0)
die("error: ioctl");
for (i = 0; i < 256; i++) {
if (ioctl(fd, UI_SET_KEYBIT, i) < 0)
die("error: ioctl");
}
// Mouse
if (ioctl(fd, UI_SET_EVBIT, EV_REL) < 0)
die("error: ioctl");
if (ioctl(fd, UI_SET_RELBIT, REL_X) < 0)
die("error: ioctl");
if (ioctl(fd, UI_SET_RELBIT, REL_Y) < 0)
die("error: ioctl");
for (i = BTN_LEFT; i <= BTN_TASK; i++) {
if (ioctl(fd, UI_SET_KEYBIT, i) < 0)
die("error: ioctl");
}
memset(&uidev, 0, sizeof(uidev));
snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "Input Injector");
uidev.id.bustype = BUS_VIRTUAL;
uidev.id.vendor = 0;
uidev.id.product = 0;
uidev.id.version = 0;
if (write(fd, &uidev, sizeof(uidev)) < 0)
die("error: write");
if (ioctl(fd, UI_DEV_CREATE) < 0)
die("error: ioctl");
do {
scanf("%hu %hu %d", &type, &code, &value);
send_event(fd, type, code, value);
} while (type != 65535);
if (ioctl(fd, UI_DEV_DESTROY) < 0)
die("error: ioctl");
close(fd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment