您当前的位置:首页 > 计算机 > 编程开发 > C语言

判断字符串是IP还是域名

时间:03-26来源:作者:点击数:

判断字符串是IP还是域名

int ip(char *input)
{
        // Assume input is domain name
    int is_domain = 1;

    // Check if input is a valid IP address
    for (const char *p = input; *p != '\0'; p++) {
        if (!isdigit(*p) && *p != '.') {
            is_domain = 1;
            break;
        }
        if (*p == '.') {
            is_domain = 0;
        }
    }

    // If not a valid IP address, try resolving as domain name
    if (is_domain) {
        struct hostent *h = gethostbyname(input);
        if (h == NULL) {
            printf("Failed to resolve domain %s\n", input);
            return -1;
        }
        printf("%s is a domain name.\n", input);
        return 1;
    }
    else {
        struct in_addr ip;
        if (inet_pton(AF_INET, input, &ip) == 1) {
            printf("%s is an IP address.\n", input);
            return 2;
        } else {
            printf("%s is not a valid IP address.\n", input);
            return -1;
        }
    }
}



int hostname_to_ip(char *hostname, char *ip) {
    struct hostent *he;
    struct in_addr **addr_list;
    int i;

    if ((he = gethostbyname(hostname)) == NULL) {
        return 1;
    }

    addr_list = (struct in_addr **) he->h_addr_list;

    for (i = 0; addr_list[i] != NULL; i++) {
        strcpy(ip, inet_ntoa(*addr_list[i]));
        return 0;
    }

    return 1;
}


int main() {
    char input[256];
    char output[20];
    printf("Enter a string to check: ");
    scanf("%s", input);


    int ret = ip(input);

    if(ret == 1)
    {
        hostname_to_ip(input, output);
    }
    
    printf("ip:%s\n",output);

    return 0;
}

 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门