Header file
#include <WinSock2.h>
#include <string>
#include <WS2tcpip.h>
#include <IPHlpApi.h>
#include <stdio.h>
#pragma comment (lib, "Ws2_32.lib")
Source
Initialize Winsock
Wsadata Wsadata;
int Iresult;
Iresult = WSAStartup (Makeword (2, 2), &wsadata);
if (Iresult! = 0) {
printf ("WSAStartup failed:%d\n", Iresult);
return NULL;
}
Get Connection Properties
struct Addrinfo * result = NULL, *PTR = null, hints;
ZeroMemory (&hints, sizeof (hints));
hints.ai_family = af_inet;
Hints.ai_socktype = Sock_stream;
Hints.ai_protocol = ipproto_tcp;
Iresult = getaddrinfo ("192.168.0.18", "7002", &hints, &result);
Iresult = getaddrinfo ("192.168.37.187", "7002", &hints, &result);
if (Iresult! = 0) {
printf ("Getaddrinfo failed:%d\n", Iresult);
WSACleanup ();
return NULL;
}
Creating a Socket Object
ptr = result;
SOCKET connectsocket = Invalid_socket;
Connectsocket = socket (ptr->ai_family, Ptr->ai_socktype, Ptr->ai_protocol);
if (Connectsocket = = Invalid_socket) {
printf ("Error at Socket ():%ld\n", WSAGetLastError ());
Freeaddrinfo (result);
WSACleanup ();
return NULL;
}
Link
Iresult = Connect (Connectsocket, ptr->ai_addr, (int) ptr->ai_addrlen);
if (Iresult = = Socket_error) {
printf ("Error at Socket ():%ld\n", WSAGetLastError ());
Closesocket (Connectsocket);
Connectsocket = Invalid_socket;
}
int nsendbuf = 32 * 1000;//set to 32K
SetSockOpt (Connectsocket, Sol_socket, So_rcvtimeo, (const char*) &nsendbuf, sizeof (int));
Should really try the next address returned by Getaddrinfo
If the Connect call failed
Example we just free the resources
Returned by getaddrinfo and print an arror message
Freeaddrinfo (result);
if (Connectsocket = = Invalid_socket) {
printf ("Unable to connect to server!\n");
WSACleanup ();
return NULL;
}
Send (Connectsocket, Strsendcontext.c_str (), Strsendcontext.length (), 0);
Char szbuffer[1024] = {0};
Recv (Connectsocket, Szbuffer, 1024, 0);
:: Closesocket (Connectsocket);
Description
Automated testing of current inline code
Winsock Simple Communication