Winsock simple communication
Header file
# include
# include
# include
# include
# include
# pragma comment (lib, "WS2_32.lib")
source code
/ / 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
}
/ / create 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 * 1000ram / 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
/ / But for this simple 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
Current embedded code for automated testing