-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.c
More file actions
61 lines (57 loc) · 1.61 KB
/
http.c
File metadata and controls
61 lines (57 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
int main(int argc,char* argv[]){
if(argc != 3){
printf("usage:%d [ip] [port]\n");
return 1;
}
int sock = socket(AF_INET,SOCK_STREAM,0);
if(sock < 0){
perror("socket");
return 2;
}
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_port = htons(atoi(argv[2]));//将整型由本地转向网络:htons
local.sin_addr.s_addr = inet_addr(argv[1]);//将字符串由本地转向网络:inet_addr
//绑定
int ret = bind(sock,(struct sockaddr*)&local,sizeof(local));
if(ret < 0){
perror("bind");
return 3;
}
//监听
ret = listen(sock,5);
if(ret < 0){
//监听失败
perror("listen");
return 4;
}
printf("bind and listen success!\n");
for(;;){
struct sockaddr_in client_socket;
socklen_t len;
int client_sock = accept(sock,(struct sockaddr*)&client_socket,&len);
if(client_sock<0){
perror("accept");
continue;
}
char input_buf[10240]={0};
ssize_t read_size = read(client_sock,input_buf,sizeof(input_buf)-1);
if(read_size<0){
return 6;
}
printf("[Request]%s",input_buf);
char buf[1024] = {0};
const char*hello = "<h1>8b305say:hello world<h1>";
sprintf(buf,"HTTP/1.0 200 OK\nContent-Length:%lu\n\n%s",strlen(hello),hello);
write(client_sock,buf,sizeof(buf));
}
return 0;
}