#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define IPATH "input.txt"
int main(int argc, char *argv[]){
char *ListBuffer;
int ListSize;
int ListCount = 0;
FILE *InputFile = fopen(IPATH, "r");
fseek(InputFile, 0, SEEK_END);
ListSize = ftell(InputFile);
ListBuffer = malloc(ListSize 1);
memset(ListBuffer, 0, ListSize 1);
fseek(InputFile, 0, SEEK_SET);
fread(ListBuffer, ListSize, 1, InputFile);
for (int i = 0; ListBuffer[i] != 0; i ) {
if (ListBuffer[i] == '\n')
ListCount ;
}
int ListHeight = ListCount 1;
char *ListList[ListHeight - 1];
char *str1 = NULL;
char *temp1 = strtok_r(ListBuffer, "\n", &str1);
int len = 0;
while (temp1 != NULL){
ListList[len] = temp1;
temp1 = strtok_r(NULL, "\n", &str1);
len ;
}
char *name = "www.naver.com";
struct hostent *host; //i think ListList[0] == "www.naver.com"
host = gethostbyname(name); //<= i want change variable name to ListList[0]
//host = gethostbyname(ListList[0]); like this
printf("%s\n", name);
printf("%s\n", inet_ntoa(*(struct in_addr *)host->h_addr_list[0]));
}
里面 input.txt

我認為這個 txt 在 c => "www.naver.com\nwww.google.co.kr\nwww.stackoverflow.com" 上打開
所以用“\n”作為key,分成二維陣列。
所以我認為 (name == ListList) 和列印這個值是一樣的!
這是相同的字串,但我不知道為什么會出現錯誤。幫我。
uj5u.com熱心網友回復:
上面的代碼運行良好,但一個問題是當 dns 查詢失敗時(例如:網路問題)->gethostbyname將回傳null
gethostbyname在這種情況下,您需要在使用前處理檢查回傳結果
如果您不信任您的代碼,讓我們使用一些工具來驗證 dns 查詢是否成功,使用 dig 工具、wireshark、...
以下是我檢查的內容kbphonemall.com-> dns 服務器沒有答案->host變數為空-> 您的程式在您的評論中出現了段錯誤
dig kbphonemall.com
; <<>> DiG 9.10.3-P4-Ubuntu <<>> kbphonemall.com
;; global options: cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 14201
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4000
;; QUESTION SECTION:
;kbphonemall.com. IN A
;; AUTHORITY SECTION:
com. 759 IN SOA a.gtld-servers.net. nstld.verisign-grs.com. 1646983748 1800 900 604800 86400
;; Query time: 86 msec
;; SERVER: 127.0.1.1#53(127.0.1.1)
;; WHEN: Fri Mar 11 14:31:46 07 2022
;; MSG SIZE rcvd: 117
檢查 stackoverflow.com -> 它有 151.101.1.69,...
dig stackoverflow.com
; <<>> DiG 9.10.3-P4-Ubuntu <<>> stackoverflow.com
;; global options: cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 52635
;; flags: qr rd ra; QUERY: 1, ANSWER: 4, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4000
;; QUESTION SECTION:
;stackoverflow.com. IN A
;; ANSWER SECTION:
stackoverflow.com. 35 IN A 151.101.1.69
stackoverflow.com. 35 IN A 151.101.65.69
stackoverflow.com. 35 IN A 151.101.193.69
stackoverflow.com. 35 IN A 151.101.129.69
;; Query time: 84 msec
;; SERVER: 127.0.1.1#53(127.0.1.1)
;; WHEN: Fri Mar 11 14:50:20 07 2022
;; MSG SIZE rcvd: 110
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/441821.html
