我正在尝试模拟 DNS 服务器的行为,我有一个名为 contains 的数据库hosts.txt
,machine_names/IP_addresses
例如:
equipo_00/169.0.1.169
sala_oeste_01/200.1.2.200
sala_oeste_02/200.2.3.200
sala_oeste_03/200.3.4.200
MEMFIS_04/201.4.5.201
ICARO_05/200.5.6.200
equipo_06/169.6.7.169
sala_este_07/201.7.8.201
sala_este_08/201.8.9.201
CEC_09/189.9.10.189
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char** argv)
{
char* machine, *ip_add;
FILE* db;
char* flag;
char tmp[256];
char par[256];
printf("> ");
scanf("%s", par);
db = fopen("hosts.txt", "r");
while(db != NULL && fgets(tmp, sizeof(tmp), db) != NULL)
{
if(strstr(tmp, par))
{
flag = "1"; // flag setting to 1 means find the line
machine = strtok(tmp, "/");//here's supposed to get the value of the machine
ip_add = strtok(NULL, "/");//here's supposed to get the value of the ip adress
}
}//while
if(strcmp(flag, "1") == 0) //
{
printf("here\n");
}
else
{
flag = "0"; //flag setting to 0
printf("there\n");
}
printf("flag= %s pc=%s server=%s\n", flag, machine, ip_add);
return 0;
}
我的代码从标准输入读取机器的值并指示分配给服务器上该机器的 IP 地址。问题是程序行为不正常,我不知道如何将我的代码修改为预期的输出,例如
input: equipo_00
output: flag = 1 pc = equipo_00 server=169.0.1.169
对不起,如果这个问题很愚蠢,我是这门语言的新手.. 谢谢大家的帮助,请原谅我的英语