file(1)ユーティリティに付属しているlibmagic.soライブラリを活用できます。ELF、bash / python/perlスクリプトなどのすべての実行可能ファイルを検出できます
これが私のコードです:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "magic.h"
int
main(int argc, char **argv)
{
struct magic_set *ms;
const char *result;
char *desired;
size_t desired_len;
int i;
FILE *fp;
ms = magic_open(MAGIC_RAW);
if (ms == NULL) {
(void)fprintf(stderr, "ERROR opening MAGIC_NONE: out of memory\n");
return -1;
}
if (magic_load(ms, NULL) == -1) {
(void)fprintf(stderr, "ERROR loading with NULL file: %s\n", magic_error(ms));
return 11;
}
if (argc > 1) {
if (argc != 2) {
(void)fprintf(stderr, "Usage: ./a.out </path/to/file>\n");
} else {
if ((result = magic_file(ms, argv[1])) == NULL) {
(void)fprintf(stderr, "ERROR loading file %s: %s\n", argv[1], magic_error(ms));
return -1;
} else {
if (strstr(result, (const char *)"executable")) {
printf("%s: is executable\n", argv[1], result);
}
}
}
}
magic_close(ms);
return 0;
}
$ gcc test.c -I / path / to / magic.h /usr/lib/libmagic.so.1
./a.out / bin / ls
./a.out a.out
./a.out test.c