网络编程 单纯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:%s\n", err, gai_strerror(err));
return 1;
}
for(res = res0; res != NULL; res = res->ai_next){
printf("%d\n", 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("failed\n");
return 1;
}
snprintf(buf, sizeof(buf), "GET / HTTP/1.0\r\n\r\n");
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 %s\n", 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 OK\r\n"
"Content-Length: 20\r\n"
"Content-Type:text/html\r\n"
"\r\n"
"HELLO\r\n");
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;
}
测试方式:
在浏览器里输入:http://127.0.0.1:12345
或者输入:http://localhost:12345