rendered paste body#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
#include <netdb.h>
#include <string.h>
void error(char *msg)
{
perror(msg);
exit(0);
}
int parseLine(int sockfd, char *buffer)
{
char *tmp;
printf("<- %s\n",buffer);
if(!strncmp(buffer, "PING", 4)) {
tmp = (char *)malloc(strlen(buffer) + 2);
memset(tmp,0,sizeof(tmp));
sprintf(tmp, "PONG %s\n", buffer + 5);
printf("-> %s", tmp);
write(sockfd, tmp, strlen(tmp) + 1);
free(tmp);
}
return 0;
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
struct timeval tv;
char buffer[1024];
char buf[1024];
int yes = 1;
int i = 1;
int x = 0;
int z = 0;
fd_set readfds;
fd_set writefds;
tv.tv_sec=30;
tv.tv_usec=0;
FD_ZERO(&readfds);
FD_ZERO(&writefds);
portno = 6667;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error("ERROR opening socket");
}
server = gethostbyname("irc.source.int");
if(server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
memset((char *) &serv_addr,0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
memcpy((char *)&serv_addr.sin_addr.s_addr,(char *)server->h_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if(setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(int)) == -1) {
perror("setsockopt");
}
// if(fcntl(sockfd, F_SETFL, O_NONBLOCK) == -1) {
// perror("fcntl");
// close(sockfd);
// exit(1);
// return -1;
// }
if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
error("ERROR connecting");
}
FD_SET(sockfd, &readfds);
memset(buf, 0, 1024);
while(1) {
memset(buffer, 0, 1024);
printf("READ\n");
// select(0, &readfds, &writefds, NULL, &tv);
n = read(sockfd,buffer,1023);
printf("AFTER READ\n");
if(n < 0) {
error("ERROR reading from socket");
exit(0);
} else if(n > 0) {
for(x = 0; x < strlen(buffer); x++) {
if(buffer[x] == '\n') {
buf[z] = 0;
if(parseLine(sockfd, buf)) {
printf("ERROR: parseLine(): Failed\n");
}
memset(buf, 0, 1024);
z = 0;
printf("Here\n");
} else {
//printf("%c\n", buffer[x]);
buf[z++] = buffer[x];
}
}
printf("ForEnd\n");
}
if(i == 1) {
printf("-> USER bot bot bot :bot bot bot\n");
write(sockfd, "USER bot bot bot :bot bot bot\n", 30);
printf("-> NICK srcbot\n");
write(sockfd, "NICK srcbot\n", 13);
i = 0;
}
printf("While:Loop\n");
}
return 0;
}