Related
I have to get the numbers in a buffer with recvfrom() function and compute the sum. Then I have to use sprintf() function to get the result as a string and then I have to send this string with sendto() function. Everything is fine is my code except the result that I send with sendto(). Could you help me please ?
int recv_and_handle_message(const struct sockaddr *src_addr, socklen_t addrlen) {
// TODO: Create a IPv6 socket supporting datagrams
// TODO: Bind it to the source
// TODO: Receive a message through the socket
// TODO: Perform the computation
// TODO: Send back the result
int result = 0;
int sock = socket(AF_INET6, SOCK_DGRAM, 0);
if(sock == -1) return sock;
int err = bind(sock,src_addr,addrlen);
if (err == - 1) return err;
struct sockaddr_storage recever;
socklen_t len = sizeof(recever);
char buffer[1024];
int rec = recvfrom(sock, buffer, sizeof(char)*1024, 0, (struct sockaddr*)&recever, &len);
if(rec == -1) return rec;
int*current = (int*)&buffer;
for (int i = 0; i < rec/4; ++i){
result += current[i];
}
char res[1000];
int b = sprintf(res, "%d", result);
if(b == -1){
return -1;
}
char rese[b];
memcpy(rese, res, b);
//for (int i = 0; i < b; ++i){
// rese[i] = res[i];
//}
int r = sendto(sock, &rese, 1, 0, (struct sockaddr *)&recever, len);
if(r == -1){
return -1;
}
return 0;
}
I have a server-client program written in C. My problem is that I have a while loop in which I receive and send data. it happens a lot when i need my server to do other things but it just stops at recv() function and waits for data from client. How can I overcome it? I've tried this:
int waitForAnswer =1;
if((childpid = fork()) == 0){
close(socketfd);
close(fd[0]);
while(1){
if(waitForAnswer) {
receive(newSocket, buff) == 0;
parseRecvMess(buff);
}
waitForAnswer =0;
but it doesn't work. For some reason the program finishes with an exit code 1, at accepting socket with a "No Socket" error.
Here is my program ;
nt main(){
int size = 256;
char buff[size];
char sbuff[size];
int n;
int reader;
int socketfd, ret;
struct sockaddr_in serverAddr;
int newSocket = -2;
struct sockaddr_in newAddr;
socklen_t addr_size;
pid_t childpid;
pocet_hracu = 0;
srand(time(NULL));
initializeLobby();
memset(buff, 0, size);
memset(sbuff, 0, size);
socketfd = socket(AF_INET,SOCK_STREAM,0);
if(socketfd < 0){
printf("\n error in socket creation");
return -1;
}
printf("\n Server socket is created\n");
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = bind(socketfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if(ret < 0){
printf("Error in binding\n");
return -1;
}
printf("[*]Bind to port %d\n", PORT);
if(listen(socketfd, 10) == 0){
printf("Listening...\n");
}else{
printf("Error in binding\n");
}
// pipe pro komunikaci
int readpipe;
int writepipe;
int fd[2];
pipe(fd);
for (;;) {
newSocket = accept(socketfd, (struct sockaddr *) &newAddr, &addr_size);
if (newSocket < 0) {
printf("No socket\n");
exit(1);
}
// struct timeval tv;
// tv.tv_sec = 1;
// tv.tv_usec = 0;
// setsockopt(socketfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv));
// read the message from client and copy it in buffer
receive(newSocket, buff);
parseRecvMess(buff);
printf("\n%s sent: %s", user, command);
if (strncmp(" new", command, 4) == 0) {
player newPlayer;
newPlayer.name = (char *) malloc(sizeof(char) * 10); // *login must contain up to 10 characters
strcpy(newPlayer.name, user);
newPlayer.gameScore = 0;
newPlayer.roundScore = 0;
newPlayer.socket = newSocket;
// TODO vztvorit pipe pro kounikaci
// newPlayer.readpipe
// newPlayer.writepipe
addToPlayersArray(&newPlayer); //TODO player index is not increasing
addToLobby(&newPlayer);
printf("Server : %s uspesne prihlasen.\n", newPlayer.name);
}
bzero(buff, size);
printf("To client : OK\n");
strcpy(sbuff, "OK\n" );
sendMess(newSocket, sbuff, sizeof(sbuff));
int waitForAnswer =1;
if((childpid = fork()) == 0){
close(socketfd);
close(fd[0]);
while(1){
printf("MAIN->while(1)\n");
// poslouchame zpravy
//if(waitForAnswer) {
receive(newSocket, buff) == 0;
parseRecvMess(buff);
//}
waitForAnswer =0;
if(strcmp(buff,":exit") == 0){
printf("Disconnected from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
break;
} else{
// send buff to parent
int i = findPlayerIndex();
memset(sbuff, '\0', size) ;
str str;
strcat(sbuff, "//:");
sprintf(str, "%d", i);
strcat(sbuff, str);
strcat(sbuff, ":");
strcat(sbuff, command);
strcat(sbuff, "\n");
write(fd[1], sbuff , strlen(sbuff)+1);
bzero(buff, sizeof(buff));
if (strncmp("roll", command, 4) == 0) {
//TODO
hod();
}
if (strncmp("none", command, 4) == 0) {
//TODO
}
strcpy(sbuff, "OK\n" );
write(newSocket, sbuff, strlen(sbuff));
bzero(buff, sizeof(buff));
bzero(sbuff, sizeof(sbuff));
}
}
}
close(fd[1]);
int nbytes = read(fd[0], buff, sizeof(buff));
printf("PARENT: buffer : %s\n",buff);
parseRecvMess(buff);
char *index1= (char *)malloc(sizeof(char)*10);
strcpy(index1, user);
int index = atoi(index1);
char *command1= (char *)malloc(sizeof(char)*10);
strcpy(command1, command);
//printf("PARENT - index:%d, command:%s\n", index, command );
printf("PARENT - index:%d, jmeno:%s, command:%s\n", index, players_array[index].name, command1 );
bzero(buff, sizeof(buff));
if (strncmp("room", command1, 4) == 0) {
// vlozit do mistnosti
printf("command = room\n");
command = strtok(command1," ");
command = strtok(NULL," "); // volba
printf("command(volba): + %s \n", command);
//int i = findPlayerIndex(); // find player in array based on user name
printf("player index: = %d \n", index);
//printPlayer(&players_array[i]);
volbaHry(&players_array[index], command, lobby);
//players_array[i].mist->pocet_hracu++;
printf("PARENT: array pocet hracu %d\n",players_array[index].mist->pocet_hracu);
printf("PARENT: lobby pocet hracu %d\n",lobby[0].pocet_hracu);
str str;
memset(sbuff, '\0', size);
//pokud v mistnosti jsou 2 hraci => zacina hra
if( players_array[index].mist->pocet_hracu == 2){
printf("Hra zacina ...\n");
hra(players_array[index].mist);
}
printMistnost(players_array[index].mist);
}
//players_array[index].mist = lobby[volba - 1];
// }
}
close(newSocket);
return 0;
}
and this is my receive() function:
int receive(int socket, char *buff){
int size = 256;
int reader = recv(socket, buff, size * sizeof(char), 0);
if (reader == -1) {
printf("BREAK reader == -1\n");
perror("recv()");
return(-1);
} else if (reader == 0) {
printf("BREAK reader == 0\n");
return(-2);
} else if(checkMessage(buff) == 0){
printf("ERROR: recieved message is not valid\n");
return(-3);
}
return 0;
}
if I'm not using waitForAnswer variable the program connects without any errors with the client, but at some points stops at the beginning of while waiting for another message.
You can also use ioctl() to check for data if the socket is set to non blocking
#include <sys/ioctl.h>
int status;
do{
ioctl(socketfd, FIONREAD, &status);
if( status > 0 ){
//packet waiting to be read
recv(socketfd, buff, size * sizeof(char), 0);
}
else{
// no data .. so do something else
}
} while (!must_stop);
Call recv with the nonblocking flag:
recv(socket, buff, size, MSG_DONTWAIT);
And the function will immediately return if there was no data to read.
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...\n\n");
if ((recvfrom(s1, msgBuffer, 1519, 0, (struct sockaddr *) &otherClient,
&slen)) == SOCKET_ERROR) {
printf("recvfrom() failed with error code : %d\n", WSAGetLastError());
continue;
}
//printf("Received packet from %s:%d\n", 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 : %d\n", 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: %s\n", packetData->data);
fclose(fptr);
if(packetData->fragNum == packetData->fragTotal){
receivingFile = 0;
}
} else {
printf("Received packet n. %d\n", packetData->fragNum);
printf("Packet data length: %d\n", packetData->len);
printf("Packet contains data: %s\n", packetData->data);
}
break;
}
case 'f': {
strcpy(fileName, packetData->data);
printf("Receiving file: %s\n", fileName);
printf("Receiving file: %s\n", 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: %d\n", 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 : %d\n", 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 : %d\n", 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 : %d\n", 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 again\n");
continue;
}
fseek(fl, 0, SEEK_END);
long fileLength = ftell(fl);
fclose(fl);
int numFragments = (fileLength - 1) / fragSize + 2;
printf("Number of fragments: %d\n", 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 : %d\n", 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 : %d\n", 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)] = '\0';
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 : %d\n", 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 null\n");
continue;
}
while ((c = fgetc(f2)) != EOF) {
msgBuffer[n++] = (char) c;
counter++;
if (counter == fragSize) {
n = 0;
counter = 0;
printf("Allocating fragment number: %d\n", fragNum);
PacketData *fragments2 = NULL;
fragments2 = (PacketData *) malloc(sizeof(PacketData));
if(fragments2 == NULL){
printf("Incorrect malloc\n");
break;
}
fragments2->data = (char *) malloc((fragSize+1) * sizeof(char));
if(fragments2->data == NULL){
printf("Incorrect malloc2\n");
break;
}
strncpy(fragments2->data, msgBuffer, fragSize);
printf("Copying data to fragment number: %d\n", fragNum);
fragments2->data[strlen(msgBuffer)] = '\0';
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: %d\n", 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 : %d\n", WSAGetLastError());
continue;
}
printf("Sent fragment number: %d\n", 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: %s\n", 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] = '\0';
return out;
}
PacketData *dataToPacket(char *data) { // convert received data into packet
printf("Data received: %s\n", 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] = '\0';
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: %d\n", strlen(message));
int fragCount = (strlen(message) - 1) / fragSize + 1;
if (fragCount == 0) {
fragCount++;
}
PacketData **fragments = (PacketData **) malloc((fragCount) * sizeof(PacketData *));
printf("Allocated %d fragments\n", 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] = '\0';
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: %d\n", 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;
I am working on a client server program , that uses select() calls to listen to multiple sockets. But my select call gets blocked, although I have a message in one of those sockets , select() call doesn't recognize it and it's still waits there indefinetly.
There are 2 entities in the program , a master and a client.
The master knows the number of clients it will handle and waits for the clients to connect to it. Once it receives a client acknowledgement, it stores its information. Once all the clients are connected, it then sends its neighboring client's information to every client so it can form a network. It is here, I use the select() to monitor many sockets,
master has a socket to every child tat is connected to it
client has 3 main sockets
s1-to speak with master
s2-child listens for connection on this socket
neighbour-the socket on which its neighbour wait for a connection.(i.e S2 in a neighbour)
p- the socket that is results of connection from its neighbour ( accept of s2 - returns ths)
I use select to listen to server, its own socket for incoming connections and once.
Initially my server sends a string "hello" to one of the client, which receives this message and passes it on to the neighbour, in this way when the string reaches back to the first child that has received this message from server , it passes it on to its neighbour. But all though all child are in select() waiting for an input. What could cause this ??
void main(int argc, char **argv) {
int s1, s2, n, server_port, sc1, sc2, rv, rc, left_peer_port;
int peer_port;
fd_set writefds, readfds;
struct timeval tv;
struct hostent *server_info, *child_info, *left_peer_info;
int start_flag = 0;
struct sockaddr_in server, peer, incoming;
char host_child[64];
char *left_host = malloc(1);
char *right_host = malloc(1);
char buf1[256];
char buf2[256];
server_port = atoi(argv[2]);
//speak to peer using this
s2 = socket(AF_INET, SOCK_STREAM, 0);
if (s2 < 0) {
perror("socket:");
exit(s2);
}
peer_port = server_port + 1;
gethostname(host_child, sizeof host_child);
child_info = gethostbyname(host_child);
if (child_info == NULL) {
fprintf(stderr, "%s: host not found (%s)\n", argv[0], host_child);
exit(1);
}
peer.sin_family = AF_INET;
memcpy(&peer.sin_addr, child_info->h_addr_list[0], child_info->h_length);
int changeport = 0;
do {
peer.sin_port = htons(peer_port);
rc = bind(s2, (struct sockaddr *) &peer, sizeof(peer));
if (rc < 0) {
//perror("bind:");
peer_port++;
changeport = 1;
//exit(rc);
} else {
changeport = 0;
}
} while (changeport == 1);
if (listen(s2, 100) == -1) {
perror("listen");
exit(3);
}
//Now talk to server
server_info = gethostbyname(argv[1]);
if (server_info == NULL) {
fprintf(stderr, "%s: host not found\n", argv[0]);
exit(1);
}
// pretend we've connected both to a server at this point
//speak to server using this
s1 = socket(AF_INET, SOCK_STREAM, 0);
if (s1 < 0) {
perror("socket:");
exit(s1);
}
server.sin_family = AF_INET;
server.sin_port = htons(server_port);
memcpy(&server.sin_addr, server_info->h_addr_list[0], server_info->h_length);
//To talk to the server
sc1 = connect(s1, (struct sockaddr *) &server, sizeof(server));
if (sc1 < 0) {
perror("connect:");
exit(sc1);
}
int send_len;
char *str = malloc(1);
sprintf(str, "%d", peer_port);
printf("\nport-here=%s\n", str);
send_len = send(s1, str, strlen(str), 0);
if (send_len != strlen(str)) {
perror("send");
exit(1);
}
int recv_len;
char buf[100];
int ref = 0;
int recv_stage = 0;
int start_id;
recv_len = recv(s1, buf, 34, 0);
if (recv_len < 0) {
perror("recv");
exit(1);
}
buf[recv_len] = '\0';
char *temp_port;
if (!strcmp("close", buf))
printf("%s", buf);
//break;
else {
char *temp_buffer = malloc(1);
char *id = malloc(100);
char *pp = malloc(1);
strcpy(temp_buffer, buf);
char *search = ":";
temp_port = strtok(temp_buffer, search);
strcpy(buf, temp_port);
printf("temp_name%s", temp_port);
temp_port = strtok(NULL, search);
strcpy(pp, temp_port);
printf("temp_port%s", temp_port);
temp_port = strtok(NULL, search);
strcpy(id, temp_port);
printf("id%s", temp_port);
strcpy(temp_port, pp);
printf("\nbuf=%s\n", buf);
printf("\nport=%s\n", temp_port);
printf("\nid=%s\n", id);
start_id = atoi(id);
}
//To send packet to its neighbour
left_peer_info = gethostbyname(buf);
printf("\nleft host=%s\n", buf);
if (left_peer_info == NULL) {
fprintf(stderr, "%s: host not found\n", left_host);
exit(1);
}
left_peer_port = atoi(temp_port);
int neighbour_socket;
struct hostent *neighbour_info;
struct sockaddr_in neighbour;
neighbour_socket = socket(AF_INET, SOCK_STREAM, 0);
if (neighbour_socket < 0) {
perror("socket:");
exit(neighbour_socket);
}
neighbour_info = left_peer_info;
neighbour.sin_family = AF_INET;
neighbour.sin_port = htons(left_peer_port);
memcpy(&neighbour.sin_addr, neighbour_info->h_addr_list[0], neighbour_info->h_length);
printf("\nconnected to port %d\n", left_peer_port);
//To talk to the neighbour
printf("\ncomes here\n");
//Listen on this socket connection for potato
int send_peer_len;
int nfds;
nfds = MAX(MAX(neighbour_socket, s2), s1);
// clear the set ahead of time
FD_ZERO(&writefds);
// add our descriptors to the set
FD_SET(neighbour_socket, &writefds);
FD_SET(s1, &writefds);
FD_SET(s2, &writefds);
//FD_SET(s2, &writefds);
FD_ZERO(&readfds);
FD_SET(neighbour_socket, &readfds);
FD_SET(s1, &readfds);
FD_SET(s2, &readfds);
//select()
// since we got s2 second, it's the "greater", so we use that for
// the n param in select()
//n = s1 + 1;
// wait until either socket has data ready to be recv()d (timeout 10.5 secs)
tv.tv_sec = 10;
tv.tv_usec = 500000;
int fds[3];
fds[0] = s1;
fds[1] = s2;
fds[2] = neighbour_socket;
int p = 0;
int p_flag = 0;
while (1) {
printf("\n nfds = %d , p = %d \n", nfds, p);
char buf_msg[64];
//This is where the error occurs //
rv = select(nfds, &readfds, NULL, NULL, 0);
//This is where the error occurs //
if (rv == -1) {
perror("select"); // error occurred in select()
} else if (rv == 0) {
printf("Timeout occurred! No data after 10.5 seconds.\n");
} else {
// one or both of the descriptors have data
//reading message from server
int select_fd;
for (select_fd = 0; select_fd <= nfds; select_fd++) {
if (FD_ISSET(select_fd, &readfds) != 0) {
if (select_fd == s1) {
recv_len = 0;
recv_len = recv(s1, buf_msg, 34, 0);
if (recv_len < 0) {
perror("recv");
exit(1);
}
buf_msg[recv_len] = '\0';
printf("\nreceived from server = %s\n", buf_msg);
//send to neighbour
int sc3;
sc3 = connect(neighbour_socket, (struct sockaddr *) &neighbour, sizeof(neighbour));
if (sc3 < 0) {
perror("connect:");
exit(sc3);
}
str = malloc(1);
strcpy(str, buf_msg);
send_len = send(neighbour_socket, str, strlen(str), 0);
printf("\n send - len - s1 - %d\n", send_len);
if (send_len != strlen(str)) {
perror("send");
exit(1);
}
start_flag = 1;
//FD_CLR(s1, &readfds);
printf("\ncrossed server\n");
} else if (select_fd == s2) {
int list_len = sizeof incoming;
printf("\ninside client\n");
printf("\nWaiting for accept in S2\n");
if (p_flag == 0) {
p_flag = 1;
p = accept(s2, (struct sockaddr *) &incoming, &list_len);
printf("\nConnection accepted in S2\n");
if (p < 0) {
perror("bind:");
exit(rc);
}
}
nfds = MAX(nfds, p);
recv_len = 0;
buf_msg[recv_len] = '\0';
recv_len = recv(p, buf_msg, 34, 0);
if (recv_len < 0) {
perror("recv");
exit(1);
}
buf_msg[recv_len] = '\0';
printf("\nreceived from client = %s\n", buf_msg);
//send to neighbour
//if(start_id!=1){
int sc3;
sc3 = connect(neighbour_socket, (struct sockaddr *) &neighbour, sizeof(neighbour));
if (sc3 < 0) {
perror("connect:");
//exit(sc3);
}
//}
str = malloc(1);
strcpy(str, buf_msg);
send_len = send(neighbour_socket, str, strlen(str), 0);
printf("\n send - len - s2 - %d\n", send_len);
if (send_len != strlen(str)) {
perror("send");
exit(1);
}
} else if (select_fd == neighbour_socket) {
printf("\ncomes in\n");
} else if (select_fd == p && p != 0) {
int list_len = sizeof incoming;
printf("\ninside p\n");
recv_len = 0;
buf_msg[recv_len] = '\0';
printf("\nwaiting at recv in P\n");
recv_len = recv(p, buf_msg, 34, 0);
printf("\ncrossed at recv in P\n");
if (recv_len < 0) {
perror("recv");
exit(1);
}
buf_msg[recv_len] = '\0';
printf("\nreceived from client = %s\n", buf_msg);
//send to neighbour
str = malloc(1);
strcpy(str, buf_msg);
send_len = send(neighbour_socket, str, strlen(str), 0);
printf("\n send - len - neighbour - %d\n", send_len);
if (send_len != strlen(str)) {
perror("send");
exit(1);
}
}
}
}
FD_ZERO(&readfds);
//FD_SET(neighbour_socket,&readfds);
FD_SET(s1, &readfds);
FD_SET(neighbour_socket, &readfds);
if (p_flag == 1) {
printf("\nsetting P\n");
FD_SET(p, &readfds);
FD_SET(s2, &readfds);
p_flag = 0;
} else {
printf("\nNot setting P\n");
FD_SET(s2, &readfds);
}
}
}
close(s1);
close(s2);
}
Thanks in advance.
The first parameter to select must be the maximum file descriptor plus one. As far as I can tell in that huge lump of code you posted, you forgot that "plus one".
I believe Mat has found the underlying problem. But I think there is a much larger problem here:
int send_len;
char *str=malloc(1);
sprintf(str,"%d",peer_port);
printf("\nport-here=%s\n",str);
You have corrupted your heap with your sprintf(3) call. Maybe it isn't important data you've overwritten, and maybe malloc(3) won't ever actually allocate one byte, but that is a bad assumption to make. You need to allocate at least six bytes for a port number: five for the digits in 65535 and one for the trailing ASCII NUL \0 byte.
buf[recv_len] = '\0';
char *temp_port;
//printf("\n-%s\n",buf);
if ( !strcmp("close", buf) )
printf("%s",buf);
//break;
else{
char *temp_buffer=malloc(1);
char *id=malloc(100);
char *pp=malloc(1);
strcpy(temp_buffer,buf);
In the preceding selection, you have stored a \0 into the end of buf, so you're presumably working with a string of some sort. But in a few lines, you allocate a single byte and then proceed to copy the contents of buf into that single byte. The ASCII NUL will use that byte entirely, leaving no space for the string you received. But strcpy(3) doesn't work that way -- it will copy the contents of buf, until that '\0' character, into the memory starting with your single byte. You've again destroyed your heap. But this time it can overwrite significantly more than five bytes -- and all under the control of the remote peer.
Heap overflows are extremely dangerous. I found over 350 references to exploitable bugs in programs that derive directly from heap overflows in an old archive I have from the Common Vulnerabilities and Exposures project.
Do not deploy this program on publicly-accessible machines until you have fixed these problems. It represents a significant security flaw. Find every instance of malloc(1) and replace it with the correct amount of memory that must be allocated. Once you've done this, please run your program with MALLOC_CHECK_=1 or under control of valgrind(1) to help you find further memory allocation problems.
Have you considered using poll() instead of select()? It's easier to debug and scales elegantly to however many you need.
For a few days I have been trying to run my server as a daemon process that runs continuously. Right now, my server closes the connection with the client and then closes itself. So I am able to send my packet once to the server, but when I try to send it again I get a segmentation fault error.
Also, even though I wrote the daemon process, I am not sure about its behavior and whether it is working or not.
Server Code:
#include <sys/socket.h>
#include <netinet/in.h>
#include "unistd.h"
#include <syslog.h>
#include <math.h>
#define MAXPROFILES 2
float Pearson(int mySum, int recSum, int multSum);
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, clilen;
struct sockaddr_in serv_addr, cli_addr;
unsigned char buf[1024];
int myDataBinary[500] = {0};
int myDataBinary2[500] = {0};
int recData[500] = {0};*/
int index1=0;
struct profile_t
{
unsigned char length;
unsigned char type;
unsigned char *data;
};
typedef struct profile_datagram_t
{
unsigned char *src;
unsigned char *dst;
unsigned char ver;
unsigned char n;
struct profile_t profiles[MAXPROFILES];
} header;
header outObj;
int j =0;
int i =0;
extern int daemon_proc; /* defined in error.c */
void daemon_init (const char *pname, int facility)
{
/* Our process ID and Session ID */
pid_t pid, sid;
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If we got a good PID, then
we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Change the current working directory */
if ((chdir("/")) < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Close out the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* Daemon-specific initialization goes here */
}
if (argc < 2) {
fprintf(stderr,"usage: %s port_number1",argv[0]);
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR DETECTED !!! Problem in opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR DETECTED !!! There was a problem in binding");
listen(sockfd, 10);
clilen = sizeof(cli_addr);
while (1){
printf("Server listening on port number %d...\n", serv_addr.sin_port);
newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR DETECTED !!! the connection request was not accepted");
int rc = read(newsockfd,buf,100);
if(rc < 0){
printf("error");
}
else {
printf("success %d",rc);
}
outObj.src = malloc(4);
outObj.dst = malloc(4);
// printf(pointer);
memcpy(outObj.src,buf+0,4);
memcpy(outObj.dst,buf+4,4);
memcpy(&outObj.ver,buf+8,1);
memcpy(&outObj.n,buf+9,1);
printf("\nSource IP = ");
for(int i=0;i<4;i++){
printf("%d ",outObj.src[i]);
}
printf("\nDestination IP = ");
for(int i=0;i<4;i++){
printf("%d ",outObj.dst[i]);
}
printf("\nVersion = %d",outObj.ver);
printf("\nNumber of messages = %d",outObj.n);
int k = 10;
for(i=0;i<outObj.n;i++){
memcpy(&outObj.profiles[i].length,buf+k,1);
memcpy(&outObj.profiles[i].type,buf+k+1,1);
outObj.profiles[i].data = malloc(outObj.profiles[i].length);
memcpy(outObj.profiles[i].data,buf+k+2,5);
k +=7;
}
for(int i=0;i<outObj.n;i++){
printf("\n------- Message %d --------",i+1);
printf("\nLength : %d",outObj.profiles[i].length);
printf("\nType : %d\n",outObj.profiles[i].type);
for(int j=0;j<5;j++){
printf(" Data[%d] : %d",j,outObj.profiles[i].data[j]);
}
}
float rho;
for(int i=0;i<outObj.n;i++){
printf("\n\n---------- Values for Data Profile %d ------------",i+1);
index1=0;
int sumRecievedData = 0;
int sumMyData = 0;
int sumMultpliedData = 0;
int my_data[10] = {0};// = {1,2,3,4,5};
int myDataBinary[500] = {0};
int recData[500] = {0};
if(i==0){
my_data[0] = 1;
my_data[1] = 3;
my_data[2] = 9;
my_data[3] = 10;
} else if(i==1){
my_data[0] = 1;
my_data[1] = 2;
my_data[2] = 3;
my_data[3] = 4;
my_data[4] = 5;
}
for(int i=0; i<sizeof(my_data)/sizeof(int);i++)
{
if(my_data[i] > 0){
index1 = my_data[i];
myDataBinary[index1] = 1;
//printf("my data %d = %d\n",index1,myDataBinary[index1]);
}
}
for (int j=0; j<outObj.profiles[i].length;j++) {
if(outObj.profiles[i].data[j] > 0){
index1 = outObj.profiles[i].data[j];
recData[index1] = 1;
//printf("rec data %d = %d\n",index1,recData[index1]);
}
}
for(int i=0;i<500;i++){
sumRecievedData += recData[i];
sumMyData += myDataBinary[i];
sumMultpliedData += recData[i] * myDataBinary[i];
}
printf("\nrecSum = %d, \nmySum = %d, \nmultSum = %d\n",sumRecievedData,sumMyData,sumMultpliedData);
rho = Pearson(sumMyData,sumRecievedData,sumMultpliedData);
printf("\nPearson Coefficient for Data Profile %d= %f\n",i+1,rho);
}
return 0;
}
//exit(EXIT_SUCCESS);
}
float Pearson(int mySum, int recSum, int multSum)
{
float Cov =0;
float sdMyData = 0;
float sdRecievedData =0;
float rho;
int n = 500;
Cov = (1.0/(n-1))*(multSum - (1.0/n)*mySum*recSum);
sdMyData = sqrt((1.0/(n-1))*(mySum - (1.0/n)*mySum*mySum));
sdRecievedData = sqrt((1.0/(n-1))*(recSum - (1.0/n)*recSum*recSum));
printf("\nCovariance = %f, \nVarianceMyData = %f, \nVarianceRecData = %f",Cov,sdMyData,sdRecievedData);
if (sdMyData == 0.0 || sdRecievedData == 0.0){
rho = 0.0;
}else{
rho = Cov/(sdMyData*sdRecievedData);
}
return(rho);
}
The server does return(0); at the bottom of the supposedly infinite loop, thus exiting from main() and terminating.
As noted in a comment, your code includes a nested function daemon_init() which is never called. Nested functions are a GCC-only feature; you should avoid using them. If you do call it, the server is going to have problems because it closes stdout and stderr but your code then tries to write to the now closed files.
Without the client code, it is very far from clear what information is being sent over the wire. There is one read() call:
int rc = read(newsockfd,buf,100);
That should be using sizeof(buf) in place of 100; and it is wasteful to use char buf[1024]; when you only use 100 bytes. You check that you got some data; you do not check that you got all the data you expect. You might, therefore, be reading uninitialized data.
There are numerous other similar problems in the code, especially with constants used somewhat inappropriately. As also noted in a comment, the code is not properly modularized.
The code does not seem to respond to the client; its outputs only go to its standard output (or error).
This code compiles reasonably cleanly, but still doesn't call daemon_init() for the reasons mentioned earlier.
#include <errno.h>
#include <math.h>
#include <netinet/in.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h> /* exit() */
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h> /* umask() */
#include <syslog.h>
#include <unistd.h>
#define MAXPROFILES 2
static void error(const char *fmt, ...)
{
va_list args;
int errnum = errno;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, ": %d %s\n", errnum, strerror(errnum));
exit(1);
}
static float Pearson(int mySum, int recSum, int multSum);
static void daemon_init(void)
{
/* Our process ID and Session ID */
pid_t pid, sid;
/* Fork off the parent process */
pid = fork();
if (pid < 0)
error("failed to fork");
/* If we got a good PID, then
we can exit the parent process. */
if (pid > 0)
exit(EXIT_SUCCESS);
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0)
error("failed to set session ID");
/* Change the current working directory */
if ((chdir("/")) < 0)
error("failed to chdir to root");
/* Close out the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* Daemon-specific initialization goes here */
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
unsigned char buf[1024];
struct profile_t
{
unsigned char length;
unsigned char type;
unsigned char *data;
};
typedef struct profile_datagram_t
{
unsigned char *src;
unsigned char *dst;
unsigned char ver;
unsigned char n;
struct profile_t profiles[MAXPROFILES];
} header;
header outObj;
if (argc != 2)
error("usage: %s port", argv[0]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR DETECTED !!! Problem in opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR DETECTED !!! There was a problem in binding");
listen(sockfd, 10);
while (1)
{
clilen = sizeof(cli_addr);
printf("Server listening on port number %d...\n", serv_addr.sin_port);
newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR DETECTED !!! the connection request was not accepted");
int rc = read(newsockfd,buf,100);
if (rc < 0)
error("read error");
else
printf("read: success %d", rc);
outObj.src = malloc(4);
outObj.dst = malloc(4);
// printf(pointer);
memcpy(outObj.src,buf+0,4);
memcpy(outObj.dst,buf+4,4);
memcpy(&outObj.ver,buf+8,1);
memcpy(&outObj.n,buf+9,1);
printf("\nSource IP = ");
for (int i=0;i<4;i++)
printf("%d ",outObj.src[i]);
printf("\nDestination IP = ");
for (int i=0;i<4;i++)
printf("%d ",outObj.dst[i]);
printf("\nVersion = %d",outObj.ver);
printf("\nNumber of messages = %d",outObj.n);
int k = 10;
for (int i=0;i<outObj.n;i++)
{
memcpy(&outObj.profiles[i].length,buf+k,1);
memcpy(&outObj.profiles[i].type,buf+k+1,1);
outObj.profiles[i].data = malloc(outObj.profiles[i].length);
memcpy(outObj.profiles[i].data,buf+k+2,5);
k +=7;
}
for (int i=0;i<outObj.n;i++)
{
printf("\n------- Message %d --------",i+1);
printf("\nLength : %d",outObj.profiles[i].length);
printf("\nType : %d\n",outObj.profiles[i].type);
for (int j=0;j<5;j++)
{
printf(" Data[%d] : %d",j,outObj.profiles[i].data[j]);
}
}
for (int i=0;i<outObj.n;i++)
{
printf("\n\n---------- Values for Data Profile %d ------------",i+1);
int index1=0;
int sumReceivedData = 0;
int sumMyData = 0;
int sumMultpliedData = 0;
int my_data[10] = {0};
int myDataBinary[500] = {0};
int recData[500] = {0};
if (i==0)
{
my_data[0] = 1;
my_data[1] = 3;
my_data[2] = 9;
my_data[3] = 10;
}
else if (i==1)
{
my_data[0] = 1;
my_data[1] = 2;
my_data[2] = 3;
my_data[3] = 4;
my_data[4] = 5;
}
for (int i=0; i<sizeof(my_data)/sizeof(int);i++)
{
if (my_data[i] > 0)
{
index1 = my_data[i];
myDataBinary[index1] = 1;
//printf("my data %d = %d\n",index1,myDataBinary[index1]);
}
}
for (int j=0; j<outObj.profiles[i].length;j++)
{
if (outObj.profiles[i].data[j] > 0)
{
index1 = outObj.profiles[i].data[j];
recData[index1] = 1;
//printf("rec data %d = %d\n",index1,recData[index1]);
}
}
for (int i=0;i<500;i++)
{
sumReceivedData += recData[i];
sumMyData += myDataBinary[i];
sumMultpliedData += recData[i] * myDataBinary[i];
}
printf("\nrecSum = %d, \nmySum = %d, \nmultSum = %d\n",sumReceivedData,sumMyData,sumMultpliedData);
float rho = Pearson(sumMyData,sumReceivedData,sumMultpliedData);
printf("\nPearson Coefficient for Data Profile %d= %f\n",i+1,rho);
}
return 0;
}
//exit(EXIT_SUCCESS);
}
static float Pearson(int mySum, int recSum, int multSum)
{
float Cov =0;
float sdMyData = 0;
float sdReceivedData =0;
float rho;
int n = 500;
Cov = (1.0/(n-1))*(multSum - (1.0/n)*mySum*recSum);
sdMyData = sqrt((1.0/(n-1))*(mySum - (1.0/n)*mySum*mySum));
sdReceivedData = sqrt((1.0/(n-1))*(recSum - (1.0/n)*recSum*recSum));
printf("Covariance = %f\n",Cov);
printf("VarianceMyData = %f\n",sdMyData);
printf("VarianceRecData = %f\n",sdReceivedData);
if (sdMyData == 0.0 || sdReceivedData == 0.0)
rho = 0.0;
else
rho = Cov/(sdMyData*sdReceivedData);
return(rho);
}
It still needs a lot of work.