Reputation: 11768
I have a simple routing daemon made by me witch automatically routes some packets witch arrive on my ip on other ip's. The daemon runs great but after a while the function witch retrieves the ip's from database fails and I have no idea why.
Here is my code:
#include "database.h"
BOOL getip(char * ip,int * port,BOOL serie)
{
MYSQL * conn,mysql;
MYSQL_RES * res;
MYSQL_ROW row;
char * server = "mysqldbhost";
char * user = "mysqluser";
char * pass = "mysqlpass";
char * db = "databasenamehere";
char * query = NULL;
mysql_init(&mysql);
conn = mysql_real_connect(&mysql,server,user,pass,db,0,NULL,0);
if (conn == NULL){
fprintf(stderr,"%s\n",mysql_error(conn));
mysql_close(&mysql);
mysql_library_end();
return false;
}
query = malloc(255);
if (strlen(ip) > 30)
{
fprintf(stderr,"INVALID IP SIZE!");
mysql_close(&mysql);
mysql_close(conn);
mysql_library_end();
return false;
}
if (serie)
sprintf(query,"SELECT client_ip,client_port FROM routing WHERE serie_cartela=\"%s\"",ip);
else
sprintf(query,"SELECT client_ip,client_port FROM routing WHERE cartela_ip=\"%s\"",ip);
if (mysql_query(conn,query)){
free(query);
fprintf(stderr,"%s\n",mysql_error(conn));
mysql_close(&mysql);
mysql_close(conn);
mysql_library_end();
return false;
}
free(query);
res = mysql_use_result(conn);
if (res != NULL)
{
row = mysql_fetch_row(res);
if ((row!=NULL) && (row[0] != NULL) && (row[1] != NULL))
{
strcpy(ip,row[0]);
*port = atoi(row[1]);
mysql_free_result(res);
mysql_close(&mysql);
mysql_close(conn);
mysql_library_end();
return true;
}
mysql_free_result(res);
mysql_close(&mysql);
mysql_close(conn);
mysql_library_end();
}
return false;
}
Upvotes: 1
Views: 127
Reputation: 6070
if (res != NULL)
{
row = mysql_fetch_row(res);
if ((row!=NULL) && (row[0] != NULL) && (row[1] != NULL))
{
strcpy(ip,row[0]);
*port = atoi(row[1]);
mysql_free_result(res);
mysql_close(&mysql);
mysql_close(conn);
mysql_library_end();
return true;
}
mysql_free_result(res);
mysql_close(&mysql);
mysql_close(conn);
mysql_library_end();
}
if res is NULL you do not cleanup!
Upvotes: 1