Linux下用C语言通过HOSTNAME获取对应IP


=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.com
strlen(ip)-1 = -1
220.181.111.188
strlen(ip)-1 15
220.181.112.244
www.baidu.com resolved to 220.181.111.188,220.181.112.244
参考链接:

=END=


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注