Вы находитесь на странице: 1из 4

#include <stdlib.

h>
#include <malloc.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>

#define BACKSPACE 8
#define ENTER 13
#define BLANK 32
#define SIZE 32
#define BEEP putch(7)
#define SPACE 32
#define IGNORE BEEP;continue
#define MAX 36
void Backspace (void);
char * GetIP (void);
int main (void)
{

printf("Enter your IP Address\n->");


printf("\n\nYour IP Address is %s",GetIP());
getch();
return EXIT_SUCCESS;
}
void Backspace (void)
{
putch(BACKSPACE);
putch(BLANK);
putch(BACKSPACE);
}

char * GetIP (void)


{
char ch;
char *buffer, *check, *check2;
int pos=0,cpos=0;//buffer position and check position
int period=0,indexPeriod;
register int i;

//IP add can have max 16 char including NULL eg 255.255.255.255+'\0'


buffer = (char *) malloc(16 * sizeof(char));
//Each octet in an IP address can have max 4 char inc NULL eg 255 + '\0'
check = (char *) malloc(4 * sizeof(char));
//Backup check
check2 = (char *) malloc(4 * sizeof(char));
while (pos<15)//15th index position is NULL
{
ch=getch();
switch(ch)
{
case BACKSPACE :
if(pos==0)//Cant backspace when buffer empty
{
IGNORE;
}
if(buffer[pos-1] == '.')
{
period--;
/***RELOAD BACKUP check2***/
i=0;
while(check2[i]!=NULL)
{
check[i]=check2[i];
i++;
}
check[i]=NULL;
cpos=i;
}
else
{
check[--cpos]=NULL;
}
Backspace();
buffer[--pos]=NULL;
continue;
case ENTER :
if(period!=3) // period must be atleast 3 for ip address
{
IGNORE;
}
//If period is three,
//Get index of third period
for(i =0; i<15; i++)
{
if(buffer[i]== '.')
{
indexPeriod=i;
}
}

//After third period there MUST be one more octet After it eg 255.
255.255.HERE
if(buffer[indexPeriod+1]!=NULL)
{
buffer[pos]=NULL;
//Make While Loop Stop
pos=99;
break;
}
else
{
IGNORE; //eg 192.168.1.NULL
}

case '.' :
if(pos==0)//cannot start ip with a period
{
IGNORE;
}
if(buffer[pos-1]=='.')//ip address cant haf double periods
{
IGNORE;
}
if(period==3) // ip address max periods is 3
{
IGNORE;
}
buffer[pos]=putch(ch);
period++;

//Backup and Reset check array


for(i=0; i<4;i++)
{
check2[i]=check[i];
check[i]=NULL;
}
cpos=0;
break;
default :
if(!isdigit(ch))
{
IGNORE;
}
else
{
if(cpos==3) // if an octet has more than 3 digits, ignore additi
onal digits to be entered
{
IGNORE;
}
//Checking octets numerical range
check[cpos]=ch;
check[++cpos]=NULL;
if(atoi(check)<256)
{
buffer[pos]=putch(ch);
}
else
{
check[--cpos]=NULL;
IGNORE;
}
}
}//end of switch
pos++;
}//end of while
return buffer;
}

Вам также может понравиться