美文网首页C语言C语言&嵌入式
使用socket写一个tcp客户端

使用socket写一个tcp客户端

作者: sunnnnnnnnnny | 来源:发表于2020-03-11 21:48 被阅读0次

    原理大家都懂
    环境

    • ubuntu14.04
      直接上代码
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <netdb.h>
    #include <sys/types.h>
    #include <netinet/in.h>
    #include <sys/socket.h>
    #include <unistd.h>
    #include <arpa/inet.h>
    #include <errno.h>
    
    int main(int argc, char *argv[])
    {
        int sockfd;
        char recvbuffer[1024*4];
        //  char buffer[1024];
        struct sockaddr_in server_addr;
        struct hostent *host;
        int portnumber, nbytes;
        int i = 0;
        char *t;
        char send_buffer[] = "GET / HTTP/1.1\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36\r\n\r\n";
        if (argc != 3)
        {
            fprintf(stderr, "Usage :%s hostname portnumber\a\n", argv[0]);
            exit(1);
        }
        if ((host = gethostbyname(argv[1])) == NULL)
        {
            herror("Get host name error\n");
            exit(1);
        }
        printf("h_name: %s\n", host->h_name); //IP地址
        for (; host->h_addr_list[i]; i++)
        {
            printf("IP addr %d: %s\n", i + 1, inet_ntoa(*(struct in_addr *)host->h_addr_list[i]));
        }
        if ((portnumber = atoi(argv[2])) < 0)
        {
            fprintf(stderr, "Usage:%s hostname portnumber\a\n", argv[0]);
            exit(1);
        }
        if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
        {
            fprintf(stderr, "Socket Error:%s\a\n", strerror(errno));
            exit(1);
        }
        bzero(&server_addr, sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(portnumber);
        server_addr.sin_addr = *((struct in_addr *)host->h_addr_list[0]);
        if (connect(sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1)
        {
            fprintf(stderr, "Connect error:%s\n", strerror(errno));
            exit(1);
        }
        printf("Request:\n%s",send_buffer);
        send(sockfd, send_buffer, strlen(send_buffer), 0);
        recv(sockfd, recvbuffer, sizeof(recvbuffer), 0);
        t = strstr(recvbuffer,"\r\n\r\n");
        *t = (char)0;
        
        printf("\nResponse:\n%s\n", recvbuffer);
    
        close(sockfd);
        exit(0);
    }
    

    编译

     gcc -o tcp_client tcp_client.c 
    

    运行

    ./tcp_client www.baidu.com 80
    

    输入了http请求头部和响应头


    运行结果

    相关文章

      网友评论

        本文标题:使用socket写一个tcp客户端

        本文链接:https://www.haomeiwen.com/subject/ojlkjhtx.html