我正在尝试使用 C++ 开发一个 Web 服务器程序,该程序应该在运行亚马逊机器的云机器上运行。我用C写了一个代码,但是当在地址栏中输入IP地址和端口号时,它不会收到来自Web浏览器的任何响应。但是,它会收到来自 的响应localhost
。这是我的源代码:
#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;
}
我的源代码中是否有任何逻辑问题?