如何在 Linux 上使用套接字发出 http 请求?目前,我得到
HTTP/1.1 301 Moved Permanently
//etc
Location: https://server.com
这是代码的相关部分(函数太大,无法在此处发布):
/* Socket file descriptor. */
int sock;
struct sockaddr_in sockaddr;
struct hostent *host; /* Host information. */
sock = socket(AF_INET, /* IPV4 protocol. */
SOCK_STREAM, /* TCP socket. */
0); /* O for socket() function choose the correct protocol based on the socket type. */
if(sock == INVALID_SOCKET) return SOCK_GENERROR;
if((host = gethostbyname(server)) == NULL) {
close(sock);
return SOCK_HOSTNFOUND;
}
/* zero buffer */
memset(&sockaddr, 0, sizeof(sockaddr));
sockaddr.sin_family = AF_INET;
memcpy(&sockaddr.sin_addr,
host -> h_addr,
host -> h_length );
sockaddr.sin_port = htons(port);
if(connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) == INVALID_SOCKET) {
close(sock);
return SOCK_FERRCONN;
}
if(send(sock, sendbuf, bufsize, 0) == INVALID_SOCKET) {
close(sock);
return SOCK_FERRWRITE;
}
if((readed = recv(sock, recvbuffer, sizeof(recvbuffer), 0)) <= 0)
break;
在通话中,server="server.com";
并且port=80;
我试图尽可能删除我的 onw 例程并从此代码中键入以使您更干净。