2

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

#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_pton 但这会导致inet_pton使用该memcpy函数时出现段错误(内存访问冲突)。那么这里发生了什么?功能是否connect执行不当?也许还有另一种方法来指定地址结构。

4

2 回答 2

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 的原因。

于 2013-01-09T19:47:04.470 回答
0

在您的情况下,问题是这里的这一行:

clientService.sin_addr = (in_addr_t)s;

您正在将 in_addr 指针分配给 in_addr 对象。像这样取消引用指针(另请注意,如果您删除强制转换,编译器会发现问题:

clientService.sin_addr = *s;

不过,LastCoder 的方法会更容易。没有理由malloc()只复制一个单独的 in_addr 结构。

于 2013-01-09T23:18:43.100 回答