// TCPClient.cpp // A simple example for TCP client #include #include #define PORTNUM 50000 /* random port number, we need something */ int main(int argc, char* argv[]) { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD( 2, 2 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ return 1; } struct sockaddr_in sa; struct hostent *hp; SOCKET s; hp = gethostbyname("localhost"); if (hp == NULL) /* we don't know who this host is */ return INVALID_SOCKET; memset(&sa,0,sizeof(sa)); memcpy((char *)&sa.sin_addr, hp->h_addr, hp->h_length); /* set address */ sa.sin_family = hp->h_addrtype; sa.sin_port = htons((u_short)PORTNUM); s = socket(hp->h_addrtype, SOCK_STREAM, 0); if (s == INVALID_SOCKET) return INVALID_SOCKET; /* try to connect to the specified socket */ if (connect(s, (struct sockaddr *)&sa, sizeof sa) == SOCKET_ERROR) { // you should check for error... //int last = WSAGetLastError(); //.... closesocket(s); return INVALID_SOCKET; } char str[] = "hello world"; char inStr[256]; int ret; ret = send( s, str, sizeof(str), 0 ); /*you should check the ret value ...*/ ret = recv(s, inStr, sizeof(inStr), 0); printf("Client Received: %s", inStr); return 0; }