0

我有 ac# gui,它在单击按钮时调用引用的 c++ dll。在 c++ dll 中,我有以下代码

  SOCKADDR_IN server; 

    server.sin_port=htons (54321); 
    server.sin_family = AF_INET; 

    server.sin_addr.s_addr = INADDR_ANY; 

    // Connect to server.
    int iResult = connect(Socket, (SOCKADDR *) & server, sizeof (server));
    if (iResult == SOCKET_ERROR) {

          long iError = WSAGetLastError();
            if (iError == WSAEWOULDBLOCK)
                printf("recv failed with error: WSAEWOULDBLOCK\n");
            else
                printf("recv failed with error: %ld\n", iError);

        wprintf(L"connect function failed with error: %ld\n", WSAGetLastError());
        iResult = closesocket(Socket);
        if (iResult == SOCKET_ERROR)
        wprintf(L"closesocket function failed with error: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

在调用dll之前的c#调用程序和dll中的winsock2建立的连接中,我有

IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener serverSocket = new TcpListener(localAddr,54321);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();

然后在调用dll之后我做

//调用dll运行连接代码

clientSocket = serverSocket.AcceptTcpClient();//hangs up here because dll can't Connect.

在我进入 Connect 的 c++ dll 中,我收到错误 10049,即 WSAEADDRNOTAVAIL。

msdn winsock 错误代码

我在 Connect 通话中做错了什么?我按照 msdn 示例选择了 54321 作为端口。谢谢!

4

1 回答 1

2

From what I can see, unless you haven't provided the code here, you haven't set the sin_addr field of the SOCKADDR_IN structure properly. It is expecting an IP address in network byte order.

You need to do something like:

inet_pton(AF_INET, "127.0.0.1", &server.sin_addr);

Source:

http://msdn.microsoft.com/en-us/library/windows/desktop/cc805844(v=vs.85).aspx

于 2013-07-10T18:21:51.403 回答