开发者

How to get magic number of a binary file

There is a magic number associated with each binary file , does anyone know how to retrieve this informatio开发者_JAVA技巧n from the file?


file <file_name>

magic numbers are usually stored in (linux):

/usr/share/file/magic

also check this link, someone was trying to use libmagic to get the information in C program, might be useful if you're writing something yourself.


Use libmagic from the file package to try and sniff out the type of file if that's your goal.

There are no general "magic" numbers in binary files on unix, though different formats might define their own. The above library knows about many of those and also use various other heuristics to try and figure out the format/type of file.


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


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

It's complex, and depends on the specific file type you're looking for.


There is a file command which in turn uses a magic library, the magic library reads from a file found in /etc called magic (this is installation dependant and may vary), which details what are the first few bytes of the file and tells the file what kind of a file it is, be it, jpg, binary, text, shell script. There is an old version of libmagic found on sourceforge. Incidentally, there is a related answer to this here.

Hope this helps, Best regards, Tom.


Expounding on @nos's answer:

Example below uses the default magic database to query the file passed on the command line. (Essentially an implementation of the file command. See man libmagic for more details/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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜