Sockets and multi string comparison

This is a discussion on Sockets and multi string comparison within the C Programming forums, part of the General Programming Boards category; Hello, I have a socket server program which takes things like CMD:hci_scan as input into a char * and i ...

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    61

    Sockets and multi string comparison

    Hello,

    I have a socket server program which takes things like CMD:hci_scan as input into a char *
    and i would like to know how i could differentiate between all the different commands and i do know that you cant simply use a switch because a switch can only compare numerical data (and character constants, which, in terms of C are pretty much numbers)

    so, my question is how do i efficiently make a server than can take a bunch of commands without using strcmp heaps

    thanks for your help!

  2. #2
    Registered User
    Join Date
    Jan 2009
    Posts
    61
    hmm i have found while searching that i could create a function map where the string is the key and a pointer to the function is the value

    could you give me a few tips on how would start to go about this?

    thanks

  3. #3
    Registered User
    Join Date
    Mar 2009
    Posts
    31
    if you are thinking of the C++ STL type "std::map" you are in the wrong forumsection, otherwise: read on.

    tip #1
    compare parts of strings (char *):
    Code:
    #include <string.h>
    
    char *foobar = "hello world!";
    
    if (strncmp("hello", foobar, 4) == 0) { ... }
    tip #2
    function callbacks:
    Code:
    void (my_exit_callback)(int);
    my_func_callback = &exit; /* assign callback-pointer with the address of exit-function */
    
    my_func_callback(0); /* exit with code 0 */
    tip #3
    put all information in a struct, then put all your pairs into an array which you can easily loop through to find the correct callback function.
    Code:
    struct foobar {
      char *cmd_key;
      void (*cmd_handler)(char *);
    }
    
    struct foobar callbacks[] = {
      {"PRINT", &print_handler},
      {"EXIT", &exit_handler}
    };

  4. #4
    Registered User
    Join Date
    Jan 2009
    Posts
    61
    wow thanks for your help... as it turns out just tip #1 was cool enough i ended up not having that many commands... for now

    anyway, i love this forum it is sooooo good as a C resource!!!!

    thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sockets, multi home, multicast, security, complicated issue
    By ekymk in forum Networking/Device Communication
    Replies: 6
    Last Post: 08-13-2004, 02:12 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21