Dronov Dmitrii
Dronov Dmitrii

Reputation: 23

Can't GET html page from my HTTP server written in C

I can't get in my browser a HTML page from my server written in C. Code for server is here:

#define PORT 8080

int serverSocket = 0;

//Creating a socket, AF_INET is for IPv4
if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
    perror("Error in socket");
    exit(EXIT_FAILURE);
}

//setting address
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(PORT); //htons() is for converting TCP/IP network byte order.
address.sin_addr.s_addr = INADDR_ANY;
memset(&address.sin_zero, 0, sizeof(address.sin_zero)); //IMPORTANT to clear sin_zero because of unexpected behavior!

//binding server
if (bind(serverSocket, (struct sockaddr*)&address, sizeof(address)) < 0) {
    perror("Error in bind");
    exit(EXIT_FAILURE);
}

//setting listen
if (listen(serverSocket, 10) < 0) {
    perror("Error in listen");
    exit(EXIT_FAILURE);
}

long valRead = 0;
int newSocket = 0;
int addrLen = sizeof(address);

char *send = "GET /index.html HTTP/1.1 200 OK\nContent-Type: text/html;charset=UTF-8\nContent-Length: 242\n\nindex.html";

while(1) {
    printf("Waiting for a connection.\n");
    if (newSocket = accept(serverSocket, (struct sockaddr*)&address, (socklen_t*)&addrLen) < 0) {
        perror("Error in accept");
        exit(EXIT_FAILURE);
    }
    char buffer[3000] = {0};
    valRead = read(newSocket, buffer , sizeof(buffer));
    printf("%s\n", buffer);
    write(newSocket, send, strlen(send));
    printf("Sent\n");
    if (close(newSocket) < 0) {
        perror("Error in close");
        exit(EXIT_FAILURE);
    }
    exit(EXIT_SUCCESS);
}
return 0;

Terminal output: Server is running on my Virtual Machine.

I use browser in my VM also. Page just isn't loading. After a try to connect server is still waiting for a connection.

What can be a problem? Thanks.

Upvotes: 0

Views: 42

Answers (1)

Barmar
Barmar

Reputation: 782166

You need parentheses here, because < has higher precedence than =:

if ((newSocket = accept(serverSocket, (struct sockaddr*)&address, (socklen_t*)&addrLen)) < 0) {

You're setting newSocket to the result of the comparison, not the descriptor returned by accept().

Upvotes: 2

Related Questions