/* Poor man dhcp sort of The idea is to allocate an IP number (for a vserver) based on its name (a key). You use this when you have many vservers running on a host in a private network. This host is seen as a gateway to the private server. This is useful for test environnement where new vservers appear and go. */ #include #include #include #include #include #include #include #include using namespace std; static const char *lockfile = "/var/run/alloc_ip.lock"; static const char *datafile = "/var/run/alloc_ip.data"; typedef map mapss; typedef mapss::iterator mapss_it; #include "vipalias.lock.h" int main (int argc, char *argv[]) { int ret = -1; if (argc != 3){ fprintf (stderr,"alloc_ip key IP_prefix\n"); fprintf (stderr,"alloc_ip server1 192.168.1\n"); }else{ const char *argkey = argv[1]; const char *ipprefix = argv[2]; if (vipalias_lock() != -1){ mapss mp; set st; FILE *fin = fopen (datafile,"r"); if (fin != NULL){ char buf[100]; while (fgets(buf,sizeof(buf)-1,fin)!=NULL){ char key[100],ip[100]; if (sscanf(buf,"%s %s",ip,key)==2){ mp[key] = ip; st.insert (ip); } } fclose (fin); } bool changed = false; mapss_it it=mp.find(argkey); if (it == mp.end()){ for (int i=1; i<254; i++){ char tmp[20]; snprintf (tmp,sizeof(tmp)-1,"%s.%d",ipprefix,i); if (st.count(tmp)==0){ mp[argkey] = tmp; printf ("%s\n",tmp); changed = true; ret = 0; break; } } if (!changed){ fprintf (stderr,"No IP available\n"); } }else{ printf ("%s\n",it->second.c_str()); ret = 0; } if (changed){ FILE *fout = fopen (datafile,"w"); if (fout == NULL){ fprintf (stderr,"Can't open datafile %s (%s)\n" ,datafile,strerror(errno)); }else{ for (mapss_it it=mp.begin(); it != mp.end(); it++){ fprintf (fout,"%s %s\n",it->second.c_str() ,it->first.c_str()); } fclose (fout); } } vipalias_unlock(); } } return ret; }