我正在尝试使用C语言中的SOCKS5代理进行HTTP请求,我尝试了以下代码
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc, char** argv) {
struct addrinfo hints, *res;
int sockfd;
memset(&hints,0,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo("localhost","9050",&hints,&res);
sockfd = socket(res->ai_family,res->ai_socktype,res->ai_protocol);
int connected = connect(sockfd,res->ai_addr,res->ai_addrlen);
if (connected == -1) {
perror("Error");
}
char buffer[256];
char msginit[256];
msginit[0] = '\5'; //Protocol number
msginit[1] = '\2'; //# of authentication methods
msginit[2] = '\0'; //no authentication
msginit[3] = '\2'; //user+pass auth
//get dest
memset(&hints,0,sizeof hints);
memset(res,0,sizeof *res);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo("duckduckgo.com","80",&hints,&res);
struct sockaddr_in *ip = (struct sockaddr_in *)res->ai_addr;
uint32_t* addr=&(ip->sin_addr.s_addr);
//copy dest to request
memcpy (msginit+4,addr,sizeof (uint32_t));
send(sockfd, (void *)msginit, (size_t)strlen(msginit),0);
printf("Sent.\n");
recv(sockfd,buffer,256,0); //This is where it gets stuck!
printf("%s\n",buffer);
}
它说它发送但请求没有发送到网站,我也无法从recv读取任何数据,任何想法我怎么能解决这个问题?
答案 0 :(得分:0)
正如评论中所建议的那样,您不能使用strlen()来获取二进制缓冲区的使用量。在这种情况下,您知道要发送4个字节加sizeof (uint32_t)
,因此您可以在发送呼叫中使用此字符,并且您将不再被卡住。否则,您将只发送两个第一个字节(\ 0之前的字节),代理将在响应之前等待更多数据。
(有关SOCKS5的更多帮助,其他地方有大量可用信息。但上述内容解决了代码发布后的特定问题。)