C as a web server to run in the cloud without receiving any response from the browser

I am trying to develop a web server program using C ++, which is supposed to run on a cloud machine running on an amazon machine. I wrote the code in C, but it will not receive any response from the web browser when the IP address and port number are entered in the address bar. However, it receives a response from localhost . Here is my source code:

 #include<stdio.h> #include<string.h> #include<sys/socket.h> #include<arpa/inet.h> #include<unistd.h> int main(int argc , char *argv[]) { int socket_desc , new_socket , c; struct sockaddr_in server , client; char *message; //Create socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket"); } server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( 8080 ); //Bind if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) { puts("bind failed"); return 1; } puts("bind done"); listen(socket_desc , 3); puts("Waiting for incoming connections..."); c = sizeof(struct sockaddr_in); while( (new_socket = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) ) { puts("Connection accepted"); //Reply to the client message = "Hello Client , I have received your connection. But I have to go now, bye\n"; write(new_socket , message , strlen(message)); } if (new_socket<0) { perror("accept failed"); return 1; } return 0; } 

Is there any logical problem in my source code?

+4
source share
2 answers

Just tested your code on a CentOS 6.4 computer. It worked ... I had a "Connection Accepted" from

 "http://localhost:8080" 

and from another computer on the network I entered

 "http://192.168.2.22:8080" 

and got "Connection Accepted" on the Linux console. In addition, both the IP address and "localhost" worked with the machine on which the program is running. I am sure this is a network problem.

But try changing the code a bit, just for that ...

Try the following:

changes:

 socket_desc = socket(AF_INET , SOCK_STREAM , 0); 

in

 socket_desc = socket(AF_INET , SOCK_STREAM , IPPROTO_TCP); 

add:

 close(new_socket); 

after

 write(new_socket , message , strlen(message)); 

and again, hell ... add:

 memset(&server, 0, sizeof(server)); 

before using the server structure.

0
source

You are checking the firewall settings of a running host.

if it is linux use the command

netstat -atnp - to see if the correct port (8080) is open in your program or not.

service iptables stop - stop the firewall in old versions

systemctl stop firewalld - stop the firewall in recent versions

enable the firewall again after testing your program, replacing stop with start .

or enable TCP port 8080 in the firewall settings if you want to constantly use this port

0
source

Source: https://habr.com/ru/post/1492585/


All Articles