gpt4 book ai didi

c - 运行程序固定时间

转载 作者:行者123 更新时间:2023-11-30 18:36:12 24 4
gpt4 key购买 nike

我正在尝试编写一个可以运行有限次数的代码(就像在试用版本中发生的那样),比如 5 次或 10 次。之后代码将无法运行。我有一个方法,但它修改了源代码。我不想那样。此外,禁止使用外部文件。这是我使用源代码修改方法的代码 - 你必须将 fseek 值(此处为 38)计算 int x=5 中 5 的位置。 (不确定是否清楚)

#include<stdio.h>
int main(){
int x=5;
char c;
FILE *f;

if(x>0){
f=fopen("FT.c","r+");
fseek(f,38,SEEK_SET);
fprintf(f,"%d",--x);
fclose(f);
printf("%d time left",x);

}else{
printf("you cannot run more than 5 time");

}
return 0;

}

注意我不想再次编译源代码。我希望制作可执行文件,然后该 .exe 文件可以运行有限的时间

最佳答案

你可以这样做,但这不是一个好主意。

您要求的是 Digital Rights Management or DRM但它不起作用。即使是最大的软件公司也无法使其可靠地工作,其根本原因是,如果我可以运行你的代码,我就可以修改你的代码。所有 DRM 都是一个减速带。你改变二进制中的数字的想法很容易被发现和失败。友情提示:不要在这上面浪费时间。相反,拥有许可证并强制执行,或者不要分发您的软件(即将其作为服务器提供)。

<小时/>

但是让我们将其作为练习。

将一个数字附加到已编译的可执行文件的末尾。可执行文件读取该值以确定其剩余次数,并用新的次数重写它。

有多种方法可以将数字放在末尾。您可以使用十六进制编辑器在那里编写它。我使用了一个小的 Perl 程序来写入 4 个字节。

# It's backwards because x86 machines are little-endian.
# And you're probably on an x86 machine.
$ perl -we 'open my $fh, ">>", shift; print $fh "\x03\x00\x00\x00";' executable

这意味着程序必须...

  1. 使用argv[0]打开自身。
  2. 从末尾开始查找 4 个字节。
  3. 将最后 4 个字节读取为 4 字节整数。
  4. 检查它是否不为 0。

我们需要读取/写入特定数量的字节,因此我将使用 uint32_t 来获得固定大小的 4 字节整数。

// Open our own executable for reading.
FILE *fp = fopen(argv[0], "rb");
if( fp == NULL ) {
fprintf( stderr, "Can't open %s for %s: %s", argv[0], mode, strerror(errno) );
exit(-1);
}

// Seek 4 bytes from the end.
if( fseek( fp, -4, SEEK_END ) != 0 ) {
fprintf( stderr, "Can't seek: %s", strerror(errno) );
exit(-1);
}

// Read 4 bytes
uint32_t times = 0;
fread( &times, 4, 1, fp );

if( times == 0 ) {
printf("Program expired. Please give me $money$.\n");
exit(-1);
}
else {
printf("You have %d tries remaining.\n", times);
}

写作非常相似。

  1. 使用argv[0]打开自身。
  2. 从末尾开始查找 4 个字节。
  3. 写下新的剩余次数。
// Open our own executable for reading & writing.
// Can't use "a", that will always write to the end of the file.
// Can't use "w", that will erase the file.
FILE *fp = fopen(argv[0], "r+b");
if( fp == NULL ) {
fprintf( stderr, "Can't open %s for %s: %s", argv[0], mode, strerror(errno) );
exit(-1);
}

// Seek 4 bytes from the end.
if( fseek( fp, -4, SEEK_END ) != 0 ) {
fprintf( stderr, "Can't seek: %s", strerror(errno) );
exit(-1);
}

fwrite( &times, 4, 1, fp );
<小时/>

同样,这种形式的复制保护几乎不是一个减速带。任何知道什么是十六进制编辑器的人都可以轻松识别它并破解它。任何不会的人都可以在 Google 上搜索会的人编写的说明。此答案仅供练习。

关于c - 运行程序固定时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42616734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com