我正在尝试用c ++编写一个CGI脚本,它打印反向网络路径(使用 traceroute)从Web服务器到调用CGI脚本的客户端的IP地址。
当我在Visual Studio中运行程序时,它工作正常(创建进程,将结果打印到“C:/result.out”文件,打开文件,从文件打印每一行,关闭文件)但编译后并尝试只运行其.exe文件,它会抛出异常。我该怎么做才能使.exe正常工作? 就像一张纸条,我正在使用Windows XP和Visual C ++ 2008
这是代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <process.h>
#include <conio.h>
int main()
{
char *line, *command, *userIp;
printf("Content-Type:text/html\n\n");
printf("<html><head></head><br/>");
printf("<body><br/>");
line = (char*)malloc(255*sizeof(char));
command = (char*)malloc(10*sizeof(char));
userIp = (char*)malloc(30*sizeof(char));
//userIp = getenv("REMOTE_ADDR"); // use a default IP until program works
strcpy(command,"tracert ");
strcpy(userIp,"74.125.87.104");
strcat(command,userIp);
strcat(command," > C:/result.out");
// create command "tracert 74.125.87.104 > C:/result.out"
printf("%s",command);
system(command);
FILE *f;
f = fopen("C:/result.out","r"); // open C:/result.out and read line - by - line
strcpy(line,"");
while(!feof(f)){
fgets(line,255,f);
printf("%s\n",line);
}
fclose(f);
printf("<br/>Test running OK<br/>");
printf("</body></html>");
getch();
return 0;
}
答案 0 :(得分:3)
您的Web服务器(sanely)很可能无权写入c:\。要么为临时文件使用正确的位置,要么tracert
将结果传回给可执行文件,以便捕获它们。
答案 1 :(得分:0)
以下两行导致缓冲区溢出
strcat(command,userIp);
strcat(command," > C:/result.out");
所以这可能是崩溃的结果。
除非抛出异常,否则请不要使用术语“异常”,因为您编写的C代码不太可能。所以这不是一个例外。
不是使用system()运行命令并将结果传递给文件,而是使用popen()命令,这将运行命令并将输出传递给您可以像文件一样读取的流(但没有安全性)写入文件系统的含义。)
FILE *f;
f = popen(command,"r"); // run the command. The std out goes to the FILE stream
^^^^^^
strcpy(line,"");
while(!feof(f)){
fgets(line,255,f);
printf("%s\n",line);
}
fclose(f);