All pastes #461977 Raw Edit

Someone

public text v1 · immutable
#461977 ·published 2007-04-27 23:26 UTC
rendered paste body
#include <iostream>
#include <errno.h>
#include <cstring>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

using namespace std;

char *substr (const char *str, int start, int end) {
char *sub = new char[strlen(str)];
start -=1 ;

for(int i = 0;start<end;i += 1) {
        sub[i] = str[start];
        start += 1;
}
sub[end] = '\0';

return sub;
}

int main() {

struct hostent *he;
struct sockaddr_in their_addr; 
int sockfd;
char msg[512];
char buffer[512];
int length;
int stay = 1;

// Connect the socket to the server, if you read Beej's Guide a 
// lot of this will look fimiliar.

if ((he=gethostbyname("irc.easynews.com")) == NULL) {  
	perror("gethostbyname");
	exit(1);
}

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
	perror("socket");
	exit(1);
}

their_addr.sin_family = AF_INET;    
their_addr.sin_port = htons(6667);  
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
memset(&(their_addr.sin_zero), '\0', 8); 

if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {
	perror("connect");
	exit(1);
}

strcpy(msg,"USER jay jay jay :jay jay\r\nNICK jaybot\r\n");

if (send(sockfd, msg, strlen(msg), 0) == -1) {
	perror("send");
}

while (stay) {
// get info from the server, put it in buffer
if ((length=recv(sockfd, buffer, 511, 0)) == -1) {
	perror("recv");
	exit(1);
}
buffer[length] = '\0';


for (int i = 0; buffer[i] != '\0'; i += 1) {

if (strncmp(substr(buffer,i,i+4),"PING",4) == 0) {
	// reply to ping with pong, also joining #xboxrocks
	sprintf(msg, "PONG %s\r\njoin :#xboxrocks\r\n",substr(buffer,i+6,i+13));
	
	if (send(sockfd, msg, strlen(msg), 0) == -1) {
		perror("send");
	}	
}
if (strncmp(substr(buffer,i,i+5),"die",5) == 0) {
	strcpy(msg, "PRIVMSG #xboxrocks :die!\r\nQUIT\r\n");
	
	if (send(sockfd, msg, strlen(msg), 0) == -1) {
		perror("send");
	}	
	
	stay = 0; // leave our while()
}

}

}

close(sockfd);

return 0;
}