How to get magic number of a binary file

别来无恙 提交于 2019-11-26 21:19:27

问题


There is a magic number associated with each binary file , does anyone know how to retrieve this information from the file?


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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

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




回答5:


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.




回答6:


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;
    }

}


来源:https://stackoverflow.com/questions/2147484/how-to-get-magic-number-of-a-binary-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!