Hello, I am trying to create a very basic socket program in C, (first time programming linux sockets) that the data is recieved and then displayed to the user.. However it doesn't seem to wait for a connection when I call "accept()" and simply sets conn_desc to -1 without pausing at all so of course itthen prints "connection attempt failed!". Can anyone see where I am going wrong?
Here is my code:
Code:
//Socket Header File for connections
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#define Buffer_Size 50
//Integers to hold all the socket data for both server and client
int sock_descriptor, conn_desc;
// Two socket address structures - One for the server itself and the other for client
struct sockaddr_in serv_addr, client_addr;
char buff[Buffer_Size];
void InitaliseSockets()
{
sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);
// Check that the socket descriptor has been created correctly
if(sock_descriptor < 0)
{
printf("Failed creating socket\n");
exit(0);
}
// Initialize the server address struct to zero
bzero((char *)&serv_addr, sizeof(serv_addr));
// Fill server's address family (j.e. get local ips)
serv_addr.sin_family = AF_INET;
// Allow connections from any IP
serv_addr.sin_addr.s_addr = INADDR_ANY;
//Listen on this port
serv_addr.sin_port = htons(28886);
if (bind(sock_descriptor, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("Failed to bind socket!\n");
exit(0);
}
else
printf("Waiting for commands...\n");
}
void WaitForConnect()
{
printf("Waiting for connection...\n");
unsigned int size = sizeof(client_addr);
// Server blocks on this call until a client tries to establish connection.
conn_desc = accept(sock_descriptor, (struct sockaddr *)&client_addr, &size); IT DOESNT SEEM TO WANT TO WAIT HERE, IT SIMPLY CONTINUES AND conn_desc is then == -1...
if (conn_desc == -1)
{
printf("Conection Attempt failed!\n");
exit(0);
}
else
printf("Connected!\n");
if ( read(conn_desc, buff, sizeof(buff)-1) > 0)
printf("Received %s", buff);
else
printf("Failed receiving\n");
close(conn_desc);
close(sock_descriptor);
}
InitialiseSockets() is called at the start of the program, after that WaitForConnection() is called from main. Here is my main function:
Code:
int main()
{
std::string InputCommand;
InitaliseSockets();
START:
cout << "Type 'start' to start the server..\n";
cin >> InputCommand;
//Check for commands
if (InputCommand == "start")
WaitForConnect();
else if (InputCommand == "exit")
exit(0);
else
goto START;
return 0;
}
Can anyone see why this might be happening?
Thanks
DoctorZeus