|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <string.h> |
| 4 | +#include <errno.h> |
| 5 | +#include <sys/types.h> |
| 6 | +#include <sys/socket.h> |
| 7 | +#include <netinet/in.h> |
| 8 | + |
| 9 | +#define MAXLINE 4096 |
| 10 | + |
| 11 | +int main(int argc, char ** argv) |
| 12 | +{ |
| 13 | + int listenfd, connfd; |
| 14 | + struct sockaddr_in servaddr; |
| 15 | + char buff[4096]; |
| 16 | + int n; |
| 17 | + |
| 18 | + if (-1 == (listenfd = socket(AF_INET, SOCK_STREAM, 0))) { |
| 19 | + printf("create socket error: %s(errno: %d)\n", strerror(errno), errno); |
| 20 | + exit(0); |
| 21 | + } |
| 22 | + |
| 23 | + memset(&servaddr, 0, sizeof(servaddr)); |
| 24 | + servaddr.sin_family = AF_INET; |
| 25 | + servaddr.sin_addr.s_addr = htonl(INADDR_ANY); |
| 26 | + servaddr.sin_port = htons(8888); |
| 27 | + |
| 28 | + if (-1 == (bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)))) { |
| 29 | + printf("bind socket error: %s(errno: %d)\n", strerror(errno), errno); |
| 30 | + exit(0); |
| 31 | + } |
| 32 | + |
| 33 | + if (-1 == (listen(listenfd, 10))) { |
| 34 | + printf("listen socket error: %s(errno: %d)\n", strerror(errno), errno); |
| 35 | + exit(0); |
| 36 | + } |
| 37 | + |
| 38 | + printf("=====waiting for client's request=====\n"); |
| 39 | + while (1) { |
| 40 | + if (-1 == (connfd = accept(listenfd, (struct sockaddr *)NULL, NULL))) { |
| 41 | + printf("accept socket error: %s(errno: %d)\n", strerror(errno), errno); |
| 42 | + continue; |
| 43 | + } |
| 44 | + |
| 45 | + n = recv(connfd, buff, MAXLINE, 0); |
| 46 | + buff[n] = '\0'; |
| 47 | + printf("recv msg from client: %s\n", buff); |
| 48 | + |
| 49 | + char *header = "HTTP/1.1 200 OK\r\nContent-type: text/html\r\nServer-name:WenJun1055\r\n\r\n"; |
| 50 | + char *body = "Hello World"; |
| 51 | + write(connfd, header, strlen(header)); |
| 52 | + write(connfd, body, strlen(body)); |
| 53 | + |
| 54 | + close(connfd); |
| 55 | + } |
| 56 | + |
| 57 | + close(listenfd); |
| 58 | +} |
0 commit comments