Skip to content

Instantly share code, notes, and snippets.

@feelfreelinux feelfreelinux/pc.cpp
Created Feb 10, 2017

Embed
What would you like to do?
Crappy IRC bouncer
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
using namespace std;
int ircSock, bncSock;
int sendCMD( string command, int socket ){
return( send( socket, (void*)command.c_str(), command.length(), 0 ) );
}
// Tests, is data available on socket
int isData( int socket ){
int count;
int res = ioctl( socket, FIONREAD, &count );
return count;
}
int main()
{
cout << "Hello world!" << endl;
int clientSock = 0;
bool clientConnected = false;
printf( "Starting IRC client...\n" );
struct sockaddr_in ircAddr, bncAddr, clientAddr;
char buffer[500];
// TODO Replace this IP with gethostbyname() DNS
ircSock = socket( AF_INET, SOCK_STREAM, 0 );
bncSock = socket( AF_INET, SOCK_STREAM, 0 );
ircAddr.sin_addr.s_addr = inet_addr("149.56.134.238");
ircAddr.sin_family = AF_INET;
ircAddr.sin_port = htons( 6667 );
bncAddr.sin_addr.s_addr = INADDR_ANY;
bncAddr.sin_family = AF_INET;
bncAddr.sin_port = htons( 1337 );
bzero( &(bncAddr.sin_zero), 8 ); // empty it
int clientSCK = 0;
bind( bncSock, (sockaddr *)&bncAddr, sizeof(struct sockaddr) );
listen( bncSock, 1 );
// We don't want to block server socket
fcntl( bncSock, F_SETFL, O_NONBLOCK );
connect( ircSock, (sockaddr*)&ircAddr, sizeof( ircAddr ) );
// empty buffer, and send needed auth messages
bzero( buffer, 500 );
sendCMD( "USER esp32 8 * ESP32 test\n", ircSock );
sendCMD( "NICK esp32\n", ircSock );
while(1){
// Client socket have data.
if(isData(ircSock)){
bzero( buffer, 500 );
recv( ircSock, buffer, sizeof(buffer), 0 );
string line = buffer;
// handle PING command
if(line.substr(0, 4)=="PING"){
line[1] ='O';
sendCMD( line, ircSock );
}
if( clientConnected ){
sendCMD( line, clientSCK );
//printf("Sending message to client, ID %i \n", clientSCK);
}
cout << line;
// TODO Add logging, basic bouncer functionality
}
socklen_t socklen = sizeof(struct sockaddr_in);
if( (clientSock = accept( bncSock, (sockaddr *)&clientAddr, &socklen ) ) > 0){
clientConnected = true;
clientSCK = clientSock;
cout<< "Client connected :) "+clientSCK<<endl;
sendCMD( "HI! \n", clientSCK );
}
if(clientConnected){
if(isData(clientSCK)){
bzero( buffer, 500 );
recv( clientSCK, buffer, sizeof(buffer), 0 );
string line = buffer;
sendCMD( line, ircSock );
//printf("Got message from client, sending it to freenode. Whoo!\n");
}
//if(clientSock<1){
// clientConnected = false;
//}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.