0
votes

I have a c# gui that calls a referenced c++ dll when a button is clicked. In the c++ dll I have the following code

  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;
    }

In the c# calling program before the dll is called and the connection made by winsock2 in the dll, I have

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

Then after the dll is called I do

//call dll to run Connect code

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

In the c++ dll when i step in to Connect I get error 10049, which is WSAEADDRNOTAVAIL.

msdn winsock error codes

What am I doing wrong in the Connect call? I chose 54321 as the port following an msdn example. thanks!

1

1 Answers

2
votes

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