So I copied some test code from the MSDN site that uses basic windows socket functions. Here is the code:
#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;
}
The code compiles just fine. But when I run the program the command prompt screen displays the following error message:
connection failed with error: 10047
Now I know that Error 10047 indicates an error in the address structure. I tried using inet_pto
n but that leads to a segment error (memory access violation) as inet_pton
uses the memcpy
function. So what is going on here? Is the connect
function improperly implemented? Maybe there is another way to specify the address structure.
Is the connect function improperly implemented?
-- No. – GSerg