#include #include #include #include #include #include #define serverport 8000 #define httpanswer "HTTP/1.1 200 OK\nContent-Type: text/html\n\nHello World\n" int main (int argc, const char * argv[]) { int e; printf("First, open a socket.\n"); int handle=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); printf("socket handle %d \n",handle); printf("Second, bind to port.\n"); struct sockaddr_in a; bzero(&a, sizeof(a)); // clear structure a.sin_family=AF_INET; a.sin_addr.s_addr=INADDR_ANY; a.sin_port=serverport; e=bind(handle, (struct sockaddr*)&a, sizeof(a)); printf("result from bind: %d \n",e); printf("Third, listen for an incoming connection.\n"); e=listen(handle, 5); // 5 items in waiting quere printf("result from listen: %d \n",e); if (e>=0) // success { struct sockaddr_in cli_addr; int clilen=sizeof(cli_addr); int sock=accept(handle, (struct sockaddr*) &cli_addr, &clilen); printf("second socket handle %d \n",sock); printf("Read request.\n"); char buf[5000]; e=read(sock, buf, sizeof(buf)); if (e>0) { buf[e]=0; // end mark printf("%s \n",buf); } printf("Send answer.\n"); e=write(sock, httpanswer, strlen(httpanswer)); printf("result from write: %d \n",e); close(sock); } e=close(handle); printf("result from close: %d \n",e); return 0; }