C winsock program crashing whenever I free structure
I know this is kinda lame question, but what am I doing wrong in my code ? Basically, I wanna create communication on local IP using UDP, also send some files etc. The problem is, that when I get to freeing my structures after using them/converting them to/from char* the program just crashes. What is even more weird, the program does not crash when debugging and stepping through using CLion debugger. What am I doing wrong? Here is my source code:
The error seems to happen, when I can not allocate more memory (so logically, I need to free some) when sending a file over network. Sending messages works just fine
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
// PKS2Visual.cpp : Defines the entry point for the console application.
//
#include "main.h"
#include <stdio.h>
#include <string.h>
#include <winsock2.h>
#include <windows.h>
#include <time.h>
#define BREAKSOMETHING 0
#pragma comment(lib, "ws2_32.lib")
int fragSize = 1500;
int isInside = 0;
SOCKET s1, s2;
struct sockaddr_in server, myClient, otherClient;
int main() {
char mode;
printf("Enter fragment size:n");
scanf("%d", &fragSize);
p2pMode();
}
DWORD WINAPI receiveThreadFunc(LPVOID lpParam) {
int slen = sizeof(otherClient);
int doRun = 1;
int sizee;
char msgBuffer[1519];
char fileName[1519];
int receivingFile = 0;
while (doRun) {
printf("Waiting for data...nn");
if ((recvfrom(s1, msgBuffer, 1519, 0, (struct sockaddr *) &otherClient,
&slen)) == SOCKET_ERROR) {
printf("recvfrom() failed with error code : %dn", WSAGetLastError());
continue;
}
//printf("Received packet from %s:%dn", inet_ntoa(otherClient.sin_addr), ntohs(otherClient.sin_port));
PacketData *packetData = dataToPacket(msgBuffer);
if (packetData == NULL) {
continue;
}
char flag = packetData->flag;
switch (flag) {
case 's': {
PacketData *packetDataAck = createPacket('a');
char *messageToSend2 = packetToData(packetDataAck, &sizee);
if (sendto(s1, messageToSend2, 18, 0, (struct sockaddr *) &otherClient, slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
//free(packetDataAck);
//free(messageToSend2);
break;
}
case 'm': {
if (receivingFile) {
FILE *fptr;
fptr = fopen(fileName, "a");
fprintf(fptr, "%s", packetData->data);
printf("Packet contains data: %sn", packetData->data);
fclose(fptr);
if(packetData->fragNum == packetData->fragTotal){
receivingFile = 0;
}
} else {
printf("Received packet n. %dn", packetData->fragNum);
printf("Packet data length: %dn", packetData->len);
printf("Packet contains data: %sn", packetData->data);
}
break;
}
case 'f': {
strcpy(fileName, packetData->data);
printf("Receiving file: %sn", fileName);
printf("Receiving file: %sn", packetData->data);
receivingFile = 1;
break;
}
default: {
doRun = 0;
break;
}
}
free(packetData);
}
return 0;
}
DWORD WINAPI sendThreadFunc(LPVOID lpParam) {
PacketData **fragments = NULL;
int doRun = 1;
char msgBuffer[1500];
int actualSize = 0;
int slen = sizeof(myClient);
while (1) {
printf("Enter message or -e to end messaging and return to menu:n");
fflush(stdin);
scanf("%1500[^n]", msgBuffer);
getc(stdin);
if (strcmp(msgBuffer, "-e") == 0) {
isInside = 0;
return 0;
}
if (strlen(msgBuffer) >= 1499) {
continue;
}
fragments = makeFragments(msgBuffer);
int numFragments = fragments[0]->fragTotal;
printf("Number of fragments: %dn", numFragments);
PacketData *packetData = createPacket('s');
if (packetData == NULL) {
printf("Could not init packet 's'n");
continue;
}
char *sync = packetToData(packetData, &actualSize);
if (sendto(s2, sync, 18, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("First fragment sent.n");
free(packetData);
char *ack = (char *) calloc(18, sizeof(char));
if (recvfrom(s2, ack, 18, 0, (struct sockaddr *) &myClient, &slen) ==
SOCKET_ERROR) {
printf("recvfrom() failed with error code : %dn", WSAGetLastError());
continue;
}
free(ack);
printf("Server confirmed first packet.n");
for (int i = 0; i < fragments[0]->fragTotal; i++) {
char *msgBuffer2 = packetToData(fragments[i], &actualSize);
if (sendto(s2, msgBuffer2, actualSize + 1, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
}
free(fragments);
}
return 0;
}
DWORD WINAPI sendFileFunc(LPVOID lpParam) {
char msgBuffer[1500];
int actualSize = 0;
int slen = sizeof(myClient);
while (1) {
printf("Enter file name or -e to return to menu:n");
fflush(stdin);
scanf("%1500[^n]", msgBuffer);
getc(stdin);
if (strcmp(msgBuffer, "-e") == 0) {
isInside = 0;
return 0;
}
if (strlen(msgBuffer) >= 1499) {
continue;
}
//Get file length:
FILE *fl = fopen(msgBuffer, "r");
if (fl == NULL) {
printf("Invalid name, try againn");
continue;
}
fseek(fl, 0, SEEK_END);
long fileLength = ftell(fl);
fclose(fl);
int numFragments = (fileLength - 1) / fragSize + 2;
printf("Number of fragments: %dn", numFragments);
PacketData *packetData = createPacket('s');
if (packetData == NULL) {
printf("Could not init packet 's'n");
continue;
}
char *sync = packetToData(packetData, &actualSize);
if (sendto(s2, sync, 18, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("First fragment sent.n");
free(packetData);
char *ack = (char *) calloc(18, sizeof(char));
if (recvfrom(s2, ack, 18, 0, (struct sockaddr *) &myClient, &slen) ==
SOCKET_ERROR) {
printf("recvfrom() failed with error code : %dn", WSAGetLastError());
continue;
}
//free(ack);
PacketData *fragments = NULL;
fragments = (PacketData *) malloc(sizeof(PacketData));
fragments->data = (char *) malloc(fragSize * sizeof(char));
strncpy(fragments->data, msgBuffer, strlen(msgBuffer));
fragments->data[strlen(msgBuffer)] = '';
fragments->flag = 'f';
fragments->len = strlen(msgBuffer);
fragments->fragNum = (unsigned int) (1);
fragments->fragTotal = (unsigned int) numFragments - 1;
fragments->CRC = (unsigned int) calculate_crc(msgBuffer, strlen(msgBuffer));
//Sending the first fragment with 'f' flag
char *toSend = packetToData(fragments, &actualSize);
if (sendto(s2, toSend, actualSize + 1, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("Server confirmed first packet.n");
size_t n = 0;
int counter = 0;
int fragNum = 2;
int c;
FILE *f2 = fopen(msgBuffer, "r");
if(f2 == NULL){
printf("File was nulln");
continue;
}
while ((c = fgetc(f2)) != EOF) {
msgBuffer[n++] = (char) c;
counter++;
if (counter == fragSize) {
n = 0;
counter = 0;
printf("Allocating fragment number: %dn", fragNum);
PacketData *fragments2 = NULL;
fragments2 = (PacketData *) malloc(sizeof(PacketData));
if(fragments2 == NULL){
printf("Incorrect mallocn");
break;
}
fragments2->data = (char *) malloc((fragSize+1) * sizeof(char));
if(fragments2->data == NULL){
printf("Incorrect malloc2n");
break;
}
strncpy(fragments2->data, msgBuffer, fragSize);
printf("Copying data to fragment number: %dn", fragNum);
fragments2->data[strlen(msgBuffer)] = '';
fragments2->flag = 'm';
fragments2->len = (unsigned int) fragSize;
fragments2->fragNum = (unsigned int) (fragNum);
fragments2->fragTotal = (unsigned int) numFragments - 1;
fragments2->CRC = (unsigned int) calculate_crc(msgBuffer, fragSize);
printf("Allocated fragment number: %dn", fragNum);
fragNum++;
char *toSend = packetToData(fragments2, &actualSize);
if (sendto(s2, toSend, actualSize + 1, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("Sent fragment number: %dn", fragNum);
}
}
fclose(fl);
}
return 0;
}
void p2pMode() {
int serverPort, clientPort;
char *serverAddr = (char *) malloc(20 * sizeof(char));
WSADATA wsa;
printf("nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("Failed. Error Code : %d", WSAGetLastError());
getchar();
exit(EXIT_FAILURE);
}
printf("Initialised.n");
char hostname[128] = "";
char menuBuffer;
gethostname(hostname, sizeof(hostname));
struct hostent *ent = gethostbyname(hostname);
struct in_addr ip_addr = *(struct in_addr *) (ent->h_addr);
printf("Your IP Address: %sn", inet_ntoa(ip_addr));
printf("Enter other PC IP Address:n");
scanf("%s", serverAddr);
if (!strcmp(serverAddr, "localhost"))
serverAddr = (char *) "127.0.0.1";
printf("Enter your listening port:n");
scanf("%d", &clientPort);
printf("Enter other PC's port:n");
scanf("%d", &serverPort);
if ((s1 = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
if ((s2 = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.n");
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(inet_ntoa(ip_addr));
server.sin_port = htons(clientPort);
myClient.sin_family = AF_INET;
myClient.sin_port = htons(serverPort);
myClient.sin_addr.S_un.S_addr = inet_addr(serverAddr);
if (bind(s1, (struct sockaddr *) &server, sizeof(server)) == SOCKET_ERROR) {
printf("Bind failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
free(serverAddr);
DWORD dwThreadId, dwThreadId2, dwThreadId3, dwThrdParam = 1;
CreateThread(
NULL, // default security attributes
10000, // use default stack size
receiveThreadFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId); // returns the thread identifier
while (1) {
if (!isInside) {
printf("For messages, write 'm', for file 'f'n");
scanf("%c", &menuBuffer);
switch (menuBuffer) {
case 'm':
CreateThread(
NULL, // default security attributes
10000, // use default stack size
sendThreadFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId2); // returns the thread identifier
isInside = 1;
break;
case 'f':
CreateThread(
NULL, // default security attributes
10000, // use default stack size
sendFileFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId3); // returns the thread identifier
isInside = 1;
break;
}
}
}
}
char *packetToData(PacketData *packet, int *size) { // convert packet into sendable data
int sizee = packet->len + 18;
*size = sizee;
char *temp = (char *) calloc(sizee, sizeof(char));
char *out;
if (temp == NULL) {
return NULL;
}
out = temp;
*(temp) = packet->flag;
*(unsigned int *) (temp + 2) = packet->CRC;
*(unsigned int *) (temp + 6) = packet->fragNum;
*(unsigned int *) (temp + 10) = packet->fragTotal;
*(unsigned int *) (temp + 14) = packet->len;
temp = (temp + 18);
int i;
for (i = 0; i < packet->len; i++) { // copy data
temp[i] = packet->data[i];
}
temp[i] = '';
return out;
}
PacketData *dataToPacket(char *data) { // convert received data into packet
printf("Data received: %sn", data);
PacketData *packet = (PacketData *) malloc(sizeof(PacketData));
if (packet == NULL)
return NULL;
packet->flag = *(data);
packet->CRC = *(unsigned int *) (data + 2);
packet->fragNum = *(unsigned int *) (data + 6);
packet->fragTotal = *(unsigned int *) (data + 10);
packet->len = *(unsigned int *) (data + 14);
packet->data = (char *) malloc(packet->len);
char *packetdata = (data + 18);
int i;
for (i = 0; i < packet->len; i++) { // copy data
packet->data[i] = packetdata[i];
}
packet->data[i] = '';
return packet;
}
PacketData *createPacket(char flag) {
PacketData *packetData = (PacketData *) malloc(sizeof(PacketData));
packetData->flag = flag;
packetData->len = 0;
packetData->CRC = 0;
packetData->fragNum = 1;
packetData->fragTotal = 1;
return packetData;
}
int calculate_crc(char *buf, int size) {
int crcHash = 10;
for (int i = 0; i < size; i++) {
crcHash += buf[i];
crcHash *= 31;
crcHash %= 30000;
}
return crcHash;
}
struct packetData **makeFragments(char *message) {
int i;
printf("Message length: %dn", strlen(message));
int fragCount = (strlen(message) - 1) / fragSize + 1;
if (fragCount == 0) {
fragCount++;
}
PacketData **fragments = (PacketData **) malloc((fragCount) * sizeof(PacketData *));
printf("Allocated %d fragmentsn", fragCount);
for (i = 0; i < fragCount; i++) {
fragments[i] = (PacketData *) malloc(sizeof(PacketData));
fragments[i]->data = (char *) malloc(fragSize * sizeof(char));
int toCopy = 0;
if (strlen(message) > fragSize) {
toCopy = fragSize;
} else {
toCopy = strlen(message);
}
strncpy(fragments[i]->data, message, toCopy);
fragments[i]->data[toCopy] = '';
fragments[i]->flag = 'm';
fragments[i]->len = (unsigned int) toCopy;
fragments[i]->fragNum = (unsigned int) (i + 1);
fragments[i]->fragTotal = (unsigned int) fragCount;
fragments[i]->CRC = (unsigned int) calculate_crc(message, toCopy);
message += fragSize;
}
printf("Fragments needed: %dn", fragments[0]->fragTotal);
return fragments;
}
and here is my header if someone needed to run it:
//
// Created by lukas on 11/19/2018.
//
#include <winsock2.h>
#include <windows.h>
#ifndef PKS2C_MAIN_H
#define PKS2C_MAIN_H
#endif //PKS2C_MAIN_H
typedef struct packetData {
char flag;
unsigned int CRC;
unsigned int fragNum;
unsigned int fragTotal;
unsigned int len;
char *data;
} PacketData;
struct packetData **makeFragments(char *message);
struct packetData **makeFileFragments(char *message);
char *packetToData(PacketData *packet, int *size);
PacketData *dataToPacket(char *data);
PacketData *createPacket(char flag);
void p2pMode();
int calculate_crc(char *buf, int size);
DWORD WINAPI receiveThread(LPVOID lpParam);
DWORD WINAPI sendThread(LPVOID lpParam);
SOCKET s1, s2;
struct sockaddr_in server, myClient, otherClient;
c windows multithreading free winsock2
|
show 3 more comments
I know this is kinda lame question, but what am I doing wrong in my code ? Basically, I wanna create communication on local IP using UDP, also send some files etc. The problem is, that when I get to freeing my structures after using them/converting them to/from char* the program just crashes. What is even more weird, the program does not crash when debugging and stepping through using CLion debugger. What am I doing wrong? Here is my source code:
The error seems to happen, when I can not allocate more memory (so logically, I need to free some) when sending a file over network. Sending messages works just fine
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
// PKS2Visual.cpp : Defines the entry point for the console application.
//
#include "main.h"
#include <stdio.h>
#include <string.h>
#include <winsock2.h>
#include <windows.h>
#include <time.h>
#define BREAKSOMETHING 0
#pragma comment(lib, "ws2_32.lib")
int fragSize = 1500;
int isInside = 0;
SOCKET s1, s2;
struct sockaddr_in server, myClient, otherClient;
int main() {
char mode;
printf("Enter fragment size:n");
scanf("%d", &fragSize);
p2pMode();
}
DWORD WINAPI receiveThreadFunc(LPVOID lpParam) {
int slen = sizeof(otherClient);
int doRun = 1;
int sizee;
char msgBuffer[1519];
char fileName[1519];
int receivingFile = 0;
while (doRun) {
printf("Waiting for data...nn");
if ((recvfrom(s1, msgBuffer, 1519, 0, (struct sockaddr *) &otherClient,
&slen)) == SOCKET_ERROR) {
printf("recvfrom() failed with error code : %dn", WSAGetLastError());
continue;
}
//printf("Received packet from %s:%dn", inet_ntoa(otherClient.sin_addr), ntohs(otherClient.sin_port));
PacketData *packetData = dataToPacket(msgBuffer);
if (packetData == NULL) {
continue;
}
char flag = packetData->flag;
switch (flag) {
case 's': {
PacketData *packetDataAck = createPacket('a');
char *messageToSend2 = packetToData(packetDataAck, &sizee);
if (sendto(s1, messageToSend2, 18, 0, (struct sockaddr *) &otherClient, slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
//free(packetDataAck);
//free(messageToSend2);
break;
}
case 'm': {
if (receivingFile) {
FILE *fptr;
fptr = fopen(fileName, "a");
fprintf(fptr, "%s", packetData->data);
printf("Packet contains data: %sn", packetData->data);
fclose(fptr);
if(packetData->fragNum == packetData->fragTotal){
receivingFile = 0;
}
} else {
printf("Received packet n. %dn", packetData->fragNum);
printf("Packet data length: %dn", packetData->len);
printf("Packet contains data: %sn", packetData->data);
}
break;
}
case 'f': {
strcpy(fileName, packetData->data);
printf("Receiving file: %sn", fileName);
printf("Receiving file: %sn", packetData->data);
receivingFile = 1;
break;
}
default: {
doRun = 0;
break;
}
}
free(packetData);
}
return 0;
}
DWORD WINAPI sendThreadFunc(LPVOID lpParam) {
PacketData **fragments = NULL;
int doRun = 1;
char msgBuffer[1500];
int actualSize = 0;
int slen = sizeof(myClient);
while (1) {
printf("Enter message or -e to end messaging and return to menu:n");
fflush(stdin);
scanf("%1500[^n]", msgBuffer);
getc(stdin);
if (strcmp(msgBuffer, "-e") == 0) {
isInside = 0;
return 0;
}
if (strlen(msgBuffer) >= 1499) {
continue;
}
fragments = makeFragments(msgBuffer);
int numFragments = fragments[0]->fragTotal;
printf("Number of fragments: %dn", numFragments);
PacketData *packetData = createPacket('s');
if (packetData == NULL) {
printf("Could not init packet 's'n");
continue;
}
char *sync = packetToData(packetData, &actualSize);
if (sendto(s2, sync, 18, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("First fragment sent.n");
free(packetData);
char *ack = (char *) calloc(18, sizeof(char));
if (recvfrom(s2, ack, 18, 0, (struct sockaddr *) &myClient, &slen) ==
SOCKET_ERROR) {
printf("recvfrom() failed with error code : %dn", WSAGetLastError());
continue;
}
free(ack);
printf("Server confirmed first packet.n");
for (int i = 0; i < fragments[0]->fragTotal; i++) {
char *msgBuffer2 = packetToData(fragments[i], &actualSize);
if (sendto(s2, msgBuffer2, actualSize + 1, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
}
free(fragments);
}
return 0;
}
DWORD WINAPI sendFileFunc(LPVOID lpParam) {
char msgBuffer[1500];
int actualSize = 0;
int slen = sizeof(myClient);
while (1) {
printf("Enter file name or -e to return to menu:n");
fflush(stdin);
scanf("%1500[^n]", msgBuffer);
getc(stdin);
if (strcmp(msgBuffer, "-e") == 0) {
isInside = 0;
return 0;
}
if (strlen(msgBuffer) >= 1499) {
continue;
}
//Get file length:
FILE *fl = fopen(msgBuffer, "r");
if (fl == NULL) {
printf("Invalid name, try againn");
continue;
}
fseek(fl, 0, SEEK_END);
long fileLength = ftell(fl);
fclose(fl);
int numFragments = (fileLength - 1) / fragSize + 2;
printf("Number of fragments: %dn", numFragments);
PacketData *packetData = createPacket('s');
if (packetData == NULL) {
printf("Could not init packet 's'n");
continue;
}
char *sync = packetToData(packetData, &actualSize);
if (sendto(s2, sync, 18, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("First fragment sent.n");
free(packetData);
char *ack = (char *) calloc(18, sizeof(char));
if (recvfrom(s2, ack, 18, 0, (struct sockaddr *) &myClient, &slen) ==
SOCKET_ERROR) {
printf("recvfrom() failed with error code : %dn", WSAGetLastError());
continue;
}
//free(ack);
PacketData *fragments = NULL;
fragments = (PacketData *) malloc(sizeof(PacketData));
fragments->data = (char *) malloc(fragSize * sizeof(char));
strncpy(fragments->data, msgBuffer, strlen(msgBuffer));
fragments->data[strlen(msgBuffer)] = '';
fragments->flag = 'f';
fragments->len = strlen(msgBuffer);
fragments->fragNum = (unsigned int) (1);
fragments->fragTotal = (unsigned int) numFragments - 1;
fragments->CRC = (unsigned int) calculate_crc(msgBuffer, strlen(msgBuffer));
//Sending the first fragment with 'f' flag
char *toSend = packetToData(fragments, &actualSize);
if (sendto(s2, toSend, actualSize + 1, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("Server confirmed first packet.n");
size_t n = 0;
int counter = 0;
int fragNum = 2;
int c;
FILE *f2 = fopen(msgBuffer, "r");
if(f2 == NULL){
printf("File was nulln");
continue;
}
while ((c = fgetc(f2)) != EOF) {
msgBuffer[n++] = (char) c;
counter++;
if (counter == fragSize) {
n = 0;
counter = 0;
printf("Allocating fragment number: %dn", fragNum);
PacketData *fragments2 = NULL;
fragments2 = (PacketData *) malloc(sizeof(PacketData));
if(fragments2 == NULL){
printf("Incorrect mallocn");
break;
}
fragments2->data = (char *) malloc((fragSize+1) * sizeof(char));
if(fragments2->data == NULL){
printf("Incorrect malloc2n");
break;
}
strncpy(fragments2->data, msgBuffer, fragSize);
printf("Copying data to fragment number: %dn", fragNum);
fragments2->data[strlen(msgBuffer)] = '';
fragments2->flag = 'm';
fragments2->len = (unsigned int) fragSize;
fragments2->fragNum = (unsigned int) (fragNum);
fragments2->fragTotal = (unsigned int) numFragments - 1;
fragments2->CRC = (unsigned int) calculate_crc(msgBuffer, fragSize);
printf("Allocated fragment number: %dn", fragNum);
fragNum++;
char *toSend = packetToData(fragments2, &actualSize);
if (sendto(s2, toSend, actualSize + 1, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("Sent fragment number: %dn", fragNum);
}
}
fclose(fl);
}
return 0;
}
void p2pMode() {
int serverPort, clientPort;
char *serverAddr = (char *) malloc(20 * sizeof(char));
WSADATA wsa;
printf("nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("Failed. Error Code : %d", WSAGetLastError());
getchar();
exit(EXIT_FAILURE);
}
printf("Initialised.n");
char hostname[128] = "";
char menuBuffer;
gethostname(hostname, sizeof(hostname));
struct hostent *ent = gethostbyname(hostname);
struct in_addr ip_addr = *(struct in_addr *) (ent->h_addr);
printf("Your IP Address: %sn", inet_ntoa(ip_addr));
printf("Enter other PC IP Address:n");
scanf("%s", serverAddr);
if (!strcmp(serverAddr, "localhost"))
serverAddr = (char *) "127.0.0.1";
printf("Enter your listening port:n");
scanf("%d", &clientPort);
printf("Enter other PC's port:n");
scanf("%d", &serverPort);
if ((s1 = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
if ((s2 = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.n");
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(inet_ntoa(ip_addr));
server.sin_port = htons(clientPort);
myClient.sin_family = AF_INET;
myClient.sin_port = htons(serverPort);
myClient.sin_addr.S_un.S_addr = inet_addr(serverAddr);
if (bind(s1, (struct sockaddr *) &server, sizeof(server)) == SOCKET_ERROR) {
printf("Bind failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
free(serverAddr);
DWORD dwThreadId, dwThreadId2, dwThreadId3, dwThrdParam = 1;
CreateThread(
NULL, // default security attributes
10000, // use default stack size
receiveThreadFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId); // returns the thread identifier
while (1) {
if (!isInside) {
printf("For messages, write 'm', for file 'f'n");
scanf("%c", &menuBuffer);
switch (menuBuffer) {
case 'm':
CreateThread(
NULL, // default security attributes
10000, // use default stack size
sendThreadFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId2); // returns the thread identifier
isInside = 1;
break;
case 'f':
CreateThread(
NULL, // default security attributes
10000, // use default stack size
sendFileFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId3); // returns the thread identifier
isInside = 1;
break;
}
}
}
}
char *packetToData(PacketData *packet, int *size) { // convert packet into sendable data
int sizee = packet->len + 18;
*size = sizee;
char *temp = (char *) calloc(sizee, sizeof(char));
char *out;
if (temp == NULL) {
return NULL;
}
out = temp;
*(temp) = packet->flag;
*(unsigned int *) (temp + 2) = packet->CRC;
*(unsigned int *) (temp + 6) = packet->fragNum;
*(unsigned int *) (temp + 10) = packet->fragTotal;
*(unsigned int *) (temp + 14) = packet->len;
temp = (temp + 18);
int i;
for (i = 0; i < packet->len; i++) { // copy data
temp[i] = packet->data[i];
}
temp[i] = '';
return out;
}
PacketData *dataToPacket(char *data) { // convert received data into packet
printf("Data received: %sn", data);
PacketData *packet = (PacketData *) malloc(sizeof(PacketData));
if (packet == NULL)
return NULL;
packet->flag = *(data);
packet->CRC = *(unsigned int *) (data + 2);
packet->fragNum = *(unsigned int *) (data + 6);
packet->fragTotal = *(unsigned int *) (data + 10);
packet->len = *(unsigned int *) (data + 14);
packet->data = (char *) malloc(packet->len);
char *packetdata = (data + 18);
int i;
for (i = 0; i < packet->len; i++) { // copy data
packet->data[i] = packetdata[i];
}
packet->data[i] = '';
return packet;
}
PacketData *createPacket(char flag) {
PacketData *packetData = (PacketData *) malloc(sizeof(PacketData));
packetData->flag = flag;
packetData->len = 0;
packetData->CRC = 0;
packetData->fragNum = 1;
packetData->fragTotal = 1;
return packetData;
}
int calculate_crc(char *buf, int size) {
int crcHash = 10;
for (int i = 0; i < size; i++) {
crcHash += buf[i];
crcHash *= 31;
crcHash %= 30000;
}
return crcHash;
}
struct packetData **makeFragments(char *message) {
int i;
printf("Message length: %dn", strlen(message));
int fragCount = (strlen(message) - 1) / fragSize + 1;
if (fragCount == 0) {
fragCount++;
}
PacketData **fragments = (PacketData **) malloc((fragCount) * sizeof(PacketData *));
printf("Allocated %d fragmentsn", fragCount);
for (i = 0; i < fragCount; i++) {
fragments[i] = (PacketData *) malloc(sizeof(PacketData));
fragments[i]->data = (char *) malloc(fragSize * sizeof(char));
int toCopy = 0;
if (strlen(message) > fragSize) {
toCopy = fragSize;
} else {
toCopy = strlen(message);
}
strncpy(fragments[i]->data, message, toCopy);
fragments[i]->data[toCopy] = '';
fragments[i]->flag = 'm';
fragments[i]->len = (unsigned int) toCopy;
fragments[i]->fragNum = (unsigned int) (i + 1);
fragments[i]->fragTotal = (unsigned int) fragCount;
fragments[i]->CRC = (unsigned int) calculate_crc(message, toCopy);
message += fragSize;
}
printf("Fragments needed: %dn", fragments[0]->fragTotal);
return fragments;
}
and here is my header if someone needed to run it:
//
// Created by lukas on 11/19/2018.
//
#include <winsock2.h>
#include <windows.h>
#ifndef PKS2C_MAIN_H
#define PKS2C_MAIN_H
#endif //PKS2C_MAIN_H
typedef struct packetData {
char flag;
unsigned int CRC;
unsigned int fragNum;
unsigned int fragTotal;
unsigned int len;
char *data;
} PacketData;
struct packetData **makeFragments(char *message);
struct packetData **makeFileFragments(char *message);
char *packetToData(PacketData *packet, int *size);
PacketData *dataToPacket(char *data);
PacketData *createPacket(char flag);
void p2pMode();
int calculate_crc(char *buf, int size);
DWORD WINAPI receiveThread(LPVOID lpParam);
DWORD WINAPI sendThread(LPVOID lpParam);
SOCKET s1, s2;
struct sockaddr_in server, myClient, otherClient;
c windows multithreading free winsock2
1
That's alot of code. IndataToPacket()
you write past the end of the array withpacket->data[i] = '';
That may or may not be the issue. Maybe this will help you: How to debug small programs
– Johnny Mopp
Nov 20 at 21:15
HI, thanks for comment :) Unfortunately, that did not help. As what is crashing my code is that I am using free on corrupted pointer
– Lukas Anda
Nov 20 at 21:27
Maybe add some comments to point out where it crashes?
– sstefan
Nov 20 at 21:44
1
I run your program and sent main.cpp successfully. All on same computer, though.
– sstefan
Nov 20 at 22:02
1
@LukasAnda you definitely have some memory issues. It tried to write to file while sending...don't think it's supposed to.
– sstefan
Nov 20 at 22:09
|
show 3 more comments
I know this is kinda lame question, but what am I doing wrong in my code ? Basically, I wanna create communication on local IP using UDP, also send some files etc. The problem is, that when I get to freeing my structures after using them/converting them to/from char* the program just crashes. What is even more weird, the program does not crash when debugging and stepping through using CLion debugger. What am I doing wrong? Here is my source code:
The error seems to happen, when I can not allocate more memory (so logically, I need to free some) when sending a file over network. Sending messages works just fine
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
// PKS2Visual.cpp : Defines the entry point for the console application.
//
#include "main.h"
#include <stdio.h>
#include <string.h>
#include <winsock2.h>
#include <windows.h>
#include <time.h>
#define BREAKSOMETHING 0
#pragma comment(lib, "ws2_32.lib")
int fragSize = 1500;
int isInside = 0;
SOCKET s1, s2;
struct sockaddr_in server, myClient, otherClient;
int main() {
char mode;
printf("Enter fragment size:n");
scanf("%d", &fragSize);
p2pMode();
}
DWORD WINAPI receiveThreadFunc(LPVOID lpParam) {
int slen = sizeof(otherClient);
int doRun = 1;
int sizee;
char msgBuffer[1519];
char fileName[1519];
int receivingFile = 0;
while (doRun) {
printf("Waiting for data...nn");
if ((recvfrom(s1, msgBuffer, 1519, 0, (struct sockaddr *) &otherClient,
&slen)) == SOCKET_ERROR) {
printf("recvfrom() failed with error code : %dn", WSAGetLastError());
continue;
}
//printf("Received packet from %s:%dn", inet_ntoa(otherClient.sin_addr), ntohs(otherClient.sin_port));
PacketData *packetData = dataToPacket(msgBuffer);
if (packetData == NULL) {
continue;
}
char flag = packetData->flag;
switch (flag) {
case 's': {
PacketData *packetDataAck = createPacket('a');
char *messageToSend2 = packetToData(packetDataAck, &sizee);
if (sendto(s1, messageToSend2, 18, 0, (struct sockaddr *) &otherClient, slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
//free(packetDataAck);
//free(messageToSend2);
break;
}
case 'm': {
if (receivingFile) {
FILE *fptr;
fptr = fopen(fileName, "a");
fprintf(fptr, "%s", packetData->data);
printf("Packet contains data: %sn", packetData->data);
fclose(fptr);
if(packetData->fragNum == packetData->fragTotal){
receivingFile = 0;
}
} else {
printf("Received packet n. %dn", packetData->fragNum);
printf("Packet data length: %dn", packetData->len);
printf("Packet contains data: %sn", packetData->data);
}
break;
}
case 'f': {
strcpy(fileName, packetData->data);
printf("Receiving file: %sn", fileName);
printf("Receiving file: %sn", packetData->data);
receivingFile = 1;
break;
}
default: {
doRun = 0;
break;
}
}
free(packetData);
}
return 0;
}
DWORD WINAPI sendThreadFunc(LPVOID lpParam) {
PacketData **fragments = NULL;
int doRun = 1;
char msgBuffer[1500];
int actualSize = 0;
int slen = sizeof(myClient);
while (1) {
printf("Enter message or -e to end messaging and return to menu:n");
fflush(stdin);
scanf("%1500[^n]", msgBuffer);
getc(stdin);
if (strcmp(msgBuffer, "-e") == 0) {
isInside = 0;
return 0;
}
if (strlen(msgBuffer) >= 1499) {
continue;
}
fragments = makeFragments(msgBuffer);
int numFragments = fragments[0]->fragTotal;
printf("Number of fragments: %dn", numFragments);
PacketData *packetData = createPacket('s');
if (packetData == NULL) {
printf("Could not init packet 's'n");
continue;
}
char *sync = packetToData(packetData, &actualSize);
if (sendto(s2, sync, 18, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("First fragment sent.n");
free(packetData);
char *ack = (char *) calloc(18, sizeof(char));
if (recvfrom(s2, ack, 18, 0, (struct sockaddr *) &myClient, &slen) ==
SOCKET_ERROR) {
printf("recvfrom() failed with error code : %dn", WSAGetLastError());
continue;
}
free(ack);
printf("Server confirmed first packet.n");
for (int i = 0; i < fragments[0]->fragTotal; i++) {
char *msgBuffer2 = packetToData(fragments[i], &actualSize);
if (sendto(s2, msgBuffer2, actualSize + 1, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
}
free(fragments);
}
return 0;
}
DWORD WINAPI sendFileFunc(LPVOID lpParam) {
char msgBuffer[1500];
int actualSize = 0;
int slen = sizeof(myClient);
while (1) {
printf("Enter file name or -e to return to menu:n");
fflush(stdin);
scanf("%1500[^n]", msgBuffer);
getc(stdin);
if (strcmp(msgBuffer, "-e") == 0) {
isInside = 0;
return 0;
}
if (strlen(msgBuffer) >= 1499) {
continue;
}
//Get file length:
FILE *fl = fopen(msgBuffer, "r");
if (fl == NULL) {
printf("Invalid name, try againn");
continue;
}
fseek(fl, 0, SEEK_END);
long fileLength = ftell(fl);
fclose(fl);
int numFragments = (fileLength - 1) / fragSize + 2;
printf("Number of fragments: %dn", numFragments);
PacketData *packetData = createPacket('s');
if (packetData == NULL) {
printf("Could not init packet 's'n");
continue;
}
char *sync = packetToData(packetData, &actualSize);
if (sendto(s2, sync, 18, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("First fragment sent.n");
free(packetData);
char *ack = (char *) calloc(18, sizeof(char));
if (recvfrom(s2, ack, 18, 0, (struct sockaddr *) &myClient, &slen) ==
SOCKET_ERROR) {
printf("recvfrom() failed with error code : %dn", WSAGetLastError());
continue;
}
//free(ack);
PacketData *fragments = NULL;
fragments = (PacketData *) malloc(sizeof(PacketData));
fragments->data = (char *) malloc(fragSize * sizeof(char));
strncpy(fragments->data, msgBuffer, strlen(msgBuffer));
fragments->data[strlen(msgBuffer)] = '';
fragments->flag = 'f';
fragments->len = strlen(msgBuffer);
fragments->fragNum = (unsigned int) (1);
fragments->fragTotal = (unsigned int) numFragments - 1;
fragments->CRC = (unsigned int) calculate_crc(msgBuffer, strlen(msgBuffer));
//Sending the first fragment with 'f' flag
char *toSend = packetToData(fragments, &actualSize);
if (sendto(s2, toSend, actualSize + 1, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("Server confirmed first packet.n");
size_t n = 0;
int counter = 0;
int fragNum = 2;
int c;
FILE *f2 = fopen(msgBuffer, "r");
if(f2 == NULL){
printf("File was nulln");
continue;
}
while ((c = fgetc(f2)) != EOF) {
msgBuffer[n++] = (char) c;
counter++;
if (counter == fragSize) {
n = 0;
counter = 0;
printf("Allocating fragment number: %dn", fragNum);
PacketData *fragments2 = NULL;
fragments2 = (PacketData *) malloc(sizeof(PacketData));
if(fragments2 == NULL){
printf("Incorrect mallocn");
break;
}
fragments2->data = (char *) malloc((fragSize+1) * sizeof(char));
if(fragments2->data == NULL){
printf("Incorrect malloc2n");
break;
}
strncpy(fragments2->data, msgBuffer, fragSize);
printf("Copying data to fragment number: %dn", fragNum);
fragments2->data[strlen(msgBuffer)] = '';
fragments2->flag = 'm';
fragments2->len = (unsigned int) fragSize;
fragments2->fragNum = (unsigned int) (fragNum);
fragments2->fragTotal = (unsigned int) numFragments - 1;
fragments2->CRC = (unsigned int) calculate_crc(msgBuffer, fragSize);
printf("Allocated fragment number: %dn", fragNum);
fragNum++;
char *toSend = packetToData(fragments2, &actualSize);
if (sendto(s2, toSend, actualSize + 1, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("Sent fragment number: %dn", fragNum);
}
}
fclose(fl);
}
return 0;
}
void p2pMode() {
int serverPort, clientPort;
char *serverAddr = (char *) malloc(20 * sizeof(char));
WSADATA wsa;
printf("nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("Failed. Error Code : %d", WSAGetLastError());
getchar();
exit(EXIT_FAILURE);
}
printf("Initialised.n");
char hostname[128] = "";
char menuBuffer;
gethostname(hostname, sizeof(hostname));
struct hostent *ent = gethostbyname(hostname);
struct in_addr ip_addr = *(struct in_addr *) (ent->h_addr);
printf("Your IP Address: %sn", inet_ntoa(ip_addr));
printf("Enter other PC IP Address:n");
scanf("%s", serverAddr);
if (!strcmp(serverAddr, "localhost"))
serverAddr = (char *) "127.0.0.1";
printf("Enter your listening port:n");
scanf("%d", &clientPort);
printf("Enter other PC's port:n");
scanf("%d", &serverPort);
if ((s1 = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
if ((s2 = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.n");
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(inet_ntoa(ip_addr));
server.sin_port = htons(clientPort);
myClient.sin_family = AF_INET;
myClient.sin_port = htons(serverPort);
myClient.sin_addr.S_un.S_addr = inet_addr(serverAddr);
if (bind(s1, (struct sockaddr *) &server, sizeof(server)) == SOCKET_ERROR) {
printf("Bind failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
free(serverAddr);
DWORD dwThreadId, dwThreadId2, dwThreadId3, dwThrdParam = 1;
CreateThread(
NULL, // default security attributes
10000, // use default stack size
receiveThreadFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId); // returns the thread identifier
while (1) {
if (!isInside) {
printf("For messages, write 'm', for file 'f'n");
scanf("%c", &menuBuffer);
switch (menuBuffer) {
case 'm':
CreateThread(
NULL, // default security attributes
10000, // use default stack size
sendThreadFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId2); // returns the thread identifier
isInside = 1;
break;
case 'f':
CreateThread(
NULL, // default security attributes
10000, // use default stack size
sendFileFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId3); // returns the thread identifier
isInside = 1;
break;
}
}
}
}
char *packetToData(PacketData *packet, int *size) { // convert packet into sendable data
int sizee = packet->len + 18;
*size = sizee;
char *temp = (char *) calloc(sizee, sizeof(char));
char *out;
if (temp == NULL) {
return NULL;
}
out = temp;
*(temp) = packet->flag;
*(unsigned int *) (temp + 2) = packet->CRC;
*(unsigned int *) (temp + 6) = packet->fragNum;
*(unsigned int *) (temp + 10) = packet->fragTotal;
*(unsigned int *) (temp + 14) = packet->len;
temp = (temp + 18);
int i;
for (i = 0; i < packet->len; i++) { // copy data
temp[i] = packet->data[i];
}
temp[i] = '';
return out;
}
PacketData *dataToPacket(char *data) { // convert received data into packet
printf("Data received: %sn", data);
PacketData *packet = (PacketData *) malloc(sizeof(PacketData));
if (packet == NULL)
return NULL;
packet->flag = *(data);
packet->CRC = *(unsigned int *) (data + 2);
packet->fragNum = *(unsigned int *) (data + 6);
packet->fragTotal = *(unsigned int *) (data + 10);
packet->len = *(unsigned int *) (data + 14);
packet->data = (char *) malloc(packet->len);
char *packetdata = (data + 18);
int i;
for (i = 0; i < packet->len; i++) { // copy data
packet->data[i] = packetdata[i];
}
packet->data[i] = '';
return packet;
}
PacketData *createPacket(char flag) {
PacketData *packetData = (PacketData *) malloc(sizeof(PacketData));
packetData->flag = flag;
packetData->len = 0;
packetData->CRC = 0;
packetData->fragNum = 1;
packetData->fragTotal = 1;
return packetData;
}
int calculate_crc(char *buf, int size) {
int crcHash = 10;
for (int i = 0; i < size; i++) {
crcHash += buf[i];
crcHash *= 31;
crcHash %= 30000;
}
return crcHash;
}
struct packetData **makeFragments(char *message) {
int i;
printf("Message length: %dn", strlen(message));
int fragCount = (strlen(message) - 1) / fragSize + 1;
if (fragCount == 0) {
fragCount++;
}
PacketData **fragments = (PacketData **) malloc((fragCount) * sizeof(PacketData *));
printf("Allocated %d fragmentsn", fragCount);
for (i = 0; i < fragCount; i++) {
fragments[i] = (PacketData *) malloc(sizeof(PacketData));
fragments[i]->data = (char *) malloc(fragSize * sizeof(char));
int toCopy = 0;
if (strlen(message) > fragSize) {
toCopy = fragSize;
} else {
toCopy = strlen(message);
}
strncpy(fragments[i]->data, message, toCopy);
fragments[i]->data[toCopy] = '';
fragments[i]->flag = 'm';
fragments[i]->len = (unsigned int) toCopy;
fragments[i]->fragNum = (unsigned int) (i + 1);
fragments[i]->fragTotal = (unsigned int) fragCount;
fragments[i]->CRC = (unsigned int) calculate_crc(message, toCopy);
message += fragSize;
}
printf("Fragments needed: %dn", fragments[0]->fragTotal);
return fragments;
}
and here is my header if someone needed to run it:
//
// Created by lukas on 11/19/2018.
//
#include <winsock2.h>
#include <windows.h>
#ifndef PKS2C_MAIN_H
#define PKS2C_MAIN_H
#endif //PKS2C_MAIN_H
typedef struct packetData {
char flag;
unsigned int CRC;
unsigned int fragNum;
unsigned int fragTotal;
unsigned int len;
char *data;
} PacketData;
struct packetData **makeFragments(char *message);
struct packetData **makeFileFragments(char *message);
char *packetToData(PacketData *packet, int *size);
PacketData *dataToPacket(char *data);
PacketData *createPacket(char flag);
void p2pMode();
int calculate_crc(char *buf, int size);
DWORD WINAPI receiveThread(LPVOID lpParam);
DWORD WINAPI sendThread(LPVOID lpParam);
SOCKET s1, s2;
struct sockaddr_in server, myClient, otherClient;
c windows multithreading free winsock2
I know this is kinda lame question, but what am I doing wrong in my code ? Basically, I wanna create communication on local IP using UDP, also send some files etc. The problem is, that when I get to freeing my structures after using them/converting them to/from char* the program just crashes. What is even more weird, the program does not crash when debugging and stepping through using CLion debugger. What am I doing wrong? Here is my source code:
The error seems to happen, when I can not allocate more memory (so logically, I need to free some) when sending a file over network. Sending messages works just fine
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
// PKS2Visual.cpp : Defines the entry point for the console application.
//
#include "main.h"
#include <stdio.h>
#include <string.h>
#include <winsock2.h>
#include <windows.h>
#include <time.h>
#define BREAKSOMETHING 0
#pragma comment(lib, "ws2_32.lib")
int fragSize = 1500;
int isInside = 0;
SOCKET s1, s2;
struct sockaddr_in server, myClient, otherClient;
int main() {
char mode;
printf("Enter fragment size:n");
scanf("%d", &fragSize);
p2pMode();
}
DWORD WINAPI receiveThreadFunc(LPVOID lpParam) {
int slen = sizeof(otherClient);
int doRun = 1;
int sizee;
char msgBuffer[1519];
char fileName[1519];
int receivingFile = 0;
while (doRun) {
printf("Waiting for data...nn");
if ((recvfrom(s1, msgBuffer, 1519, 0, (struct sockaddr *) &otherClient,
&slen)) == SOCKET_ERROR) {
printf("recvfrom() failed with error code : %dn", WSAGetLastError());
continue;
}
//printf("Received packet from %s:%dn", inet_ntoa(otherClient.sin_addr), ntohs(otherClient.sin_port));
PacketData *packetData = dataToPacket(msgBuffer);
if (packetData == NULL) {
continue;
}
char flag = packetData->flag;
switch (flag) {
case 's': {
PacketData *packetDataAck = createPacket('a');
char *messageToSend2 = packetToData(packetDataAck, &sizee);
if (sendto(s1, messageToSend2, 18, 0, (struct sockaddr *) &otherClient, slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
//free(packetDataAck);
//free(messageToSend2);
break;
}
case 'm': {
if (receivingFile) {
FILE *fptr;
fptr = fopen(fileName, "a");
fprintf(fptr, "%s", packetData->data);
printf("Packet contains data: %sn", packetData->data);
fclose(fptr);
if(packetData->fragNum == packetData->fragTotal){
receivingFile = 0;
}
} else {
printf("Received packet n. %dn", packetData->fragNum);
printf("Packet data length: %dn", packetData->len);
printf("Packet contains data: %sn", packetData->data);
}
break;
}
case 'f': {
strcpy(fileName, packetData->data);
printf("Receiving file: %sn", fileName);
printf("Receiving file: %sn", packetData->data);
receivingFile = 1;
break;
}
default: {
doRun = 0;
break;
}
}
free(packetData);
}
return 0;
}
DWORD WINAPI sendThreadFunc(LPVOID lpParam) {
PacketData **fragments = NULL;
int doRun = 1;
char msgBuffer[1500];
int actualSize = 0;
int slen = sizeof(myClient);
while (1) {
printf("Enter message or -e to end messaging and return to menu:n");
fflush(stdin);
scanf("%1500[^n]", msgBuffer);
getc(stdin);
if (strcmp(msgBuffer, "-e") == 0) {
isInside = 0;
return 0;
}
if (strlen(msgBuffer) >= 1499) {
continue;
}
fragments = makeFragments(msgBuffer);
int numFragments = fragments[0]->fragTotal;
printf("Number of fragments: %dn", numFragments);
PacketData *packetData = createPacket('s');
if (packetData == NULL) {
printf("Could not init packet 's'n");
continue;
}
char *sync = packetToData(packetData, &actualSize);
if (sendto(s2, sync, 18, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("First fragment sent.n");
free(packetData);
char *ack = (char *) calloc(18, sizeof(char));
if (recvfrom(s2, ack, 18, 0, (struct sockaddr *) &myClient, &slen) ==
SOCKET_ERROR) {
printf("recvfrom() failed with error code : %dn", WSAGetLastError());
continue;
}
free(ack);
printf("Server confirmed first packet.n");
for (int i = 0; i < fragments[0]->fragTotal; i++) {
char *msgBuffer2 = packetToData(fragments[i], &actualSize);
if (sendto(s2, msgBuffer2, actualSize + 1, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
}
free(fragments);
}
return 0;
}
DWORD WINAPI sendFileFunc(LPVOID lpParam) {
char msgBuffer[1500];
int actualSize = 0;
int slen = sizeof(myClient);
while (1) {
printf("Enter file name or -e to return to menu:n");
fflush(stdin);
scanf("%1500[^n]", msgBuffer);
getc(stdin);
if (strcmp(msgBuffer, "-e") == 0) {
isInside = 0;
return 0;
}
if (strlen(msgBuffer) >= 1499) {
continue;
}
//Get file length:
FILE *fl = fopen(msgBuffer, "r");
if (fl == NULL) {
printf("Invalid name, try againn");
continue;
}
fseek(fl, 0, SEEK_END);
long fileLength = ftell(fl);
fclose(fl);
int numFragments = (fileLength - 1) / fragSize + 2;
printf("Number of fragments: %dn", numFragments);
PacketData *packetData = createPacket('s');
if (packetData == NULL) {
printf("Could not init packet 's'n");
continue;
}
char *sync = packetToData(packetData, &actualSize);
if (sendto(s2, sync, 18, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("First fragment sent.n");
free(packetData);
char *ack = (char *) calloc(18, sizeof(char));
if (recvfrom(s2, ack, 18, 0, (struct sockaddr *) &myClient, &slen) ==
SOCKET_ERROR) {
printf("recvfrom() failed with error code : %dn", WSAGetLastError());
continue;
}
//free(ack);
PacketData *fragments = NULL;
fragments = (PacketData *) malloc(sizeof(PacketData));
fragments->data = (char *) malloc(fragSize * sizeof(char));
strncpy(fragments->data, msgBuffer, strlen(msgBuffer));
fragments->data[strlen(msgBuffer)] = '';
fragments->flag = 'f';
fragments->len = strlen(msgBuffer);
fragments->fragNum = (unsigned int) (1);
fragments->fragTotal = (unsigned int) numFragments - 1;
fragments->CRC = (unsigned int) calculate_crc(msgBuffer, strlen(msgBuffer));
//Sending the first fragment with 'f' flag
char *toSend = packetToData(fragments, &actualSize);
if (sendto(s2, toSend, actualSize + 1, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("Server confirmed first packet.n");
size_t n = 0;
int counter = 0;
int fragNum = 2;
int c;
FILE *f2 = fopen(msgBuffer, "r");
if(f2 == NULL){
printf("File was nulln");
continue;
}
while ((c = fgetc(f2)) != EOF) {
msgBuffer[n++] = (char) c;
counter++;
if (counter == fragSize) {
n = 0;
counter = 0;
printf("Allocating fragment number: %dn", fragNum);
PacketData *fragments2 = NULL;
fragments2 = (PacketData *) malloc(sizeof(PacketData));
if(fragments2 == NULL){
printf("Incorrect mallocn");
break;
}
fragments2->data = (char *) malloc((fragSize+1) * sizeof(char));
if(fragments2->data == NULL){
printf("Incorrect malloc2n");
break;
}
strncpy(fragments2->data, msgBuffer, fragSize);
printf("Copying data to fragment number: %dn", fragNum);
fragments2->data[strlen(msgBuffer)] = '';
fragments2->flag = 'm';
fragments2->len = (unsigned int) fragSize;
fragments2->fragNum = (unsigned int) (fragNum);
fragments2->fragTotal = (unsigned int) numFragments - 1;
fragments2->CRC = (unsigned int) calculate_crc(msgBuffer, fragSize);
printf("Allocated fragment number: %dn", fragNum);
fragNum++;
char *toSend = packetToData(fragments2, &actualSize);
if (sendto(s2, toSend, actualSize + 1, 0, (struct sockaddr *) &myClient,
slen) == SOCKET_ERROR) {
printf("sendto() failed with error code : %dn", WSAGetLastError());
continue;
}
printf("Sent fragment number: %dn", fragNum);
}
}
fclose(fl);
}
return 0;
}
void p2pMode() {
int serverPort, clientPort;
char *serverAddr = (char *) malloc(20 * sizeof(char));
WSADATA wsa;
printf("nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("Failed. Error Code : %d", WSAGetLastError());
getchar();
exit(EXIT_FAILURE);
}
printf("Initialised.n");
char hostname[128] = "";
char menuBuffer;
gethostname(hostname, sizeof(hostname));
struct hostent *ent = gethostbyname(hostname);
struct in_addr ip_addr = *(struct in_addr *) (ent->h_addr);
printf("Your IP Address: %sn", inet_ntoa(ip_addr));
printf("Enter other PC IP Address:n");
scanf("%s", serverAddr);
if (!strcmp(serverAddr, "localhost"))
serverAddr = (char *) "127.0.0.1";
printf("Enter your listening port:n");
scanf("%d", &clientPort);
printf("Enter other PC's port:n");
scanf("%d", &serverPort);
if ((s1 = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
if ((s2 = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.n");
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(inet_ntoa(ip_addr));
server.sin_port = htons(clientPort);
myClient.sin_family = AF_INET;
myClient.sin_port = htons(serverPort);
myClient.sin_addr.S_un.S_addr = inet_addr(serverAddr);
if (bind(s1, (struct sockaddr *) &server, sizeof(server)) == SOCKET_ERROR) {
printf("Bind failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
free(serverAddr);
DWORD dwThreadId, dwThreadId2, dwThreadId3, dwThrdParam = 1;
CreateThread(
NULL, // default security attributes
10000, // use default stack size
receiveThreadFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId); // returns the thread identifier
while (1) {
if (!isInside) {
printf("For messages, write 'm', for file 'f'n");
scanf("%c", &menuBuffer);
switch (menuBuffer) {
case 'm':
CreateThread(
NULL, // default security attributes
10000, // use default stack size
sendThreadFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId2); // returns the thread identifier
isInside = 1;
break;
case 'f':
CreateThread(
NULL, // default security attributes
10000, // use default stack size
sendFileFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId3); // returns the thread identifier
isInside = 1;
break;
}
}
}
}
char *packetToData(PacketData *packet, int *size) { // convert packet into sendable data
int sizee = packet->len + 18;
*size = sizee;
char *temp = (char *) calloc(sizee, sizeof(char));
char *out;
if (temp == NULL) {
return NULL;
}
out = temp;
*(temp) = packet->flag;
*(unsigned int *) (temp + 2) = packet->CRC;
*(unsigned int *) (temp + 6) = packet->fragNum;
*(unsigned int *) (temp + 10) = packet->fragTotal;
*(unsigned int *) (temp + 14) = packet->len;
temp = (temp + 18);
int i;
for (i = 0; i < packet->len; i++) { // copy data
temp[i] = packet->data[i];
}
temp[i] = '';
return out;
}
PacketData *dataToPacket(char *data) { // convert received data into packet
printf("Data received: %sn", data);
PacketData *packet = (PacketData *) malloc(sizeof(PacketData));
if (packet == NULL)
return NULL;
packet->flag = *(data);
packet->CRC = *(unsigned int *) (data + 2);
packet->fragNum = *(unsigned int *) (data + 6);
packet->fragTotal = *(unsigned int *) (data + 10);
packet->len = *(unsigned int *) (data + 14);
packet->data = (char *) malloc(packet->len);
char *packetdata = (data + 18);
int i;
for (i = 0; i < packet->len; i++) { // copy data
packet->data[i] = packetdata[i];
}
packet->data[i] = '';
return packet;
}
PacketData *createPacket(char flag) {
PacketData *packetData = (PacketData *) malloc(sizeof(PacketData));
packetData->flag = flag;
packetData->len = 0;
packetData->CRC = 0;
packetData->fragNum = 1;
packetData->fragTotal = 1;
return packetData;
}
int calculate_crc(char *buf, int size) {
int crcHash = 10;
for (int i = 0; i < size; i++) {
crcHash += buf[i];
crcHash *= 31;
crcHash %= 30000;
}
return crcHash;
}
struct packetData **makeFragments(char *message) {
int i;
printf("Message length: %dn", strlen(message));
int fragCount = (strlen(message) - 1) / fragSize + 1;
if (fragCount == 0) {
fragCount++;
}
PacketData **fragments = (PacketData **) malloc((fragCount) * sizeof(PacketData *));
printf("Allocated %d fragmentsn", fragCount);
for (i = 0; i < fragCount; i++) {
fragments[i] = (PacketData *) malloc(sizeof(PacketData));
fragments[i]->data = (char *) malloc(fragSize * sizeof(char));
int toCopy = 0;
if (strlen(message) > fragSize) {
toCopy = fragSize;
} else {
toCopy = strlen(message);
}
strncpy(fragments[i]->data, message, toCopy);
fragments[i]->data[toCopy] = '';
fragments[i]->flag = 'm';
fragments[i]->len = (unsigned int) toCopy;
fragments[i]->fragNum = (unsigned int) (i + 1);
fragments[i]->fragTotal = (unsigned int) fragCount;
fragments[i]->CRC = (unsigned int) calculate_crc(message, toCopy);
message += fragSize;
}
printf("Fragments needed: %dn", fragments[0]->fragTotal);
return fragments;
}
and here is my header if someone needed to run it:
//
// Created by lukas on 11/19/2018.
//
#include <winsock2.h>
#include <windows.h>
#ifndef PKS2C_MAIN_H
#define PKS2C_MAIN_H
#endif //PKS2C_MAIN_H
typedef struct packetData {
char flag;
unsigned int CRC;
unsigned int fragNum;
unsigned int fragTotal;
unsigned int len;
char *data;
} PacketData;
struct packetData **makeFragments(char *message);
struct packetData **makeFileFragments(char *message);
char *packetToData(PacketData *packet, int *size);
PacketData *dataToPacket(char *data);
PacketData *createPacket(char flag);
void p2pMode();
int calculate_crc(char *buf, int size);
DWORD WINAPI receiveThread(LPVOID lpParam);
DWORD WINAPI sendThread(LPVOID lpParam);
SOCKET s1, s2;
struct sockaddr_in server, myClient, otherClient;
c windows multithreading free winsock2
c windows multithreading free winsock2
asked Nov 20 at 21:08
Lukas Anda
4671620
4671620
1
That's alot of code. IndataToPacket()
you write past the end of the array withpacket->data[i] = '';
That may or may not be the issue. Maybe this will help you: How to debug small programs
– Johnny Mopp
Nov 20 at 21:15
HI, thanks for comment :) Unfortunately, that did not help. As what is crashing my code is that I am using free on corrupted pointer
– Lukas Anda
Nov 20 at 21:27
Maybe add some comments to point out where it crashes?
– sstefan
Nov 20 at 21:44
1
I run your program and sent main.cpp successfully. All on same computer, though.
– sstefan
Nov 20 at 22:02
1
@LukasAnda you definitely have some memory issues. It tried to write to file while sending...don't think it's supposed to.
– sstefan
Nov 20 at 22:09
|
show 3 more comments
1
That's alot of code. IndataToPacket()
you write past the end of the array withpacket->data[i] = '';
That may or may not be the issue. Maybe this will help you: How to debug small programs
– Johnny Mopp
Nov 20 at 21:15
HI, thanks for comment :) Unfortunately, that did not help. As what is crashing my code is that I am using free on corrupted pointer
– Lukas Anda
Nov 20 at 21:27
Maybe add some comments to point out where it crashes?
– sstefan
Nov 20 at 21:44
1
I run your program and sent main.cpp successfully. All on same computer, though.
– sstefan
Nov 20 at 22:02
1
@LukasAnda you definitely have some memory issues. It tried to write to file while sending...don't think it's supposed to.
– sstefan
Nov 20 at 22:09
1
1
That's alot of code. In
dataToPacket()
you write past the end of the array with packet->data[i] = '';
That may or may not be the issue. Maybe this will help you: How to debug small programs– Johnny Mopp
Nov 20 at 21:15
That's alot of code. In
dataToPacket()
you write past the end of the array with packet->data[i] = '';
That may or may not be the issue. Maybe this will help you: How to debug small programs– Johnny Mopp
Nov 20 at 21:15
HI, thanks for comment :) Unfortunately, that did not help. As what is crashing my code is that I am using free on corrupted pointer
– Lukas Anda
Nov 20 at 21:27
HI, thanks for comment :) Unfortunately, that did not help. As what is crashing my code is that I am using free on corrupted pointer
– Lukas Anda
Nov 20 at 21:27
Maybe add some comments to point out where it crashes?
– sstefan
Nov 20 at 21:44
Maybe add some comments to point out where it crashes?
– sstefan
Nov 20 at 21:44
1
1
I run your program and sent main.cpp successfully. All on same computer, though.
– sstefan
Nov 20 at 22:02
I run your program and sent main.cpp successfully. All on same computer, though.
– sstefan
Nov 20 at 22:02
1
1
@LukasAnda you definitely have some memory issues. It tried to write to file while sending...don't think it's supposed to.
– sstefan
Nov 20 at 22:09
@LukasAnda you definitely have some memory issues. It tried to write to file while sending...don't think it's supposed to.
– sstefan
Nov 20 at 22:09
|
show 3 more comments
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401559%2fc-winsock-program-crashing-whenever-i-free-structure%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401559%2fc-winsock-program-crashing-whenever-i-free-structure%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
That's alot of code. In
dataToPacket()
you write past the end of the array withpacket->data[i] = '';
That may or may not be the issue. Maybe this will help you: How to debug small programs– Johnny Mopp
Nov 20 at 21:15
HI, thanks for comment :) Unfortunately, that did not help. As what is crashing my code is that I am using free on corrupted pointer
– Lukas Anda
Nov 20 at 21:27
Maybe add some comments to point out where it crashes?
– sstefan
Nov 20 at 21:44
1
I run your program and sent main.cpp successfully. All on same computer, though.
– sstefan
Nov 20 at 22:02
1
@LukasAnda you definitely have some memory issues. It tried to write to file while sending...don't think it's supposed to.
– sstefan
Nov 20 at 22:09