基本C Windows TCP套接字TOR,recv()挂起?

时间:2017-12-24 15:42:00

标签: c windows sockets tcp-ip tor

我在我的本地Windows机器上设置了tor,它在监听,我可以通过我的firefox浏览器连接它。 我尝试在c中创建一个简单的套接字程序(在socks5 rfc:https://en.wikipedia.org/wiki/SOCKS#SOCKS5之后),但recv()挂起一段时间,然后我没有收到任何内容(字节数:0,在我的printf语句中)。

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")

#pragma comment(lib, "wsock32.lib")
#pragma comment(lib, "advapi32.lib")


#define LENGTH 1256
int main(int argc, char** argv) {
    int iResult = 0;
    WSADATA wsaData ;
    struct addrinfo hints, *res ;
    int sockfd = INVALID_SOCKET ;

    char buffer[LENGTH];
    char msginit[LENGTH];
    ZeroMemory(msginit, LENGTH);

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    printf("Start ...\n");



    memset(&hints,0,sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    getaddrinfo("127.0.0.1","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 == SOCKET_ERROR) {
        printf("connect() error, code: %d\n", WSAGetLastError());
        return -1;
    } else {
        printf("conenct() success.\n");
    }


    msginit[0] = 0x05; //Protocol number
    msginit[1] = 0x01; //# of authentication methods
    msginit[2] = 0x00; //no authentication 
    //msginit[3] = 0x02; //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;
    int * addr=&(ip->sin_addr.s_addr);

    //copy dest to request
    memcpy (msginit+3,addr,sizeof (int)); 

    iResult = send(sockfd, msginit, (size_t)strlen(msginit),0);
    if(iResult == SOCKET_ERROR) {
        printf("send() - error: %d\n", WSAGetLastError() );
    }
    printf("Init message `Sent`.\n");

    iResult = recv(sockfd,buffer,LENGTH,0); //This is where it gets stuck!
    printf("Received number of bytes: %d\n", iResult);
    printf("In the end.\n");
    printf("%s\n",buffer);


}

该计划的输出如下:

Start ...
conenct() success.
Init message `Sent`.
Received number of bytes: 0
In the end.
:

1 个答案:

答案 0 :(得分:2)

问题在于send函数,请不要使用strlen()。

iResult = send(sockfd, msginit, (size_t)strlen(msginit),0);