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