Winsocket server. File opening issue - c

I have created simple TCP server using winsock2.h library. It translates english words into lithuanian for clients. I recieve query from client like this:
int MAXRECV = 100;
char *buffer;
buffer = (char*) malloc((MAXRECV + 1) * sizeof(char));
valread = recv(new_socket, buffer, MAXRECV, 0);
buffer[valread] = '\0';
After that, I want to open a dictionary and find that word translation in a file. Here is a function call and function itself.
char *lithuanianWord;
lithuanianWord = (char*) malloc((MAXWORDSIZE + 1) * sizeof(char));
if (findTranslation(buffer, &lithuanianWord)) {
send(new_socket, lithuanianWord, strlen(lithuanianWord), 0);
} else {
lithuanianWord = "Translation not found";
send(new_socket, lithuanianWord, strlen(lithuanianWord), 0);
}
int findTranslation (char* word, char** lithuanianWord) {
FILE *fp;
int translationFound = 0;
const char englishWord[50];
char buffer[255];
fp = fopen("*\\dictionary.txt","r");
while((fgets(buffer,255,fp)) != NULL) {
sscanf(buffer,"%s%s", englishWord, lithuanianWord);
if(strcmp(englishWord, word)==0 ) {
translationFound = 1;
break;
}
}
fclose(fp);
return translationFound;
}
Code compiles and runs perfectly. The problem is that txt file does not open and answer is always "Translation not found". This function works fine when stand alone. Path is full and the same, I just shortened it.
Error I get: No such file or directory. Both client and server are runing on the same hardware.
Update: full server code.
#include<io.h>
#include<stdio.h>
#include<winsock2.h>
#include<string.h>
int findTranslation (char* word, char** translation);
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET master , new_socket, client_socket[30], s;
struct sockaddr_in server , address;
int max_clients = 30, activity, addrlen, i, valread;
char *lithuanianWord;
int MAXWORDSIZE = 100;
lithuanianWord = (char*) malloc((MAXWORDSIZE + 1) * sizeof(char));
//size of our receive buffer, this is string length.
int MAXRECV = 100;
//set of socket descriptors
fd_set readfds;
//1 extra for null character, string termination
char *buffer, *message;
buffer = (char*) malloc((MAXRECV + 1) * sizeof(char));
for(i = 0 ; i < 30;i++)
{
client_socket[i] = 0;
}
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
exit(EXIT_FAILURE);
}
printf("Initialised.\n");
//Create a socket
if((master = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
//Bind
if( bind(master ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
}
puts("Bind done");
listen(master , 3);
puts("Waiting for incoming connections...");
addrlen = sizeof(struct sockaddr_in);
for(;;)
{
//clear the socket fd set
FD_ZERO(&readfds);
//add master socket to fd set
FD_SET(master, &readfds);
//add child sockets to fd set
for ( i = 0 ; i < max_clients ; i++)
{
s = client_socket[i];
if(s > 0)
{
FD_SET( s , &readfds);
}
}
//wait for an activity on any of the sockets, timeout is NULL , so wait indefinitely
activity = select( 0 , &readfds , NULL , NULL , NULL);
if ( activity == SOCKET_ERROR )
{
printf("select call failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
//If something happened on the master socket , then its an incoming connection
if (FD_ISSET(master , &readfds))
{
if ((new_socket = accept(master , (struct sockaddr *)&address, (int *)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
//inform user of socket number - used in send and receive commands
printf("New connection , socket fd is %d , ip is : %s , port : %d \n" , new_socket , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
//add new socket to array of sockets
for (i = 0; i < max_clients; i++)
{
if (client_socket[i] == 0)
{
client_socket[i] = new_socket;
printf("Adding to list of sockets at index %d \n" , i);
break;
}
}
valread = recv(new_socket, buffer, MAXRECV, 0);
buffer[valread] = '\0';
printf("%s:%d - %s \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port), buffer);
int i = findTranslation(buffer, &lithuanianWord);
if (i == 1) {
send(new_socket, lithuanianWord, strlen(lithuanianWord), 0);
} else {
lithuanianWord = "Vertimas nerastas";
send(new_socket, lithuanianWord, strlen(lithuanianWord), 0);
}
}
//else its some IO operation on some other socket
for (i = 0; i < max_clients; i++)
{
s = client_socket[i];
//if client present in read sockets
if (FD_ISSET( s , &readfds))
{
//get details of the client
getpeername(s , (struct sockaddr*)&address , (int*)&addrlen);
//Check if it was for closing , and also read the incoming message
//recv does not place a null terminator at the end of the string (whilst printf %s assumes there is one).
valread = recv( s , buffer, MAXRECV, 0);
buffer[valread] = '\0';
if( valread == SOCKET_ERROR)
{
int error_code = WSAGetLastError();
if(error_code == WSAECONNRESET)
{
//Somebody disconnected , get his details and print
printf("Host disconnected unexpectedly , ip %s , port %d \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
closesocket( s );
client_socket[i] = 0;
}
else
{
printf("recv failed with error code : %d" , error_code);
}
}
if ( valread == 0)
{
//Somebody disconnected , get his details and print
printf("Host disconnected , ip %s , port %d \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
closesocket( s );
client_socket[i] = 0;
}
//Echo back the message that came in
else
{
i = findTranslation(buffer, &lithuanianWord);
if (i == 1) {
send(s, lithuanianWord, strlen(lithuanianWord), 0);
} else {
lithuanianWord = "Vertimas nerastas";
send(s, lithuanianWord, strlen(lithuanianWord), 0);
}
}
}
}
}
closesocket(s);
WSACleanup();
return 0;
}
int findTranslation (char* word, char** lithuanianWord) {
FILE *fp;
int translationFound = 0;
const char englishWord[50];
char buffer[255];
fp = fopen("C:\\Users\\Martynas\\Documents\\Programų_sistemos\\IV semestras\\Tinklai\\async\\dictionary.txt","r");
if (fp == NULL) {
perror("Error");
}
while((fgets(buffer,255,fp)) != NULL) {
sscanf(buffer,"%s%s", englishWord, lithuanianWord);
if(strcmp(englishWord, word)==0 ) {
translationFound = 1;
break;
}
}
fclose(fp);
return translationFound;
}

Related

Vigenère cipher, Issue in C

I am working on C program in vigenere ciphere in client and Server socket programming.
My Client End file :
#include<stdio.h>
#include<string.h>
#include<stdio.h> //printf
#include<string.h> //strlen
#include<sys/socket.h> //socket
#include<arpa/inet.h> //inet_addr
int main(int argc , char *argv[])
{
int sock,i,j,msgLen,keyLen;
struct sockaddr_in server;
char message[1000] , server_reply[2000],ch,key[10],newKey[msgLen], encryptedMsg[msgLen];
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 8888 );
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
//keep communicating with server
while(1)
{
printf("Enter a message to encrypt :");
scanf("%s",message);
printf("enter key to be added :");
scanf("%s",key);
msgLen = strlen(message);
keyLen = strlen(key);
//generating new key
for(i = 0, j = 0; i < msgLen; ++i, ++j){
if(j == keyLen)
j = 0;
newKey[i] = key[j];
}
newKey[i] = '\0';
printf("\nNew Generated Key: %s", newKey);
//encryption
for(i = 0; i < msgLen; ++i)
encryptedMsg[i] = ((message[i] + newKey[i]) % 26) + 'A';
encryptedMsg[i] = '\0';
printf("\nEncrypted Message: %s\n", encryptedMsg);
// puts("connected");
//Send some data
if( send(sock , encryptedMsg , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
}
close(sock);
return 0;
}
And Here is the Server File.
#include<stdio.h>
#include<string.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h> //write
int main(int argc , char *argv[])
{
int socket_desc , client_sock , c , read_size,i,j,msgLen,keyLen;
struct sockaddr_in server , client;
char client_message[2000],key[10],ch,newKey[msgLen],decryptedMsg[msgLen];
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
//accept connection from an incoming client
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
puts("Connection accepted");
//Receive a message from client
while( (read_size = recv(client_sock , client_message , 2000 , 0)) > 0 )
{
printf("encrypted message from client :");
puts(client_message);
printf("enter key to be subtract :");
scanf("%s",key);
msgLen = strlen(client_message);keyLen = strlen(key);
//generating new key
for(i = 0, j = 0; i < msgLen; ++i, ++j){
if(j == keyLen)
j = 0;
newKey[i] = key[j];
}
newKey[i] = '\0';
printf("New Generated Key: %s", newKey);
//decryption
for(i = 0; i < msgLen; ++i)
decryptedMsg[i] = (((client_message[i] - newKey[i]) + 26) % 26) + 'A';
decryptedMsg[i] = '\0';
printf("Decrypted Message: %s", decryptedMsg);
}
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
return 0;
}
When we send message from client end to server end it transfers the message to server end and when the key is entered to the server end nothing is happening.
Can anybody help ?
Both your programs initialize the newKey[] array with an undefined length:
int msgLen; // Value of msgLen is undefined
char newKey[msgLen]; // How big is newKey[]???
As always, this sort of problem could be identified by taking some simple steps:
Get your compiler to report as many problems as possible
Add -Wall (or better still, -Wall -Werror) to the command line arguments when compiling your code. This will inform you about potential errors in your code.
Learn how to use a debugger
Tools like gdb can often help you identify and fix problems much faster than posting code at Stack Overflow.

The result does not come from the correct branch

I implemented a client server application in C, I created the admin client with different options, GET_NO_CLIENTS return number of clients connected, GET_CLIENTS must to return the clients id. Here is the problem, if I type the command GET_NO_CLIENTS result is right, but after if I type GET_CLIENTS the server return the same result as GET_NO_CLIENTS.
Here is my code for client:
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
int main(int argc, char *argv[]) {
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
/* Create a socket point */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
exit(1);
}
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
/* Now connect to the server */
if (connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
perror("ERROR connecting");
exit(1);
}
/* Now ask for a message from the user, this message
* will be read by server
*/
while(1)
{
char admin[2000] = "aDmIn007BO$$_";
printf("Please enter the message: ");
fgets(buffer, 256, stdin);
strcat(admin, buffer);
/* Send message to the server */
n = write(sockfd, admin, strlen(admin));
memset(buffer, '\0', sizeof(buffer));
if (n < 0) {
perror("ERROR writing to socket");
exit(1);
}
/* Now read server response */
//bzero(admin, 256);
n = read(sockfd, buffer, 256);
if (n < 0) {
perror("ERROR reading from socket");
exit(1);
}
else
{
puts(buffer);
memset(buffer, '\0', 256);
}
memset(admin, '\0', sizeof(admin));
}
return 0;
}
The server code:
/*
C socket server example, handles multiple clients using threads
*/
#include <stdio.h>
#include <string.h> //strlen
#include <stdlib.h> //strlen
#include <sys/socket.h>
#include <arpa/inet.h> //inet_addr
#include <unistd.h> //write
#include <pthread.h> //for threading , link with lpthread
//the thread function
void *connection_handler(void *);
pthread_t tid;
int count_conn = 0, nr_admin = 0;
int clients_id[50];
int main(int argc , char *argv[])
{
int socket_desc , client_sock , c , *new_sock;
struct sockaddr_in server , client;
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
// printf("!!!!!!!%s", server.sin_addr.s_addr);
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
{
puts("Connection accepted");
count_conn++;
pthread_t sniffer_thread;
new_sock = malloc(1);
*new_sock = client_sock;
if( pthread_create( &sniffer_thread , NULL , connection_handler , (void*) new_sock) < 0)
{
perror("could not create thread");
return 1;
}
//Now join the thread , so that we dont terminate before the thread
//pthread_join( sniffer_thread , NULL);
puts("Handler assigned");
}
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
return 0;
}
/*
* This will handle connection for each client
* */
void *connection_handler(void *socket_desc)
{
//Get the socket descriptor
int sock = *(int*)socket_desc;
int connfd = 0;
int read_size;
int err;
int i = 0, j = 0;
char *message , client_message[2000], file_name[2000], send_buffer[130000], command[200];
int kk = 0;
//Receive a message from client
while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
{
clients_id[kk] = sock;
//Send the message back to client
if(strncmp(client_message, "GET_FILE ", 8) == 0)
{
for(i = 9; i < strlen(client_message); i++){
file_name[j] = client_message[i];
j++;
}
printf("Connection accepted and id: %d\n", sock);
printf("Connected to Client: %s:%d\n", "127.0.0.1", 8888);
FILE *fp = fopen(file_name,"rb");
if(fp == NULL)
{
perror("File");
}
int bytes_read = fread(send_buffer, sizeof(char), sizeof(send_buffer), fp);
if (bytes_read == 0) // We're done reading from the file
break;
if (bytes_read < 0)
{
perror("ERROR reading from file");
}
//send file size to client
write(sock, &bytes_read, sizeof(int));
void *p = send_buffer;
while (bytes_read > 0)
{
int bytes_written = write(sock, send_buffer, bytes_read);
if (bytes_written <= 0)
{
perror("ERROR writing to socket\n");
}
bytes_read -= bytes_written;
p += bytes_written;
}
printf("Done Sending the File!\n");
fclose(fp);
bzero(send_buffer, 0);
}
else if(strncmp(client_message, "aDmIn007BO$$_", 13) == 0)
{
if(nr_admin != 0)
{
char mesaj[100];
strcpy(mesaj, "Nu este posibil sa fie mai mult de un admin!");
write(sock, mesaj, strlen(mesaj));
}
else
{
nr_admin++;
for(i = 13; i < strlen(client_message); i++)
{
command[j] = client_message[i];
j++;
}
if(strncmp(command, "GET_NO_CLIENTS", 14) == 0)
{
char str1[15];
sprintf(str1, "%d", count_conn);
write(sock , str1, sizeof(char));
memset(str1, '\0', sizeof(str1));
}
else if(strncmp(command, "GET_CLIENTS", 11) == 0)
{
char str[15];
int i = 0;
for(i = 0; i < strlen(clients_id); i++)
{
sprintf(str[i], "%d", clients_id[i]);
puts(str[i]);
}
write(sock, str, strlen(str));
memset(str, '\0', sizeof(str));
}
nr_admin--;
}
}
else
{
write(sock , client_message , strlen(client_message));
}
memset(client_message, '\0', sizeof(client_message));
memset(file_name, '\0', sizeof(file_name));
kk++;
}
if(read_size == 0)
{
puts("Client disconnected");
count_conn--;
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
//Free the socket pointer
free(socket_desc);
return 0;
}
Thanks for your help!
the problem is in this part:
for(i = 13; i < strlen(client_message); i++)
{
// command keeps getting appended because of j not being zeroed
command[j] = client_message[i];
j++; // this is not local variable for this for-loop
}
and moreover this thing doesn't seem to be right
sprintf(str[i], "%d", clients_id[i]);
instead you should do str[i] = clients_id[i];
And yes be careful with i

Why the content of file is not send?

I tried to implement a client and server in C using TCP/IP for send message and file using sockets. The message is send but content of file not working. I want to send a file from server to client, in client the file was created but the content of file from server It is not transmitted to the client.
In client waiting the message, if message contain "GET_FILE a.txt" the server sent the file a.txt to client if you enter other text this is a simple message.
So, if you run the client and type the message "GET_FILE nameOfFile" server need to return this file, and if you type the other message server need to return message tasted.
This is my server code:
#include <stdio.h>
#include <string.h> //strlen
#include <stdlib.h> //strlen
#include <sys/socket.h>
#include <arpa/inet.h> //inet_addr
#include <unistd.h> //write
#include <pthread.h> //for threading , link with lpthread
//the thread function
void *connection_handler(void *);
void *SendFileToClient(int*);
pthread_t tid;
int main(int argc , char *argv[])
{
int socket_desc , client_sock , c , *new_sock;
struct sockaddr_in server , client;
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
// printf("!!!!!!!%s", server.sin_addr.s_addr);
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
{
puts("Connection accepted");
pthread_t sniffer_thread;
new_sock = malloc(1);
*new_sock = client_sock;
if( pthread_create( &sniffer_thread , NULL , connection_handler , (void*) new_sock) < 0)
{
perror("could not create thread");
return 1;
}
//Now join the thread , so that we dont terminate before the thread
//pthread_join( sniffer_thread , NULL);
puts("Handler assigned");
}
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
return 0;
}
/*
* This will handle connection for each client
* */
void *connection_handler(void *socket_desc)
{
//Get the socket descriptor
int sock = *(int*)socket_desc;
int read_size;
int err;
int i = 0, j = 0;
char *message , client_message[2000], file_name[2000];
//Receive a message from client
while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
{
//Send the message back to client
if(strncmp(client_message, "GET_FILE ", 8) == 0)
{
for(i = 9; i < strlen(client_message); i++){
file_name[j] = client_message[i];
j++;
}
err = pthread_create(&tid, NULL, &SendFileToClient, &file_name);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
}
else
{
write(sock , client_message , strlen(client_message));
}
}
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
//Free the socket pointer
free(socket_desc);
return 0;
}
void* SendFileToClient(int* file_name){
int connfd = (int)*file_name;
printf("Connection accepted and id: %d\n",connfd);
printf("Connected to Client: %s:%d\n", "127.0.0.1", 8888);
//write(connfd, file_name,256);
FILE *fp = fopen(file_name,"rb");
if(fp==NULL)
{
printf("File opern error");
return 1;
}
/* Read data from file and send it */
while(1)
{
/* First read file in chunks of 256 bytes */
unsigned char buff[1024] = {0};
int nread = fread(buff, 1, 1024, fp);
//printf("Bytes read %d \n", nread);
/* If read was success, send data. */
if(nread > 0)
{
//printf("Sending \n");
write(connfd, buff, nread);
}
if (nread < 1024)
{
if (feof(fp))
{
printf("End of file\n");
printf("File transfer completed for id: %d\n", connfd);
}
if (ferror(fp)){
printf("Error reading\n");
break;
}
}
printf("Closing Connection for id: %d\n", connfd);
close(connfd);
shutdown(connfd, SHUT_WR);
sleep(2);
}
}
This is the client code:
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#include <stdio.h> //printf
#include <string.h> //strlen
#include <sys/socket.h> //socket
#include <arpa/inet.h> //inet_addr
void gotoxy(int x,int y)
{
printf("%c[%d;%df",0x1B,y,x);
}
int main(int argc , char *argv[])
{
int sock;
struct sockaddr_in server;
char message[1000] , server_reply[2000];
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 8888 );
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
//keep communicating with server
while(1)
{
char file_name[2000];
int i = 0, j = 0;
printf("Enter message : ");
//scanf("%s" , message);
gets(message);
//puts(message);
//printf("%d", strncmp(message, "GET_FILE ", 9) );
if(strncmp(message, "GET_FILE ", 8) == 0)
{
//Send some data
if( send(sock , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
for(i = 9; i < strlen(message); i++){
file_name[j] = message[i];
j++;
}
/* Create file where data will be stored */
FILE *fp;
int bytesReceived = 0;
char recvBuff[1024];
puts(file_name);
puts("Receiving file...");
fp = fopen(file_name, "ab");
if(NULL == fp)
{
printf("Error opening file");
return 1;
}
long double sz = 1;
/* Receive data in chunks of 256 bytes */
while((bytesReceived = read(sock, recvBuff, 1024)) > 0)
{
printf("%d", bytesReceived);
sz++;
gotoxy(0,4);
//printf("Received: %lf Mb",(sz/1024));
fflush(stdout);
// recvBuff[n] = 0;
fwrite(recvBuff, 1, bytesReceived, fp);
// printf("%s \n", recvBuff);
}
if(bytesReceived < 0)
{
printf("\n Read Error \n");
}
printf("\nFile OK....Completed\n");
}
else
{
//Send some data
if( send(sock , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
//Receive a reply from the server
if( recv(sock , server_reply , 2000 , 0) < 0)
{
puts("recv failed");
break;
}
puts("Server reply :");
puts(server_reply);
}
}
close(sock);
return 0;
}
Thank you very much for your help!
UPDATE!!!
I updated the code for server, but now I have a error message from server: "
Error reading
recv failed: Bad file descriptor
"
The client code it's the same, the server code now is:
#include <stdio.h>
#include <string.h> //strlen
#include <stdlib.h> //strlen
#include <sys/socket.h>
#include <arpa/inet.h> //inet_addr
#include <unistd.h> //write
#include <pthread.h> //for threading , link with lpthread
//the thread function
void *connection_handler(void *);
pthread_t tid;
int main(int argc , char *argv[])
{
int socket_desc , client_sock , c , *new_sock;
struct sockaddr_in server , client;
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
// printf("!!!!!!!%s", server.sin_addr.s_addr);
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
{
puts("Connection accepted");
pthread_t sniffer_thread;
new_sock = malloc(1);
*new_sock = client_sock;
if( pthread_create( &sniffer_thread , NULL , connection_handler , (void*) new_sock) < 0)
{
perror("could not create thread");
return 1;
}
//Now join the thread , so that we dont terminate before the thread
//pthread_join( sniffer_thread , NULL);
puts("Handler assigned");
}
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
return 0;
}
/*
* This will handle connection for each client
* */
void *connection_handler(void *socket_desc)
{
//Get the socket descriptor
int sock = *(int*)socket_desc;
int connfd = 0;
int read_size;
int err;
int i = 0, j = 0;
char *message , client_message[2000], file_name[2000];
//Receive a message from client
while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
{
//Send the message back to client
if(strncmp(client_message, "GET_FILE ", 8) == 0)
{
for(i = 9; i < strlen(client_message); i++){
file_name[j] = client_message[i];
j++;
}
printf("Connection accepted and id: %d\n", sock);
printf("Connected to Client: %s:%d\n", "127.0.0.1", 8888);
FILE *fp = fopen(file_name,"rb");
if(fp==NULL)
{
printf("File opern error");
return 1;
}
/* Read data from file and send it */
while(1)
{
/* First read file in chunks of 256 bytes */
unsigned char buff[1024] = {0};
int nread = fread(buff, 1, 1024, fp);
//printf("Bytes read %d \n", nread);
/* If read was success, send data. */
if(nread > 0)
{
//printf("Sending \n");
write(sock, buff, nread);
}
if (nread < 1024)
{
if (feof(fp))
{
printf("End of file\n");
printf("File transfer completed for id: %d\n", sock);
}
if (ferror(fp)){
printf("Error reading\n");
break;
}
}
printf("Closing Connection for id: %d\n", sock);
close(sock);
fclose(fp);
shutdown(sock, SHUT_WR);
}
}
else
{
write(sock , client_message , strlen(client_message));
}
}
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
//Free the socket pointer
free(socket_desc);
return 0;
}

TCP Server Crash

I am just wondering why this crashes when a client connects?? Its supposed to be a simple TCP server that when the client connects and sends a string, the server responds with the number of A's in the string. The server crashes as soon as the client types a letter in.
#include<io.h>
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s , new_socket, master;
struct sockaddr_in server , address;
int c, valread;
char *message = "Welcome to Marshall's TCP Server!!";
int MAXRECV = 1024;
char *buffer;
char AmmtA = 'a';
char AmmtB = 'A';
int count = 0, x;
fd_set readfds;
buffer = (char*) malloc((MAXRECV + 1) * sizeof(char));
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 9000 );
//Bind
if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
puts("Bind done");
//Listen to incoming connections
listen(s , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while( (new_socket = accept(s , (struct sockaddr *)&address, &c)) != INVALID_SOCKET )
{
puts("Connection accepted");
send(new_socket , message , strlen(message) , 0);
valread = recv( new_socket , buffer, MAXRECV, 0);
if( valread == SOCKET_ERROR)
{
int error_code = WSAGetLastError();
if(error_code == WSAECONNRESET)
{
//Somebody disconnected , get his details and print
printf("Host disconnected unexpectedly , ip %s , port %d \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
closesocket( s );
}
else
{
printf("recv failed with error code : %d" , error_code);
}
}
if ( valread == 0)
{
//Somebody disconnected , get his details and print
printf("Host disconnected , ip %s , port %d \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
closesocket( s );
}
else
{
for (x = 0; buffer[x] != '\0'; x++) {
if (buffer[x] == AmmtA || buffer[x] == AmmtB)
count++;
}
char feedback[150];
sprintf(feedback, "There is %d A's in your string", count);
feedback[MAXRECV] = '\0';
printf("%s:%d - %s \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port), buffer);
send( s , feedback , MAXRECV , 0 );
}
free(buffer);
}
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d" , WSAGetLastError());
return 1;
}
closesocket(s);
WSACleanup();
return 0;
}
10057 - WSAENOTCONN - Socket is not connected.
The send call is correct and it uses new_socket. But the recv call uses socket/sd "s". The recv call should also use new_socket.
The error 10057 is returned because s is only bound to the local end point and not connected with the remote end whereas the new socket returned by the accept connected to the remote end.
for (x = 0; buffer[x] != '\0'; x++) {
if (buffer[x] == AmmtA || buffer[x] == AmmtB)
count++;
}
Why are you comparing buffer[x] to 0. There's no special reason any particular entry in the buffer should be zero, and this can easily read off the end of the buffer. Perhaps you think buffer contains a string. But it doesn't. It contains whatever you read from the socket, and it has no special format or terminator.
Fortunately, you do know the number of bytes you read. You stored that in valread, so you want:
for (x = 0; x < valread; x++) {

Implementation of custom message logger for windows : reports 10049 when ntwk cable unplugged

Trying to develop a simple/small syslog server for windows.
This implementation is just to store LOGS in the same machine from 2 other processes of same machine.
Wanted this to be similar to LINUX implementation.Started to use UDP DATAGRAM to send data between processes.
It is working as expected. However, it has been noticed that when NETWORK cable is unplugged the messages are not reaching to the server from client process application.
The client process reports 10049 error (When network cable is unplugged)
Request some guidance how to make this work between local process. Since, all my process run in local machine.
SERVER END LISTEN CODE:
int main(int argc,char *argv[])
{
SOCKET s;
FILE *fp;
struct sockaddr_in server, si_other;
int slen , recv_len;
char buf[BUFLEN];
WSADATA wsa;
struct stat sts;
char fileNameWithPath[512]={'\0'};
int status;
printf("ARGC %d\n",argc);
char a[10];
strcpy(logBasePath,"C:\\log\\");
if(argc == 1)
{
//parseSyslogConfiguration();
if (loggingLevel > 4)
loggingLevel=DEBUG_LOG;
}
else
{
memset(a,0,sizeof(a));
strncpy(a,argv[1],1);
int isnum=isdigit(a[0]);
printf("len argv : %d , isdigit : %d\n",strlen(argv[1]),isnum);
//parseSyslogConfiguration();
if(strlen(argv[1]) == 1 && isnum == 1)
{
loggingLevel = atoi(argv[1]);
if (loggingLevel > 4)
loggingLevel=DEBUG_LOG;
printf("Current Log level initaited : %d",loggingLevel);
}
else
{
loggingLevel=DEBUG_LOG;
printf("Invalid arg (%s)for syslog server setting log level to DEBUG\n",argv[1]);
printf("Values can be from : 0-4 \n");
}
}
if(buf[strlen(logBasePath)-1] != '\\')
{
printf("ADDING END SLASH\n");
strncat(logBasePath,"\\",1);
}
else
printf("NOT ADDING END SLASH\n");
//g_thread_init(NULL);
//write_mutex = g_mutex_new();
slen = sizeof(si_other) ;
getdatetime(&dateinfo);
strcpy(logFileName,"syslog");
memset(fileNameWithPath,0,sizeof(fileNameWithPath));
strcat(fileNameWithPath,logBasePath);
strcat(fileNameWithPath,logFileName);
//strcat(fileNameWithPath,logFileName,logBasePath,"syslog");
status = stat(fileNameWithPath, &sts);
if(errno == ENOENT)
{
fp = fopen(fileNameWithPath, "a+");
logMessage(fp,dateinfo.syslogTimeFormat,"LOGROTATE","[origin software='TEST']",0);
fclose(fp);
}
getdatetime(&dateinfo);
setSyslogFileDate(logBasePath);
//Initialise winsock
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
exit(EXIT_FAILURE);
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_UNIX , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_UNIX;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( PORT );
//Bind
if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
puts("Bind done");
//msgQueueId = g_queue_new();
//g_queue_init(msgQueueId);
// syslogFileWriteThreadId = g_thread_create(ProcessLogMsgfunc, NULL, TRUE, &error);
// syslogRotateThreadId = g_thread_create(syslogRotateMonitor, NULL, TRUE, &error);
//keep listening for data
while(1)
{
fflush(stdout);
memset(buf,'\0', BUFLEN);
if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == SOCKET_ERROR)
{
printf("recvfrom() failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
LOGSTRUCT *qMsg = NULL;
memset(&message,0,sizeof(LOGSTRUCT));
qMsg = malloc(sizeof(LOGSTRUCT));
memset(qMsg,0,sizeof(LOGSTRUCT));
memcpy(qMsg,&buf,sizeof(LOGSTRUCT));
PostMessageQ(qMsg);
}
// g_mutex_free(write_mutex);
// g_queue_free(msgQueueId);
closesocket(s);
WSACleanup();
// g_thread_join(syslogFileWriteThreadId);
// g_thread_join(syslogRotateThreadId);
return 0;
}
CLENT SIDE IMPLEMENTATION:
#include<stdio.h>
#include<winsock2.h>
//#include <glib.h>
#define DEBUG_LOG 0
#define TRACE_LOG 1
#define WARNING_LOG 2
#define ERROR_LOG 3
#define FATAL_LOG 4
#pragma comment(lib,"ws2_32.lib") //Winsock Library
#define SERVER "127.0.0.1" //ip address of udp server
#define BUFLEN 4096 //Max length of buffer
#define PORT 514 //The port on which to listen for incoming data
#define RUN_SERVER 1
struct sockaddr_in si_other;
int s;
GMutex *write_mutex = NULL;
static char appLogName[128] = {'0'};
typedef enum{
LOGINIT,
LOGMESSAGE,
LOGTRACE,
LOGEXIT
}logCommand;
typedef struct
{
logCommand command;
int logLevel;
int pid;
char appName[128];
char loggerMessage[3200];
}LOGSTRUCT, *LPLOGSTRUCT;
int log_init(char *infoName,int level)
{
int ret=0;
WSADATA wsa;
//if(write_mutex == NULL)
//{
//g_thread_init(NULL);
//write_mutex = g_mutex_new();
//Initialise winsock
if(strlen(infoName) == 0 && strlen(appLogName) == 0)
{
strcpy(appLogName,"ATM");
}
else
{
strcpy(appLogName,infoName);
}
//create socket
if ( (s=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
{
printf("socket() failed with error code : %d" , WSAGetLastError());
//exit(EXIT_FAILURE);
return -1;
}
//int nOpt=1;
//setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char*)&nOpt, sizeof(int));
//setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&nOpt, sizeof(int));
//setup address structure
memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
si_other.sin_addr.S_un.S_addr = INADDR_ANY;
//si_other.sin_addr.S_un.S_addr = inet_addr(SERVER);
// si_other.sin_addr.S_un.S_addr = INADDR_BROADCAST ;
// si_other.sin_addr.s_addr = INADDR_ANY;
//}
return 0;
}
void log_exit()
{
RUN_SERVER=0;
closesocket(s);
WSACleanup();
}
void ms_log(char *buf,int priority)
{
debug_log(buf,priority);
}
void debug_log(char *buf,int priority)
{
//g_mutex_lock(write_mutex);
int ret = 0;
LOGSTRUCT log;
memset(&log,0,sizeof(LOGSTRUCT));
log.command=LOGMESSAGE;
log.logLevel=priority;
log.pid = GetCurrentProcessId();
if(strlen(appLogName))
{
strcpy(log.appName,appLogName);
}
if(strlen(buf))
{
strcpy(log.loggerMessage,buf);
ret=sendDataPacket(&log , sizeof(LOGSTRUCT));
}
//g_mutex_unlock(write_mutex);
}
int sendDataPacket(LOGSTRUCT *data , int dataLength)
{
BOOL bResult;
DWORD cbBytes;
int slen;
slen=sizeof(si_other);
if (sendto(s, data, dataLength , 0 , (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
{
printf("sendto() failed with error code : %d" , WSAGetLastError());
return -1;
}
return 0;
}
int main(void)
{
char buf[BUFLEN];
char message[BUFLEN];
WSADATA wsa;
LOGSTRUCT log;
//start communication
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
//exit(EXIT_FAILURE);
return -2;
}
printf("Initialised.\n");
log_init("TESTVEN",1);
while(RUN_SERVER)
{
printf("Enter message : ");
gets(message);
log.command = LOGMESSAGE;
strcpy(log.appName,"TESTAPP");
log.logLevel=DEBUG_LOG;
log.pid=GetCurrentProcessId();
strcpy(log.loggerMessage,message);
sendDataPacket(&log,sizeof(LOGSTRUCT));
//send the message
}
log_exit();
return 0;
}
Error code 10049 : WSAEADDRNOTAVAIL: Cannot assign requested address.
The requested address is not valid in its context. This normally results from an attempt to bind to an address that is not valid for the local computer. This can also result from connect, sendto, WSAConnect, WSAJoinLeaf, or WSASendTo when the remote address or port is not valid for a remote computer (for example, address or port 0).
So can happen with sendto as well. The remote address IP_ADDR_ANY is not a valid address any more on cable plugout?
If its on same machine, try 127.0.0.1 on server code as well?

Resources