socket学习(一)
环境vs2008
1.把WinSock2.h头文件包含进来;
2.把Ws2_32.lib链接库加进来;
3.相关代码:
1 void DoSocket() 2 { 3 WSADATA wsaData; 4 WSAStartup(MAKEWORD(2, 0), &wsaData); 5 SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 6 SOCKADDR_IN sa; 7 sa.sin_family = AF_INET; 8 9 sa.sin_port = htons(IPPORT_SMTP); 10 // 123.125.50.133 网易邮箱ip 11 sa.sin_addr.S_un.S_addr = inet_addr("123.125.50.133"); 12 if (connect(sock, (SOCKADDR *)&sa, sizeof(sa)) == SOCKET_ERROR) 13 { 14 ShowError(); 15 return; 16 } 17 18 char buffer[256]; 19 ZeroMemory(buffer, sizeof(buffer) / sizeof(char)); 20 recv(sock, buffer, 256, 0); 21 MessageBox(NULL, buffer, "", 0); 22 23 TCHAR cQuit[] = "QUIT\n"; 24 send(sock, cQuit, lstrlen(cQuit), 0); 25 ZeroMemory(buffer, sizeof(buffer) / sizeof(char)); 26 27 recv(sock, buffer, 256, 0); 28 MessageBox(NULL, buffer, "", 0); 29 30 closesocket(sock); 31 WSACleanup(); 32 } 33 34 void ShowError() 35 { 36 TCHAR* lpMsgBuf; 37 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER| 38 FORMAT_MESSAGE_FROM_SYSTEM, 39 NULL, GetLastError(), 40 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 41 (LPTSTR)&lpMsgBuf, 42 0, 43 NULL); 44 MessageBox(NULL, lpMsgBuf, "", MB_ICONERROR); 45 }