网络编程 单纯http客户端,服务器端
1,http客户端
2,http服务器端
http客户端:
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <netdb.h> #include <string.h> #include <unistd.h> int main(int argc, char* argv[]){ int err; int sock; char buf[32]; char* deststr; addrinfo hints, *res0, *res; if(argc != 2){return 1;} deststr = argv[1]; memset(&hints, 0, sizeof(hints)); hints.ai_socktype = sock_stream; hints.ai_family = pf_unspec; if((err = getaddrinfo(deststr, "http", &hints, &res0)) != 0){ printf("error %d:%sn", err, gai_strerror(err)); return 1; } for(res = res0; res != null; res = res->ai_next){ printf("%dn", res->ai_family); sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if(sock < 0){continue;} if(connect(sock, res->ai_addr, res->ai_addrlen) != 0){ close(sock); continue; } break; } freeaddrinfo(res0); if(res == null){ printf("failedn"); return 1; } snprintf(buf, sizeof(buf), "get / http/1.0rnrn"); int n = write(sock, buf, (int)strlen(buf)); while(n > 0){ n = read(sock, buf, sizeof(buf)); write(fileno(stdout), buf, n); } close(sock); return 0; }
发送端的执行方式:
./a.out www.baidu.com
http服务器端
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <netdb.h> #include <string.h> #include <unistd.h> int main(){ int sock0; sockaddr_in client; socklen_t len; int sock; int yes = 1; addrinfo *res, hints; int err; char buf[2048]; int n; char inbuf[2048]; hints.ai_family = af_inet; hints.ai_flags = ai_passive; hints.ai_socktype = sock_stream; err = getaddrinfo(null, "12345", &hints, &res); if(err != 0){ printf("getaddrinfo %sn", gai_strerror(err)); return 1; } sock0 = socket(res->ai_family, res->ai_socktype, 0); setsockopt(sock0, sol_socket, so_reuseaddr, (const char*)&yes, sizeof(yes)); bind(sock0, res->ai_addr, res->ai_addrlen); listen(sock0, 5); snprintf(buf, sizeof(buf), "http/1.0 200 okrn" "content-length: 20rn" "content-type:text/htmlrn" "rn" "hellorn"); while(1){ len = sizeof(client); sock = accept(sock0, (sockaddr*)&client, &len); n = read(sock, inbuf, sizeof(inbuf)); write(fileno(stdout), inbuf, n); write(sock, buf, (int)strlen(buf)); close(sock); } close(sock0); return 0; }
测试方式:
在浏览器里输入:https://127.0.0.1:12345 或者输入:https://localhost:12345
c/c++ 学习互助qq群:877684253
本人微信:xiaoshitou5854
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/607067.html