K
K.M Jr
Hi group,
I usually don't code in C. I happened to write a piece of code that
parses an input string of the form "host_name:XXXX" into host_name and
XXXX. I would request the group to give me any tips, mistakes I have
done, good coding practices etc.
Thanks
PS - I know that goto is not the recommended way of doing things, so
forgive that part for now.
/*
* Function to parse host name and port address.
* appplication_addr - pointer to string to parse, format of string
is "hostname:XXXX"
* ip_buffer - pointer to buffer to hold the host name after parsing
* ip_buffer_len - length of ip_buffer
* port - pointer to integer to hold the port number after parsing
*/
int parse_application_address (const char *application_addr, char
*ip_buffer, int ip_buffer_len, int *port)
{
int ip_len;
int retval = RET_ERR;
const char *delim_pos = strchr(application_addr, ':');
if (delim_pos != NULL)
{
ip_len = delim_pos - application_addr;
if (ip_buffer_len < ip_len + 1)
{
log("Insuffcient buffer space\n", ip_buffer_len);
goto end;
}
strncpy(ip_buffer, application_addr, ip_len);
ip_buffer[ip_len] = 0;
/* TODO - Validate IP */
*port = atoi(delim_pos + 1);
/* TODO - Validate port range */
retval = RET_OK;
}
else
{
log("Invalid application address - %s\n", application_addr);
}
end:
return retval;
}
/* RET_OK and RET_ERR are #defines for 0 and -1 respectively */
I usually don't code in C. I happened to write a piece of code that
parses an input string of the form "host_name:XXXX" into host_name and
XXXX. I would request the group to give me any tips, mistakes I have
done, good coding practices etc.
Thanks
PS - I know that goto is not the recommended way of doing things, so
forgive that part for now.
/*
* Function to parse host name and port address.
* appplication_addr - pointer to string to parse, format of string
is "hostname:XXXX"
* ip_buffer - pointer to buffer to hold the host name after parsing
* ip_buffer_len - length of ip_buffer
* port - pointer to integer to hold the port number after parsing
*/
int parse_application_address (const char *application_addr, char
*ip_buffer, int ip_buffer_len, int *port)
{
int ip_len;
int retval = RET_ERR;
const char *delim_pos = strchr(application_addr, ':');
if (delim_pos != NULL)
{
ip_len = delim_pos - application_addr;
if (ip_buffer_len < ip_len + 1)
{
log("Insuffcient buffer space\n", ip_buffer_len);
goto end;
}
strncpy(ip_buffer, application_addr, ip_len);
ip_buffer[ip_len] = 0;
/* TODO - Validate IP */
*port = atoi(delim_pos + 1);
/* TODO - Validate port range */
retval = RET_OK;
}
else
{
log("Invalid application address - %s\n", application_addr);
}
end:
return retval;
}
/* RET_OK and RET_ERR are #defines for 0 and -1 respectively */