I'm new to programming, but I'm trying to use C++ to create a TCP server with Winsock which will send a list of all the host's files and directories to the client using dirent. So far the code creates the server, lists all of its directories, and sends the name of only one of them to the client. I can't figure out why only one directory name is being sent, despite all of them being listed on the server's computer.
The 1st code block creates the socket. The issue seems to be in the 2nd block
#include<io.h>
#include<stdio.h>
#include<winsock2.h>
#include <iostream>
#include <dirent.h>
#include <sys/types.h>
#include <string>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s , new_socket;
struct sockaddr_in server , client;
int c;
char *message;
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( 8888 );
//Bind
if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
}
puts("Bind done");
//Listen to incoming connections
listen(s , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
new_socket = accept(s , (struct sockaddr *)&client, &c);
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d" , WSAGetLastError());
}
puts("Connection accepted");
This is what lists & sends the directories.
//List directory
DIR *dr;
struct dirent *en;
dr = opendir("."); //open all or present directory
if (dr) {
while ((en = readdir(dr)) != NULL) {
printf("%s\n", en->d_name); //print all directory name
message = ("%s\n", en->d_name); //Problem line?
}
closedir(dr); //close all directory
}
send(new_socket , message , strlen(message) , 0);
getchar();
closesocket(s);
WSACleanup();
return 0;
}
I'd really appreciate any help understanding the issue and how to fix it.