c - strncmp proper usage -


here's quick background: i've got client , server program communicating each other on unix socket. when parsing received messages on server side, attempting use strncmp figure out action take.

the problem i'm having figuring out use length argument of strncmp. reason being problematic of messages share common prefix. example, have message "getprimary", causes server respond primary server address, , message "getprimarystatus", causes server respond status of primary server. initial thought following:

if(strncmp(message,"getprimary",strlen("getprimary"))==0){     return foo; } else if(strncmp(message,"getprimarystatus",strlen("getprimarystatus"))==0){     return bar; } 

the problem when send server "getprimarystatus", code return foo because strncmp not checking far enough in string. pass in strlen(message) length argument strncmp, seems defeat purpose of using strncmp, prevent overflow in case of unexpected input. have static variable maximum message length can read, seems passing in length making sure if message overflows, effects minimized.

i've come few solutions, aren't pretty, wondering if there common way of dealing problem.

for reference, current solutions are: order if / else if statements in such way that messages common prefixes checked in order of descending length (which seems way throw landmine in code trying add later on).

group messages common prefixes , suffix first:

if(strncmp(message,"getprimary",strlen("getprimary"))==0){     if(strncmp(message,"getprimarystatus",strlen("getprimarystatus"))==0){         return bar;     else         return foo;     } } 

but feels messy, since have 20 different possible messages i'm handling.

create array of possible messages have, add function init sequence order array descending length, , have code search through elements of list until finds match. seems complicated , silly.

it seems should common enough issue there ought solution somewhere, haven't been able find far.

thanks in advance help!

presuming string in message supposed null-terminated, reason use strncmp() here rather strcmp() to prevent looking beyond end of message, in case message not null-terminated.

as such, n pass strncmp() should received size of message, ought know (from return value of read() / recv() function read message).


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -