How to get the magic number of a binary file

Each binary has a magic number associated with it. Does anyone know how to extract this information from a file?

+9
unix file-type magic-numbers
source share
6 answers

Use libmagic from the file package to try to determine the type of file, if that is your goal.

Unix does not have common β€œmagic” numbers in binary files, although different formats can define their own. The above library knows about many of them, and also uses various other heuristic methods to figure out the file format / type.

+6
source share
file <file_name> 

magic numbers are usually stored in (linux):

 /usr/share/file/magic 

also check this link, someone tried to use libmagic to get information in a C program, it may be useful if you write something yourself.

+8
source share

The unix file command uses a magic number. see the man file for more information. (and where to find the magic file)

+1
source share

Read this: http://linux.die.net/man/5/magic

It is complex and depends on the specific type of file you are looking for.

+1
source share

There is a file command, which, in turn, uses the magic library, the magic library reads from the file found in / etc, magic (it depends on the installation and may vary), which describes in detail the first few bytes of the file and tells file which file it is: jpg, binary, text, shell script. Sourceforge has an old version of libmagic. By the way, there is a corresponding answer to this one here .

Hope this helps, Regards, Tom.

+1
source share

Clarification of @nos answer:

The example below uses the default magic database to query the file passed on the command line. (Essentially, the implementation of the file command. See man libmagic for more information on functions.

 #include <iostream> #include <magic.h> #include <cassert> int main(int argc, char **argv) { if (argc == 1) { std::cerr << "Usage " << argv[0] << " [filename]" << std::endl; return -1; } const char * fname = argv[1]; magic_t cookie = magic_open(0); assert (cookie !=nullptr); int rc = magic_load(cookie, nullptr); assert(rc == 0); auto f= magic_file(cookie, fname); if (f ==nullptr) { std::cerr << magic_error(cookie) << std::endl; } else { std::cout << fname << ' ' << f << std::endl; } } 
0
source share

All Articles