小弟初学socket,想着用socket做一个简单的翻译程序,需要通过网络请求去获取译文,现在已经能够获取到如下服务器响应的内容:
HTTP/1.1 200 OK
Date: Wed, 08 Feb 2017 06:26:12 GMT
Connection: keep-alive
Content-Length: 11
"时钟"
但是不知道如何把响应内容中的 "时钟"
取出来,最好把状态码也能取到,不知道有没有如下这种结构体:
struct response {
int status_code; //200
int content_length; //11
char *content_data; //时钟
...
}
能够把响应的字段一一对应起来。
下面是我的代码:
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char **argv)
{
int portno = 4000;
char *host = "ilp64.com";
char *message_fmt = "GET /?qs=%s&text=%s HTTP/1.1\r\nHost: %s\r\n\r\n";
char *query_qs = "oj3rnfefnm,ew";
char *query_text = "clock";
struct hostent *server;
struct sockaddr_in serv_addr;
int sockfd;
char message[1024], response[4096];
sprintf(message, message_fmt, query_qs, query_text, host);
printf("GET Request:\n%s\n", message);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(host);
if (server == NULL)
error("ERROR no such host");
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length);
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
error("ERROR connecting");
if (send(sockfd, message, strlen(message), 0) < 0)
error("ERROR sending");
if (recv(sockfd, response, 4096, 0) < 0)
error("ERROR received");
puts(response);
return 0;
}
If you do it directly through the socket, the response is a byte array to your program, and you need to disassemble it yourself according to the http protocol. Please note that
content-length
in the http protocol is used to tell you how big the data in the body part is. If there is nocontent-length
, you have to look atTransfer-Encoding: chunked
, which is a bit more complicated. Generally speaking, if the corresponding body is not large,content-length
will be returned.content-length
用来告诉你body部分的数据到底有多大。如果没有content-length
,就得看Transfer-Encoding: chunked
,这个复杂点了。一般来说相应体不大的话,会返回content-length
。可以考虑用
You can consider usinglibcurl
libcurl
🎜Writing your own parser is very annoying. In fact, it is just a lot of string matching. Just use ready-made ones, such as the one below
http-parser
After receiving the data packet, the data packet is disassembled according to the http protocol.