#include #include #include char*chkip(char*ip) { int dots=0; int consecdig=0; char*sp; if(strlen(ip)>15)return "Too long IP."; if(strlen(ip)<7)return "Too short IP."; sp=ip; if(atoi(ip)>255)return "Too high number in IP."; while(sp[0]) {if(isdigit(sp[0])){consecdig++;if(consecdig>3)return "Too many consecutive digits in IP.";} else if(sp[0]=='.'){dots++;if(consecdig<1)return "Not enough consecutive digits in IP.";consecdig=0; if(dots>3)return "Too many dots in IP.";if(atoi(sp+1)>255)return "Too high number in IP.";} else return "Invalid character in IP."; sp++;} if(dots<3)return "Not enough dots in IP."; return NULL; } int replaceline(char*file,char*ip,char*name) { FILE*f; char s[1026],*sp,*sp1; char s1[32]; int offs; int replaces=0; if(strlen(name)>16)name[15]=0; sp=chkip(ip);if(sp){fprintf(stderr,"ERROR: Invalid IP address '%s': %s\n",ip,sp);return -1;} f=fopen(file,"r+");if(!f){fprintf(stderr,"ERROR: Cannot open file '%s'.\n",file);return -1;} while(!feof(f)) { offs=ftell(f);s[0]=0;fgets(s,1024,f); if(s[0]=='#')continue; sp=strchr(s,'\n');if(sp)sp[0]=0; if(s[0]=='\n')continue; sp=strstr(s,"##AUTOSET:");if(!sp)continue;sp+=10; if(strcasecmp(sp,name))continue; snprintf(s1,15,"%s ",ip);s1[15]=0; if(s[16]!=' '){fprintf(stderr,"ERROR: No or not enough trailing spaces after IP in '%s' in line %s.\n",file,s);return -1;} fseek(f,offs,SEEK_SET); fprintf(f,"%s",s1); fgets(s,1024,f); replaces++; } fclose(f); if(replaces<1){fprintf(stderr,"ERROR: No label '%s' found.\n",name);return 1;} return 0; } void help() { printf("Autohosts v1.0\n" "Automatically changes IP address in hosts file.\n" "Usage: autohosts \n" "Where: is the hosts file (usually /etc/hosts)\n" " is the IP address (basic checks are performed on it)\n" " is the ID of the line in the hosts file.\n" "The line in the hosts file has to be specified in specific format:\n" "#AUTOSET:\n" "The total length of the and field has to be\n" "at least one space over 15 characters (the maximum length of an IPv4 address)\n" "in order to be able to just overwrite the address in the file.\n" ); } int main(int argc,char*argv[]) { if(argc!=4){help();return 0;}; return replaceline(argv[1],argv[2],argv[3]); }