I trying to do a program let user input a host name which can't more than 10 characters and follow by input the IP address , the program need to validate the IP that user input is correct . The the end store the information in the struct and print out the host name and IP address once user finish input.(do 5 times)
The program can be compile ,but the program is hang and quit after finish input,doesn't print out any result.
Here is my code
Code:
#include <stdio.h>#include <stdlib.h>
#include <string.h>
#define DELIM "."
#define MAX 10
typedef struct data
{
int a;
int b;
int c;
int d;
char host[MAX];
}IP;
//IP = {a,b,c,d,"hostname"};
//struct data result[]={};
/* return 1 if string contain only digits, else return 0 */
int valid_digit(char *ip_str)
{
while (*ip_str) {
if (*ip_str >= '0' && *ip_str <= '9')
++ip_str;
else
return 0;
}
return 1;
}
/* return 1 if IP string is valid, else return 0 */
int is_valid_ip(char *ip_str)
{
int i, num, dots = 0;
char *ptr;
char *token;
char *flds[5];
IP ip;
//struct data x;
if (ip_str == NULL)
return 0;
ptr = strtok(ip_str, DELIM);
//x.a= ptr;
//printf("the %c",result[0].a);
if (ptr == NULL)
return 0;
while (ptr) {
/* after parsing string, it must contain only digits */
if (!valid_digit(ptr)){
printf("The ip address should contain digit only\n");
return 0;
}
num = atoi(ptr);
//printf("\npart 1 ip: %s\n",ptr);
/* check for valid IP */
if (num >= 0 && num <= 255) {
/* parse remaining string */
ptr = strtok(NULL, DELIM);
//printf("\npart 2 ip: %s",ptr);
if (ptr != NULL)
++dots;
} else{
printf("The ip address range should be 0~25\n");
return 0;
}
flds[i] = ptr;
i++;
ptr = strtok(NULL, DELIM);
ip.a = atoi(flds[0]);
ip.b = atoi(flds[1]);
ip.c = atoi(flds[2]);
ip.d = atoi(flds[3]);
strcpy(ip.host, flds[4]);
}
/* valid IP string must contain 3 dots */
if (dots != 3){
printf("invalid format for ip address. should be x.x.x.x\n");
return 0;
}
return 1;
}
int main()
{
int i;
//IP ip;
char *token;
char *flds[5];
char ip1[MAX];
char hostname[MAX];
//char ip1[] = "128.2500.0.1";
//is_valid_ip(ip1)? printf("Valid\n"): printf("Not valid\n");
//is_valid_ip(ip2)? printf("Valid\n"): printf("Not valid\n");
for(i=0;i<6;i++){
printf("Please enter host name\n");
scanf("%s",&hostname);
while( strlen(hostname) > MAX)
{
printf("invalid please type again\n");
scanf("%c",&hostname);
}
printf("Please enter ip\n");
scanf("%s",ip1);
while(!is_valid_ip(ip1))
{
printf("invalid , please enter again\n");
scanf("%s",ip1);
}
printf("Valid\n");
printf("Host :%s\n",hostname);
printf("The %d Ip address you entered:%s\n",i+1,ip1);
//printf("Host :%s\n",hostname);
//printf("IP = %d.%d.%d.%d\n", a,b,c,d);
}
system("PAUSE");
return 0;
}