Created
December 11, 2012 17:39
-
-
Save Jack2/4260534 to your computer and use it in GitHub Desktop.
[C++]connect_example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef UNICODE | |
#define UNICODE | |
#endif | |
#define WIN32_LEAN_AND_MEAN | |
#include <winsock2.h> | |
#include <ws2tcpip.h> | |
#include <stdio.h> | |
#pragma comment(lib, "ws2_32.lib") | |
int wmain() | |
{ | |
// Winsock 초기화 | |
WSADATA wsaData; | |
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData); | |
if (iResult != NO_ERROR){ | |
wprintf(L"WSAStartup function failed with error: %d\n", iResult); | |
return 1; | |
} | |
// 서버로 연결을 하기 위한 SOCKET 생성 | |
SOCKET ConnectSocket; | |
ConnectSocket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP) ; | |
if(ConnectSocket == INVALID_SOCKET){ | |
wprintf(L"socket function failed with error : %ld\n", WSAGetLastError()); | |
WSACleanup(); | |
return 1; | |
} | |
//연결할 서버의 주소와 포트번호 | |
sockaddr_in clientService; | |
clientService.sin_family = AF_INET; | |
clientService.sin_addr.s_addr = inet_addr("127.0.0.1"); | |
clientService.sin_port = htons(31337); | |
// 서버로 연결 | |
iResult = connect(ConnectSocket,(SOCKADDR *)&clientService,sizeof(clientService)) ; | |
if(iResult == SOCKET_ERROR){ | |
wprintf(L"connect function failed with error: %ld\n", WSAGetLastError()); | |
iResult = closesocket(ConnectSocket); | |
if (iResult == SOCKET_ERROR) | |
wprintf(L"closesocekt function failed with error: %ld\n",WSAGetLastError()); | |
WSACleanup(); | |
return 1; | |
} | |
wprintf(L"Connected to server. \n"); | |
iResult = closesocket(ConnectSocket); | |
if (iResult == SOCKET_ERROR){ | |
wprintf(L"closesocket function failed with error : %ld\n", WSAGetLastError()); | |
WSACleanup(); | |
return 1; | |
} | |
WSACleanup(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dev-C ++ 로 컴파일 시 오류 발생
: 프로젝트로 생성한 뒤 windows console 로 선택을 했으나 컴파일 오류 발생함.