#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "utils.h"

unsigned long int ctoip(char *s) {
unsigned long int i=0;
char *dot1,*dot2,*dot3;
char p[30];

snprintf(p,sizeof(p),"%s",s);

dot1=(char *)index(p,'.');
if(dot1) {
    dot1++[0]=0;
    i=256*256*256*atol(p);
    dot2=(char *)index(dot1,'.');
    if(dot2) {
	dot2++[0]=0;
	i+=256*256*atol(dot1);
	dot3=(char *)index(dot2,'.');
	if(dot3) {
	    dot3++[0]=0;
	    i+=256*atol(dot2)+atol(dot3);
	    return i;
	    }
	}
    }
return -1;
}

/* 
2=unknown
1=false
0=pass
*/

int check_ip4(char *ip ,char *client_address, char *net) {
unsigned long int dip=ctoip(ip);
unsigned long int cip=ctoip(client_address);
int k=32-atoi(net);

if(dip<0)return 2;
if(cip<0)return 2;

if(k>=0 && k<=32) {
    if((dip>>k) == (cip>>k))return 0;
    }
return 1;
}

int rev_addr(char *sa_org, char *ra, int sizera) {
char *dot1,*dot2,*dot3;
char sa[100];

snprintf(sa,sizeof(sa),"%s",sa_org);

dot1=(char *)index(sa,'.');
if(dot1) {
    dot1++[0]=0;
    dot2=(char *)index(dot1,'.');
    if(dot2) {
	dot2++[0]=0;
	dot3=(char *)index(dot2,'.');
	if(dot3) {
	    dot3++[0]=0;	    
	    snprintf(ra,sizera,"%s.%s.%s.%s",dot3,dot2,dot1,sa);
	    return 1;
	    }
	}
    }
return 0;
}
