I'm creating a server/client tcp connection in c which emulates an airline. I'm having problems sending the list of flights from the server to the client, I can only send a string of characters at the time, and the code I've implemented is not working, is giving me a segmentation fault, can someone please give me some inside into this?
This is the server, the send_all() function will take the socket id and the hashmap to send the list of flights line by line with the write() function.
int send_all(int socket, map_t flight_map)
{
struct hashmap_element {
char* key;
int in_use;
any_t data;
};
struct hashmap_map {
int table_size;
int size;
struct hashmap_element *data;
};
struct hashmap_map * map = (struct hashmap_map *) flight_map;
//int index = map->tableSize;
char line[12];
int i = 0;
for (i = 0; i < map->table_size; i++)
{
strcpy(line, return_flight(map->data[i].key, map->data[i].data));
if (write(socket, line, strlen(line) + 1) < 0) {
error("error: writing to connection");
return 0;
}
}
return 1;
}
char * return_flight(char * flight, void * seats)
{
char tmp[20];
strcpy(tmp, flight);
strcat(tmp, (char *)seats);
return tmp;
}
Here is the Client side: the readSocket, is in charge of reading every single string passing trough the socket connection...
// send input to server
if (write(client_fd, command, strlen(command) + 1) < 0)
error("error: writing to socket");
printf("client: sending %s to server\n", command);
// recieve response from server
if (readSocket(client_fd, buffer) < 0)
error("error: reading from socket");
printf("client: read %s from server\n", buffer);
printf("client: closing client\n");
close(client_fd);
}
return 0;
}
static int readSocket(int socket, char *buffer)
{
ssize_t bytes_read = 0;
bytes_read = recv(socket, buffer, BUFSIZE - 1, 0);
while (bytes_read > 0)
{
buffer[bytes_read] = 0; // Null-terminate the buffer
printf("Buffer: %s\n", buffer);
bytes_read = recv(socket, buffer, BUFSIZE - 1, 0);
}
if (bytes_read == -1)
{
fprintf("Socket recv failed: %s\n", strerror(errno));
return -1;
}
return 0;
}