【问题标题】:reading hex values from a file in c从c中的文件读取十六进制值
【发布时间】:2015-12-09 17:04:34
【问题描述】:

作为我正在处理的作业的一部分,我正在尝试使用以下代码步骤从文件中读取十六进制值:

char buf[2048];
FILE *fp = fopen("/home/httpd/AS1/binary.bin", "r");
fgets(buf, 1024, fp);

我创建了一个二进制文件,其值例如 /xff/xff/xff .... 等

每次我使用提供的代码读取文件时,十六进制值(shellcode)都会变成不同的数值

我也无法修改以一次准备一个循环中的值,因为我应该按原样使用代码。

我尝试以各种方式创建包含值的文件:

$ vi shcode.bin
$ vi shcode

我以各种方式将值输入到文件中:

/xff/xff/xff
"/xff/xff/xff"
ÿÿÿ

每次我读取文件时,值都会改变。

我花了无数个小时试图找到一个没有结果的解决方案。你能帮我解决我做错的事情吗

【问题讨论】:

  • 你给的代码跟数值无关,怎么改呢?您所做的只是从文件中读取一个字符串,该文件可能包含任何内容。
  • 至少必须用"rb"打开文件,也就是二进制模式。而且 vi 是 文本 编辑器,而不是二进制文件编辑器。

标签: c file hex binaryfiles shellcode


【解决方案1】:

这将打开一个文本文件并使用fgets 读取包含十六进制值的行。 sscanf 格式," /x%x%n" 跳过任何空格,扫描/,然后扫描x,一个十六进制值,并通过%n 保存offset 中处理的字符数。 usedoffset 允许 sscanf 通过 hex 缓冲区工作。

#include <stdio.h>
#include <stdlib.h>

int main( int argc, char *argv[])
{
    FILE *fp = NULL;
    char hex[1024] = "";
    int each = 0;
    size_t used = 0;
    size_t offset = 0;

    if ( ( fp = fopen ( "shcodes", "r")) == NULL) {
        printf ( "could not open file\n");
        return 1;
    }
    while ( fgets ( hex, sizeof ( hex), fp)) {
        used = 0;
         //work through the string as long the format is matched
        while ( ( sscanf ( hex + used, " /x%x%n", &each, &offset)) == 1) {
            printf ( "sscanf this int %d as hex %x\n", each, each);
            used += offset;
        }
    }
    fclose ( fp);
    return 0;
}

使用的文本文件是

/xff/xff/xff/xff/xff/xff/xff/xff/xff/xff/xff/xff/xff/xff/xff
/x0f/x1f/x2f/x3f/x4f/x5f/x6f/x7f/x8f/x9f/xaf/xbf/xcf/xff/xff
/x01/x11/x21/x31/x41/x51/x61/x71/x81/x91/xa1/xb1/xc1/xf1/xff

这应该适用于二进制文件。 fread 是读取二进制数据的更好选择。 bytes 将存储读取的字节数。

#include <stdio.h>
#include <stdlib.h>

int main( int argc, char *argv[])
{
    FILE *fp = NULL;
    unsigned char hex[1024] = "";
    int each = 0;
    size_t bytes = 0;

    if ( ( fp = fopen ( "shcodes.bin", "rb")) == NULL) {
        printf ( "could not open file\n");
        return 1;
    }
    //loop as long as there are bytes to read
    while ( ( bytes = fread ( &hex, 1, 1024, fp)) > 0) {
        for ( each = 0; each < bytes; each++) {
            printf ( "read this char as int %u and as hex %x\n", hex[each], hex[each]);
        }
    }
    fclose ( fp);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2015-05-01
    • 2014-02-25
    • 2012-04-04
    • 1970-01-01
    • 2011-10-07
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    相关资源
    最近更新 更多