连接功能错误10047(winsock2)

时间:2013-01-09 19:30:20

标签: c++ winapi winsock2

所以我从使用基本Windows套接字函数的MSDN站点复制了一些测试代码。这是代码:

#include "stdafx.h"

#ifndef UNICODE
#define UNICODE
#endif

#include <stdio.h>
#include <winsock2.h>
#include <ws2tcipip.h>
#include <wchar.h>


int main()
{

    int iResult = 0;

    //----------------------
    // Initialize Winsock
    WSADATA wsaData;
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        wprintf(L"WSAStartup function failed with error: %d\n", iResult);
        return 1;
    }
    //----------------------
    // Create a SOCKET for connecting to server
    SOCKET ConnectSocket;
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        wprintf(L"socket function failed with error: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }
    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port of the server to be connected to.

    int I = sizeof(sockaddr_in);
        sockaddr_in clientService;
    clientService.sin_family = AF_INET;     
        clientService.sin_port = htons(5000);
    in_addr *s = (in_addr*)malloc(sizeof(in_addr));
    s->s_addr = inet_addr("127.0.0.1");
    clientService.sin_addr = (in_addr_t)s;

    iResult = connect(ConnectSocket, (sockaddr*)&clientService,I);
    if (iResult == SOCKET_ERROR) {
        wprintf(L"connect function failed with error: %ld\n", WSAGetLastError());
        iResult = closesocket(ConnectSocket);
        if (iResult == SOCKET_ERROR)
            wprintf(L"closesocket function failed with error: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    wprintf(L"Connected to server.\n");

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

    WSACleanup();
    return 0;
}

代码编译得很好。但是当我运行程序时,命令提示符屏幕显示以下错误消息:

  

连接失败,错误:10047

现在我知道错误10047表示地址结构中存在错误。我尝试使用inet_pto n,但由于inet_pton使用memcpy函数,因此会导致段错误(内存访问冲突)。那么这里发生了什么? connect功能是否未正确实施?也许还有另一种方法来指定地址结构。

2 个答案:

答案 0 :(得分:1)

来自MSDN:http://msdn.microsoft.com/en-us/library/windows/desktop/ms737625%28v=vs.85%29.aspx

sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr("127.0.0.1");
clientService.sin_port = htons(27015);

看起来像你的设置.sin_addr.s_addr模糊不清。

如果结果如上所述,不是问题,那么也许你已经打开了IP6协议,但没有IP4,这就是为什么AF_NET失败并需要AF_NET6。

答案 1 :(得分:0)

在你的情况下问题出在这一行:

clientService.sin_addr = (in_addr_t)s;

您正在为in_addr对象分配一个in_addr指针。像这样取消引用指针(还要注意,如果删除转换,编译器将捕获问题:

clientService.sin_addr = *s;

但是,LastCoder的方法会更容易。没有理由malloc()单独的in_addr结构来复制它。