The follow is a simple piece of code I wrote to demonstrate how HTTP server works. I compiled it run it under cygwin, but I cannot use web browser to connect to this simple http server. And after running the simple http server, I can still run apache at port 80, and if apache is not running, "netstat -an" show that port 80 is not occupied.
I wrote another simple program which sends a simple "hello" string to the simple http server, and then got the responses.
What's wrong with this program? why I cannot connect it using web browser, but I can connect it with another simple program?
When is a port been occupied? After "bind" or "listen"?
If one application is using a port of a particular network interface (say 192.168.2.1:80, suppose more than one network interfaces exist), can another application use the same port at another interface (say 192.168.55.1:80)?
when running httpd, there are more than one httpd processes in the processes list, only one is using 0.0.0.0:80, if using cygwin apache, other httpd is using other UDP port? Why?
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "sys/types.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "netdb.h"
#include "unistd.h"
#include "fcntl.h"
#define PORT 80
char HttpHeader[1000];
char HeaderTemplate[] =
"HTTP/1.0 200 OK\r\n"
"Server: PRIMITIVE Server\r\n"
"Date: %s\r\n"
"Content-Type: text/html\r\n"
"Accept-Ranges: bytes\r\n"
"Content-Length: %d\r\n\r\n";
char PageContent[] = "Hello World!";
char GMTNow[] = "11/15/14 00:59:00 GMT";
char ClntRequest[1000];
struct sockaddr_in SocketAddress;
int ClntDescriptor; /* socket descriptor to client */
int SrvrDescriptor; /* socket descriptor for server */
int main(int argc, char* argv[])
{
sprintf(HttpHeader, HeaderTemplate, GMTNow, strlen(PageContent));
SrvrDescriptor = socket(AF_INET, SOCK_STREAM, 0);
SocketAddress.sin_family = AF_INET;
SocketAddress.sin_port = PORT;
SocketAddress.sin_addr.s_addr = INADDR_ANY;
bind(SrvrDescriptor, (struct sockaddr*)&SocketAddress, sizeof(SocketAddress));
listen(SrvrDescriptor, 5);
ClntDescriptor = accept(SrvrDescriptor, 0, 0);
while (1)
{
recv(ClntDescriptor, ClntRequest, sizeof(ClntRequest), 0);
printf("%s\n", ClntRequest);
write(ClntDescriptor, HttpHeader, strlen(HttpHeader));
write(ClntDescriptor, PageContent, strlen(PageContent));
printf("%s", HttpHeader);
printf("%s", PageContent);
}
close(SrvrDescriptor);
return EXIT_SUCCESS;
}