[linux] C语言Linux系统编程-socket开发响应HTTP协议_Linux
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(){
        //创建套接字
        int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        //将套接字和IP、端口绑定
        struct sockaddr_in serv_addr;
        memset(&serv_addr, 0, sizeof(serv_addr));  //每个字节都用0填充
        serv_addr.sin_family = AF_INET;  //使用IPv4地址
        serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);  //具体的IP地址
        serv_addr.sin_port = htons(1234);  //端口
        bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
        //进入监听状态,等待用户发起请求
        listen(serv_sock, 20);
        while(1){
                //接收客户端请求
                struct sockaddr_in clnt_addr;
                socklen_t clnt_addr_size = sizeof(clnt_addr);
                int clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size);

                FILE *cin = fdopen(clnt_sock, "r");
                setbuf(cin, (char *) 0);
                char buf[1024];
                fgets(buf, 1024, cin); //读取第一行
                printf("\n%s", buf);
                char *html="Hello Taoshihan ";
                char *result = malloc(strlen(html) + strlen(buf) + 1);
                strcpy(result, html);
                strcat(result, buf);
                                                                                                    34,7-17       Top
                //接收客户端请求
                struct sockaddr_in clnt_addr;
                socklen_t clnt_addr_size = sizeof(clnt_addr);
                int clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size);

                FILE *cin = fdopen(clnt_sock, "r");
                setbuf(cin, (char *) 0);
                char buf[1024];
                fgets(buf, 1024, cin); //读取第一行
                printf("\n%s", buf);
                char *html="Hello Taoshihan ";
                char *result = malloc(strlen(html) + strlen(buf) + 1);
                strcpy(result, html);
                strcat(result, buf);

                //char *result=str_join(html,buf);
                char res[1024];
                char str[] = "HTTP/1.1 200 OK\r\nServer: Tao\r\nContent-Type: text/html; charset=utf-8\r\nContent-Leng
th: %d\r\n\r\n%s";
                sprintf(res,str,strlen(result),result);
                printf("%s\n",res);
                write(clnt_sock, res, sizeof(res));
                //关闭套接字
                close(clnt_sock);
        }
        close(serv_sock);
        return 0;
}