// TCP Client #include <stdio.h> #include <winsock.h> //#include <afxsock.h>; #pragma comment(lib, "ws2_32.lib") int main(void) { int iRet = 0; WSADATA data; WORD w = MAKEWORD(2, 2); SOCKET s; struct sockaddr_in addrRemote, addrLocal; char sztext[10] = {0}; WSAStartup(w, &data); s = socket(AF_INET, SOCK_STREAM, 0); addrLocal.sin_family = AF_INET; addrLocal.sin_port = htons(1698); addrLocal.sin_addr.S_un.S_addr = htonl(INADDR_ANY); iRet = bind(s, (SOCKADDR*)&addrLocal, sizeof(SOCKADDR)); if (iRet < 0) { printf("bind error!"); } addrRemote.sin_family = AF_INET; addrRemote.sin_port = htons(12423); addrRemote.sin_addr.S_un.S_addr = inet_addr("10.10.22.10"); iRet = connect(s, (SOCKADDR *)&addrRemote, sizeof(addrRemote)); printf("iRet is %d\n", iRet); return 0; }
#include <winsock.h> #pragma comment(lib, "ws2_32.lib") void main(void) { SOCKET iSock = -1, tmpSock = -1; int opt = 0; int iRet = 0; int iRes = 0; struct sockaddr_in addrLocal, addrRemote; WSADATA data; WORD w = MAKEWORD(2, 2); WSAStartup(w, &data); iSock = socket(AF_INET, SOCK_STREAM, 0); if (INVALID_SOCKET == iSock) { printf("Create socket error![%d]\n", GetLastError()); WSACleanup(); return; } //iRes = 1; //ioctlsocket(iSock, FIONBIO, (u_long FAR*)&iRes); /* Set Local IP Address */ addrLocal.sin_family = AF_INET; addrLocal.sin_port = htons(20040); addrLocal.sin_addr.S_un.S_addr = htonl(INADDR_ANY); //addrLocal.sin_addr.S_un.S_addr = inet_addr("10.10.22.100"); iRet = bind(iSock, (SOCKADDR*)&addrLocal, sizeof(SOCKADDR_IN)); if (iRet < 0) { printf("bind error\n"); closesocket(iSock); WSACleanup(); return; } iRet = listen(iSock, 5); if (iRet < 0) { printf("listen error\n"); closesocket(iSock); WSACleanup(); return; } opt = sizeof(SOCKADDR); //tmpSock = accept(iSock, (SOCKADDR *)&addrRemote, &opt); while(1) { tmpSock = accept(iSock, (SOCKADDR *)&addrRemote, &opt); if (INVALID_SOCKET != tmpSock) { printf("Ready to be connected...[%d]\n", tmpSock); closesocket(tmpSock); //WSACleanup(); tmpSock = INVALID_SOCKET; //tmpSock = accept(iSock, (SOCKADDR *)&addrRemote, &opt); } //printf("tmpSock: %d.\n", tmpSock); //else //{ // closesocket(tmpSock);//printf("Accept Remote Connect![%d]\n", tmpSock); //} } return; }