All pastes #839687 Raw Edit

Someone

public text v1 · immutable
#839687 ·published 2007-12-31 04:22 UTC
rendered paste body
//main.h

#define IRCPORT 6667
#define MSGLEN 513 //max irc message + \r\n + \0 
#define IP "64.251.15.82"
#define ENDLINE "\r\n"


//main.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>

#include "main.h"

int main(void){
    int sockfd, ret, loop;
    char sizer[MSGLEN], tmpbuf[MSGLEN * 2], cycbuf[MSGLEN * 2], msg[MSGLEN], *ptmpbuf;
    void *getmem(size_t size);
    char *getmessage(char **buf, char *msg);
    int handlemsg(char *buf, time_t now, time_t start, int loop);
    time_t now, start;

    struct sockaddr_in my_addr;

    sockfd = socket(PF_INET, SOCK_STREAM, 0);

    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(IRCPORT);
    my_addr.sin_addr.s_addr = inet_addr(IP);
    memset(my_addr.sin_zero, '\0', sizeof((my_addr.sin_zero)));

    connect(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr));

    time(&start);
    loop = 0;
    while(1){
        time(&now);
        ret = recv(sockfd, tmpbuf, 512, 0);
        if((loop++ > 0) && (strlen(cycbuf) > 0)){
            //concatonate tmpbuf to the end of cycbuf:
            strcat(cycbuf, tmpbuf);
            //moving content back to tmpbuf:
            strcpy(tmpbuf, cycbuf);
        } 
        ptmpbuf = tmpbuf; //need/want a pointer for fancy positioning
        if(ret < 1){
            printf("Disconnected.\n");
            break;
        }
        while((getmessage(&ptmpbuf, msg)) != NULL){
            if(handlemsg(msg, now, start, loop)){
                printf("Quit.\n");
                break;
            }
        }
        memset(cycbuf, '\0', (MSGLEN * 2)); 
        strncpy(cycbuf, ptmpbuf, sizeof(sizer)); //copying (at most 512 characters) what's left over: in the middle of a message maybe, that is still waiting for a \r\n
        memset(tmpbuf, '\0', (MSGLEN * 2)); 
    }
    printf("Exit.\n");
    return 0;
}

void *getmem(size_t size){

    void *p;

    if((p = malloc(size)) == NULL){
        perror("Not enough memory for call to getmem");
        exit(EXIT_FAILURE);
    }
    return p;
}

//bot.c

#include <stdio.h>
#include <string.h>
#include <time.h>

#include "main.h"

int handlemsg(char *buf, time_t now, time_t start, int loop){
    printf("BEGIN BUF: (%d.)\n buf: %s\n END BUFF (%d.) \n\n", loop, buf, loop);
    return 0;
}

//copies characters from *buf into *msg until \r\n found.
char *getmessage(char **buf, char *msg){

    size_t substrlen;
    char *pos = NULL;

    pos = strstr(*buf, ENDLINE);

    if(pos != NULL){
        substrlen = strcspn(*buf, ENDLINE);
        memset(msg, '\0', MSGLEN); 
        strncpy(msg, *buf, substrlen);
        pos += 2;
        *buf = pos;
    }
    return pos;

}