首先假设输入字符串为域名,然后检查输入字符串是否是一个合法的IPv4地址。如果不是,则将输入字符串解析为域名,并输出结果。如果是一个合法的IPv4地址,则直接输出结果。注意,上述代码使用了inet_pton
函数将输入字符串解析为in_addr
结构体,如果返回值为1,则说明解析成功。
#include <stdio.h> #include <netdb.h> #include <arpa/inet.h> #include <ctype.h> int main() { char input[256]; printf("Enter a string to check: "); scanf("%s", 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); } else { struct in_addr ip; if (inet_pton(AF_INET, input, &ip) == 1) { printf("%s is an IP address.\n", input); } else { printf("%s is not a valid IP address.\n", input); return 1; } } return 0; }
标签:domain,IP,域名,printf,字符串,input,include From: https://www.cnblogs.com/zhuangquan/p/17126134.html