Skip to content

Latest commit

 

History

History
110 lines (78 loc) · 3.5 KB

57.md

File metadata and controls

110 lines (78 loc) · 3.5 KB

网络,第 3 部分:构建一个简单的 TCP 客户端

原文:https://github.com/angrave/SystemProgramming/wiki/Networking%2C-Part-3%3A-Building-a-simple-TCP-Client

socket

int socket(int domain, int type, int protocol);

Socket 创建一个带域的套接字(通常是用于 IPv4 的 AF_INET),类型是使用 UDP 还是 TCP,协议是任何添加选项。这在内核中创建了一个套接字对象,可以与外部世界/网络进行通信。这将返回一个 fd,因此您可以像普通文件描述符一样使用它!请记住,您希望从 socketfd 执行读取或写入操作,因为它仅将套接字对象表示为客户端,否则您需要遵守服务器的约定。

getaddressinfo

我们在最后一节看到了这个!你是这方面的专家。

connect

int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

将它传递给 sockfd,然后传递你要去的地址和它的长度,你就会断开连接(只要你检查错误)。请记住,网络呼叫是非常容易失败的。

read / write

一旦我们成功连接,我们可以像任何旧的文件描述符一样读取或写入。请记住,如果您连接到网站,您希望符合 HTTP 协议规范,以便获得任何有意义的结果。有一些库可以做到这一点,通常你不会在套接字级别连接,因为它周围有其他库或包

完整的简单 TCP 客户端示例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int s;
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct addrinfo hints, *result;
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_INET; /* IPv4 only */
    hints.ai_socktype = SOCK_STREAM; /* TCP */

    s = getaddrinfo("www.illinois.edu", "80", &hints, &result);
    if (s != 0) {
            fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
            exit(1);
    }

    if(connect(sock_fd, result->ai_addr, result->ai_addrlen) == -1){
                perror("connect");
                exit(2);
        }

    char *buffer = "GET / HTTP/1.0\r\n\r\n";
    printf("SENDING: %s", buffer);
    printf("===\n");
    write(sock_fd, buffer, strlen(buffer));

    char resp[1000];
    int len = read(sock_fd, resp, 999);
    resp[len] = '\0';
    printf("%s\n", resp);

    return 0;
}

示例输出:

SENDING: GET / HTTP/1.0

===
HTTP/1.1 200 OK
Date: Mon, 27 Oct 2014 19:19:05 GMT
Server: Apache/2.2.15 (Red Hat) mod_ssl/2.2.15 OpenSSL/1.0.1e-fips mod_jk/1.2.32
Last-Modified: Fri, 03 Feb 2012 16:51:10 GMT
ETag: "401b0-49-4b8121ea69b80"
Accept-Ranges: bytes
Content-Length: 73
Connection: close
Content-Type: text/html

Provided by Web Services at Public Affairs at the University of Illinois 

评论 HTTP 请求和响应

上面的示例演示了使用超文本传输​​协议向服务器发出的请求。使用以下请求请求网页(或其他资源):

GET / HTTP/1.0 

有四个部分(方法,例如 GET,POST,......);资源(例如/ /index.html /image.png); procigocol“HTTP / 1.0”和两个新行(\ r \ n \ r \ n)

服务器的第一个响应行描述了使用的 HTTP 版本以及使用 3 位数响应代码的请求是否成功:

HTTP/1.1 200 OK 

如果客户端请求了非现有文件,例如GET /nosuchfile.html HTTP/1.0然后第一行包含响应代码是众所周知的404响应代码:

HTTP/1.1 404 Not Found