03-30-2010, 08:57 PM
Code:
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#pragma comment(lib, "ws2_32.lib");
using namespace std;
typedef struct
{
string Nick;
string Host;
string Message;
} IRC_Privmsg;
string ranstring(int len)
{
string ListNew;
for(int i = 0; i < len; i++)
{
int select = rand() % 2;
char Value = (select ? (char)(rand() % 26 + 65):(char)(rand() % 10 + 48));
ListNew.append(1, Value);
}
return ListNew;
}
int IRC_Send(SOCKET s, string buf)
{
send(s, buf.c_str(), strlen(buf.c_str()), 0);
}
IRC_Privmsg privmsg_parse(string message)
{
int pos = 1;
IRC_Privmsg IRC_Parsed;
for(int x = pos; x < message.length(); x++)
{
if(message[x]!='!')
{
IRC_Parsed.Nick.append(1, message[x]);
}
else
{
pos = x + 1;
break;
}
}
for(int x = pos; x < message.length(); x++)
{
if(message[x]!=' ')
{
IRC_Parsed.Host.append(1, message[x]);
}
else
{
pos = x;
break;
}
}
for(int x = pos ;x < message.length(); x++)
{
if(message[x]==':')
{
pos = x + 1;
break;
}
}
for(int x = pos; x < message.length(); x++)
{
IRC_Parsed.Message.append(1, message[x]);
}
return IRC_Parsed;
}
void IRC_Connect(string host, int port, string nick)
{
SOCKET mySocket;
WSAData wsaData;
struct hostent *hoste;
struct sockaddr_in in;
int s;
WSAStartup(MAKEWORD(2,2), &wsaData);
s = socket(AF_INET, SOCK_STREAM, 0);
hoste = gethostbyname(host.c_str());
if (hoste == NULL)
{
IRC_Connect(host, port, nick);
}
in.sin_family = AF_INET;
in.sin_port = htons((unsigned short)port);
in.sin_addr.s_addr = *(unsigned long *) hoste->h_addr;
if (connect(s, (struct sockaddr *) &in, sizeof(struct sockaddr_in)) == SOCKET_ERROR)
{
IRC_Connect(host, port, nick);
}
char recvBuf[4096];
int byteRecv;
int byteSent;
cout << "Connected....\nSending headers...\n\n";
IRC_Send(s, "USER "+nick+" 8 * :X\r\n");
IRC_Send(s, "NICK "+nick+"\r\n");
IRC_Send(s, "JOIN #botland\r\n");
IRC_Privmsg PrivmsgHandler;
while(byteRecv != SOCKET_ERROR)
{
memset(recvBuf, '\0', sizeof(recvBuf));
byteRecv = recv(s, recvBuf, 4096, 0);
if(byteRecv == 0 || byteRecv == WSAECONNRESET)
{
cout << "Conection Reset by host!\n";
IRC_Connect(host, port, nick);
}
if(string(recvBuf).find("PING") != string::npos)
{
cout << "ping";
IRC_Send(s, "PONG "+string(recvBuf).substr(20,9) + "\r\n");
}
if(string(recvBuf).find("PRIVMSG") != string::npos)
{
PrivmsgHandler = privmsg_parse(recvBuf);
cout << PrivmsgHandler.Nick << endl;
cout << PrivmsgHandler.Host << endl;
cout << PrivmsgHandler.Message << endl;
}
cout << recvBuf <<endl;
}
}
int main()
{
string host = "irc.Malvager.com";
int port = 6667;
string ran = ranstring(7);
string nick = "Bot|"+ran;
IRC_Connect(host, port, nick);
}
Basic IRC type bot, uses a struct to handle/parse PRIVMSG's
includes a simple random string generation function for the nick
Auto reconnects, etc.