=Start=
缘由:
学习需要
正文:
参考解答:
难道是strncat的bug?还是故意为之?
#include <stdio.h> //printf#include <string.h> //memset#include <stdlib.h> //for exit(0);#include <sys/socket.h>#include <errno.h> //For errno - the error number#include <netdb.h> //hostent#include <arpa/inet.h>/*Get ip from domain name (gethostbyname) int hostname_to_ip(char * , char *); */int hostname_to_ip(char * hostname , char* ip){ struct hostent *he; struct in_addr **addr_list; if ( (he = gethostbyname( hostname ) ) == NULL) { perror("gethostbyname"); return 1; } addr_list = (struct in_addr **) he->h_addr_list; int i; for(i = 0; addr_list[i] != NULL; i++) { printf("strlen(ip)-1 = %d\n", strlen(ip)-1); strncat(ip, inet_ntoa(*addr_list[i]), strlen(ip)-1); //在第一个循环中strlen(ip)=0,所以strncat的第3个参数为-1,按理来说应该出错才对,但为啥还是可以正确实现? if(addr_list[i+1] != NULL) strncat(ip, ",", 1); printf("%s\n", inet_ntoa(*addr_list[i])); } return 0;}int main(int argc , char *argv[]){ if(argc <2) { printf("Please provide a hostname to resolve.\n"); exit(1); } char *hostname = argv[1]; char ip[100]; hostname_to_ip(hostname, ip); printf("\n%s resolved to %s\n", hostname, ip); return 0;} |
&
# gcc hostname_to_ip.c -o hostname_to_ip# ./hostname_to_ip www.baidu.comstrlen(ip)-1 = -1220.181.111.188strlen(ip)-1 = 15220.181.112.244www.baidu.com resolved to 220.181.111.188,220.181.112.244 |
参考链接:
- http://www.binarytides.com/hostname-to-ip-address-c-sockets-linux/
- http://man7.org/linux/man-pages/man3/strcat.3.html
=END=