Tom Leese
Tom Leese

Reputation: 19729

Parse IRC PRIVMSG in C

I am quite new to C (I am more used to C++) and I am trying to create an IRC Bot. I am currently struggling to find the correct string parsing functions to parse this line:

:nick!~username@server PRIVMSG #channel :message (could contain the word PRIVMSG)

So, I am asking if anyone could show me what functions I would use to split up this line into:

Thanks for any help!

Upvotes: 0

Views: 2443

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490653

I'd probably use sscanf. Something on this general order seems to be a reasonable starting point:

char nick[32], user[32], server[32], channel[32], body[256];

sscanf(buffer, ":%31[^!]!~%31[^@]@%31s PRIVMSG #%31s :%255[^\n]", 
                 nick,     user, server,       channel, body);

Upvotes: 2

Juliano
Juliano

Reputation: 41467

Considering that all this is in a char[] buffer that you can write onto (i.e., the contents will be overwritten), you can do something like:

char *nick, *username, *server, *command, *channel, *message;

nick     = strtok(buffer+1, "!");
username = strtok(NULL, "@");
server   = strtok(NULL, " ");
command  = strtok(NULL, " ");
channel  = strtok(NULL, " ");
message  = strtok(NULL, "");

You need to add some error checking to the above code, since any call to strtok() may return NULL if no more tokens are found. You could also use some more elaborate parsing, or sscanf().

Read the pages about strtok(3) and sscanf(3).

Upvotes: 1

Related Questions