判断字符串是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;
}