欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c/c++ 网络编程 单纯http客户端,服务器端

程序员文章站 2022-11-18 12:16:22
网络编程 单纯http客户端,服务器端 1,http客户端 2,http服务器端 http客户端: "github源代码" 发送端的执行方式: http服务器端 "github源代码" 测试方式: c/c++ 学习互助QQ群:877684253 本人微信:xiaoshitou5854 ......

网络编程 单纯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

c/c++ 学习互助qq群:877684253

c/c++ 网络编程 单纯http客户端,服务器端

本人微信:xiaoshitou5854