À©µµ³×Æ®¿÷ÇÁ·Î±×·¡¹Ö4Àå_ÃÖÁ¾

Similar documents
Microsoft PowerPoint - 09-CE-23-윈도우 소켓

chap7.key

2009년 상반기 사업계획

The Pocket Guide to TCP/IP Sockets: C Version

hd132x_k_v1r3_Final_.PDF

The Pocket Guide to TCP/IP Sockets: C Version

Microsoft PowerPoint - 09-CE-24-채팅 프로그램

歯9장.PDF

PowerPoint 프레젠테이션

Microsoft PowerPoint - 12 ¼ÒÄÏÀ» ÀÌ¿ëÇÑ Åë½Å 1.ppt

Microsoft PowerPoint - 13 ¼ÒÄÏÀ» ÀÌ¿ëÇÑ Åë½Å 2.ppt

Microsoft PowerPoint - chap13-입출력라이브러리.pptx

제1장 Unix란 무엇인가?

목차 목차포트스캔코드포트스캔결과포트스캔탐지코드포트스캔탐지결과 참조

K&R2 Reference Manual 번역본

Microsoft PowerPoint - 06-CompSys-16-Socket.ppt


PowerPoint 프레젠테이션

<443A5C4C C4B48555C B3E25C32C7D0B1E25CBCB3B0E8C7C1B7CEC1A7C6AE425CBED0C3E0C7C1B7CEB1D7B7A55C D616E2E637070>

SYN flooding

Microsoft Word - Network Programming_NewVersion_01_.docx

Microsoft PowerPoint - 15-EmbedSW-10-Socket

목 차 1. 포트스캐닝 (Port Scanning) 이란? 2. 포트 (Port) 란? 3. 스캔 (Scan) 의종류 4. 포트스캐너 (Port Scanner) 구현 5. 포트스캔 (Port Scan) 구현 6. 참조

Microsoft PowerPoint - Lecture_Note_5.ppt [Compatibility Mode]

슬라이드 1

본 강의에 들어가기 전

<4D F736F F D2034C0E52D554E495820BCD2C4CF20C0C0BFEB20C7C1B7CEB1D7B7A1B9D6>

vi 사용법

Microsoft PowerPoint - 09-CE-25-오목게임

제1장 Unix란 무엇인가?

9장 윈도우 소켓 프로그래밍

PowerPoint 프레젠테이션

본 강의에 들어가기 전

슬라이드 1

6주차.key

C++-¿Ïº®Çؼ³10Àå


금오공대 컴퓨터공학전공 강의자료

<43B7CE20BECBBEC6BAB8B4C220BCD2C4CFC7C1B7CEB1D7B7A1B9D62E687770>

본 강의에 들어가기 전

<C0CCBCBCBFB52DC1A4B4EBBFF82DBCAEBBE7B3EDB9AE2D D382E687770>

본 강의에 들어가기 전

The Pocket Guide to TCP/IP Sockets: C Version

Microsoft PowerPoint - Supplement-02-Socket Overview.ppt [호환 모드]

The Pocket Guide to TCP/IP Sockets: C Version

untitled

제1장 Unix란 무엇인가?

3. 다음장에나오는 sigprocmask 함수의설명을참고하여다음프로그램의출력물과그출력물이화면이표시되는시점을예측하세요. ( 힌트 : 각줄이표시되는시점은다음 6 가지중하나. (1) 프로그램수행직후, (2) 5 초후 (3) 10 초후 (4) 15 #include <signa

Microsoft PowerPoint - chap4 [호환 모드]

제1장 Unix란 무엇인가?

13주-14주proc.PDF

Sena Technologies, Inc. HelloDevice Super 1.1.0

<4D F736F F F696E74202D E20B3D7C6AEBFF6C5A920C7C1B7CEB1D7B7A1B9D62E >

문서개정이력 개정번호개정사유및내용개정일자 1.0 최초작성 본문서는원문작성자 (Peter Van Eeckhoutte) 의허가하에번역및배포하는문서로, 원문과관련된모든내용의저작권은 Corelan에있으며, 추가된내용에대해서는 ( 주 ) 한국정보보호교육센터에

학번 : 이름 1. 다음프로그램실행결과를예측하시오. $./a.out & [1] 7216 $ kill -USR $ kill -USR 아래학생이작성한쓰레드코드의문제점을설명하시오. void* thread_main() { pthread_mutex_t

untitled

제12장 파일 입출력

<443A5C4C C4B48555C B3E25C32C7D0B1E25CBCB3B0E8C7C1B7CEC1A7C6AE425CBED0C3E0C7C1B7CEB1D7B7A55C4C656D70656C2D5A69762E637070>

Microsoft PowerPoint - 제11강 파일 처리

fprintf(fp, "clf; clear; clc; \n"); fprintf(fp, "x = linspace(0, %d, %d)\n ", L, N); fprintf(fp, "U = [ "); for (i = 0; i <= (N - 1) ; i++) for (j = 0

03장.스택.key

3. 다음장에나오는 sigprocmask 함수의설명을참고하여다음프로그램의출력물과그출력물이화면이표시되는시점을예측하세요. ( 힌트 : 각줄이표시되는시점은다음 4 가지중하나. (1) 프로그램수행직후, (2) kill 명령실행직후, (3) 15 #include <signal.

BMP 파일 처리

슬라이드 1

Computer Programming (2008 Fall)

The Pocket Guide to TCP/IP Sockets: C Version

Microsoft Word - KPMC-400,401 SW 사용 설명서

0x00 Contents 0x About Nickster 0x Analaysis 0x Exploit

untitled

The Pocket Guide to TCP/IP Sockets: C Version

2009년 상반기 사업계획

The Pocket Guide to TCP/IP Sockets: C Version

자바-11장N'1-502

<4D F736F F F696E74202D FB8DEB8F0B8AE20B8C5C7CE205BC8A3C8AF20B8F0B5E55D>

10.

Microsoft PowerPoint - 04-UDP Programming.ppt


슬라이드 1

Microsoft PowerPoint C-구조체

[ 목차 ] 1. 취약점개요 2. 배경지식 3. 취약점발생결과 (exploit 테스트 ) 4. 취약점발생원인분석 4.1 취약점 Q&A 5. exploit 분석 6. 보안대책 7. 결론 8. 레퍼런스 2

1장. 유닉스 시스템 프로그래밍 개요

제 14 장포인터활용 유준범 (JUNBEOM YOO) Ver 본강의자료는생능출판사의 PPT 강의자료 를기반으로제작되었습니다.

Network Programming

Unix Network Programming Chapter 4. Elementary TCP Sockets

Network Programming

11장 포인터

Microsoft PowerPoint - Lesson13.pptx

chap8.PDF

Microsoft Word - MSOffice_WPS_analysis.doc

2009년 상반기 사업계획

프로그램을 학교 등지에서 조금이라도 배운 사람들을 위한 프로그래밍 노트 입니다. 저 역시 그 사람들 중 하나 입니다. 중고등학교 시절 학교 도서관, 새로 생긴 시립 도서관 등을 다니며 책을 보 고 정리하며 어느정도 독학으르 공부하긴 했지만, 자주 안하다 보면 금방 잊어

hd1300_k_v1r2_Final_.PDF

C Programming

, ( ),, ( ), 3, int kor[5]; int eng[5]; int Microsoft Windows 4 (ANSI C2 ) int kor[5] 20 # define #define SIZE 20 int a[10]; char c[10]; float

5.스택(강의자료).key

untitled

untitled

교육지원 IT시스템 선진화

네트워크 패턴 오버뷰 (간단한 데모 후) 대표 : 그런데, 지금 생각해보니 단일 사용자 환경은 너무 미흡하 네. 다중 사용자를 지원해야겠네. 그리고 윈도우 외 리눅 스나 유닉스 환경에서 작동했으면 좋겠네. <표 2>와 같은 스펙 문서를 다시 작성한다. 프로젝트 웹서버개

4. What will be the output of this program? Explain results for each variable and each thread. #include "apue.h" int var=1; pthread_mutex_t lock; void

Transcription:

P a 02 r t Chapter 4 TCP Chapter 5 Chapter 6 UDP Chapter 7 Chapter 8 GUI

C h a p t e r 04 TCP

1 3 1 2 3 TCP TCP TCP [ 4 2] listen connect send accept recv send recv [ 4 1] PC Internet Explorer HTTP HTTP HTTP TCP TCP FTP TCP 90 91

1 [ 4 3] [ 4 6] TCP TCP [ 4 3] 9000 bind [ 4 4] TCP [ 4 5] TCP [ 4 6] TCP [ 4 7] 1 1 TCP #n 2 TCP [ 4 8] recv printf send fgets send recv printf 2 92 93

001 #include <winsock2.h> 002 #include <stdlib.h> 003 #include <stdio.h> 004 005 #define BUFSIZE 512 006 007 // 008 void err_quit(char *msg) 009 { 010 LPVOID lpmsgbuf; 011 FormatMessage( 012 FORMAT_MESSAGE_ALLOCATE_BUFFER 013 FORMAT_MESSAGE_FROM_SYSTEM, 014 NULL, WSAGetLastError(), 015 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 016 (LPTSTR)&lpMsgBuf, 0, NULL); 017 MessageBox(NULL, (LPCTSTR)lpMsgBuf, msg, MB_ICONERROR); 018 LocalFree(lpMsgBuf); 019 exit(-1); 020 } 021 022 // 023 void err_display(char *msg) 024 { 025 LPVOID lpmsgbuf; 026 FormatMessage( 027 FORMAT_MESSAGE_ALLOCATE_BUFFER 028 FORMAT_MESSAGE_FROM_SYSTEM, 029 NULL, WSAGetLastError(), 030 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 031 (LPTSTR)&lpMsgBuf, 0, NULL); 032 printf("[%s] %s", msg, (LPCTSTR)lpMsgBuf); 033 LocalFree(lpMsgBuf); 034 } 035 036 int main(int argc, char* argv[]) 037 { 038 int retval; 039 040 // 041 WSADATA wsa; 042 if(wsastartup(makeword(2,2), &wsa)!= 0) 043 return -1; 044 045 // socket() 046 SOCKET listen_sock = socket(af_inet, SOCK_STREAM, 0); 047 if(listen_sock == INVALID_SOCKET) err_quit("socket()"); 048 049 // bind() 050 SOCKADDR_IN serveraddr; 051 ZeroMemory(&serveraddr, sizeof(serveraddr)); 052 serveraddr.sin_family = AF_INET; 053 serveraddr.sin_port = htons(9000); 054 serveraddr.sin_addr.s_addr = htonl(inaddr_any); 055 retval = bind(listen_sock, (SOCKADDR *)&serveraddr, sizeof(serveraddr)); 056 if(retval == SOCKET_ERROR) err_quit("bind()"); 057 058 // listen() 059 retval = listen(listen_sock, SOMAXCONN); 060 if(retval == SOCKET_ERROR) err_quit("listen()"); 061 062 // 063 SOCKET client_sock; 064 SOCKADDR_IN clientaddr; 065 int addrlen; 94 95

066 char buf[bufsize+1]; 067 068 while(1){ 069 // accept() 070 addrlen = sizeof(clientaddr); 071 client_sock = accept(listen_sock, (SOCKADDR *) &clientaddr, &addrlen); 072 if(client_sock == INVALID_SOCKET){ 073 err_display("accept()"); 074 continue; 075 } 076 printf("\n[tcp ] :IP =%s, =%d\n", inet_ntoa(clientaddr.sin_addr), 077 ntohs(clientaddr.sin_port)); 078 079 // 080 while(1){ 081 // 082 retval = recv(client_sock, buf, BUFSIZE, 0); 083 if(retval == SOCKET_ERROR){ 084 err_display("recv()"); 085 break; 086 } 087 else if(retval == 0) 088 break; 089 090 // 091 buf[retval] = '\0'; 092 printf("[tcp/%s:%d] %s\n", inet_ntoa(clientaddr.sin_addr), 093 ntohs(clientaddr.sin_port), buf); 094 095 // 096 retval = send(client_sock, buf, retval, 0); 097 if(retval == SOCKET_ERROR){ 098 err_display("send()"); 099 break; 100 } 101 } 102 103 // closesocket() 104 closesocket(client_sock); 105 printf("[tcp ] : IP =%s, =%d\n", 106 inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); 107 } 108 109 // closesocket() 110 closesocket(listen_sock); 111 112 // 113 WSACleanup(); 114 return 0; 115 } 001 #include <winsock2.h> 002 #include <stdlib.h> 003 #include <stdio.h> 004 005 #define BUFSIZE 512 006 007 // 008 void err_quit(char *msg) 009 { 010 LPVOID lpmsgbuf; 011 FormatMessage( 012 FORMAT_MESSAGE_ALLOCATE_BUFFER 013 FORMAT_MESSAGE_FROM_SYSTEM, 014 NULL, WSAGetLastError(), 96 97

015 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 016 (LPTSTR)&lpMsgBuf, 0, NULL); 017 MessageBox(NULL, (LPCTSTR)lpMsgBuf, msg, MB_ICONERROR); 018 LocalFree(lpMsgBuf); 019 exit(-1); 020 } 021 022 // 023 void err_display(char *msg) 024 { 025 LPVOID lpmsgbuf; 026 FormatMessage( 027 FORMAT_MESSAGE_ALLOCATE_BUFFER 028 FORMAT_MESSAGE_FROM_SYSTEM, 029 NULL, WSAGetLastError(), 030 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 031 (LPTSTR)&lpMsgBuf, 0, NULL); 032 printf("[%s] %s", msg, (LPCTSTR)lpMsgBuf); 033 LocalFree(lpMsgBuf); 034 } 035 036 // 037 int recvn(socket s, char *buf, int len, int flags) 038 { 039 int received; 040 char *ptr = buf; 041 int left = len; 042 043 while(left > 0){ 044 received = recv(s, ptr, left, flags); 045 if(received == SOCKET_ERROR) 046 return SOCKET_ERROR; 047 else if(received == 0) 048 break; 049 left -= received; 050 ptr += received; 051 } 052 053 return (len - left); 054 } 055 056 int main(int argc, char* argv[]) 057 { 058 int retval; 059 060 // 061 WSADATA wsa; 062 if(wsastartup(makeword(2,2), &wsa)!= 0) 063 return -1; 064 065 // socket() 066 SOCKET sock = socket(af_inet, SOCK_STREAM, 0); 067 if(sock == INVALID_SOCKET) err_quit("socket()"); 068 069 // connect() 070 SOCKADDR_IN serveraddr; 071 serveraddr.sin_family = AF_INET; 072 serveraddr.sin_port = htons(9000); 073 serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1"); 074 retval = connect(sock, (SOCKADDR *)&serveraddr, sizeof(serveraddr)); 075 if(retval == SOCKET_ERROR) err_quit("connect()"); 076 077 // 078 char buf[bufsize+1]; 079 int len; 080 081 // 082 while(1){ 083 // 084 ZeroMemory(buf, sizeof(buf)); 085 printf("\n[ ]"); 086 if(fgets(buf, BUFSIZE+1, stdin) == NULL) 087 break; 088 98 99

089 // '\n' 090 len = strlen(buf); 091 if(buf[len-1] == '\n') 092 buf[len-1] = '\0'; 093 if(strlen(buf) == 0) 094 break; 095 096 // 097 retval = send(sock, buf, strlen(buf), 0); 098 if(retval == SOCKET_ERROR){ 099 err_display("send()"); 100 break; 101 } 102 printf("[tcp ] %d.\n", retval); 103 104 // 105 retval = recvn(sock, buf, retval, 0); 106 if(retval == SOCKET_ERROR){ 107 err_display("recv()"); 108 break; 109 } 110 else if(retval == 0) 111 break; 112 113 // 114 buf[retval] = '\0'; 115 printf("[tcp ] %d.\n", retval); 116 printf("[ ] %s\n", buf); 117 } 118 119 // closesocket() 120 closesocket(sock); 121 122 // 123 WSACleanup(); 124 return 0; 125 } 100 101

102 103

TCP 1 TCP IP [ 4 20] TCP IP 2 local IP remote IP TCP LISTENING ESTABLISHED 104 105

bind IP 1 TCP [ 4 21] socket bind IP listen TCP LISTENING accept IP send recv closesocket s int bind( SOCKET s, const struct sockaddr* name, int namelen ); IP name TCP IP SOCKADDR_IN IP namelen TCPServer bind 050 SOCKADDR_IN serveraddr; 051 ZeroMemory(&serveraddr, sizeof(serveraddr)); 052 serveraddr.sin_family = AF_INET; 053 serveraddr.sin_port = htons(9000); 054 serveraddr.sin_addr.s_addr = htonl(inaddr_any); 055 retval = bind(listen_sock, (SOCKADDR *)&serveraddr, sizeof(serveraddr)); 056 if(retval == SOCKET_ERROR) err_quit("bind()"); TCP socket closesocket send recv 50 51 0 API ZeroMemory C memset 52 AF_INET 53 9000 htons 106 107

54 IP IP INADDR_ANY IP multihomed host INADDR_ANY 55 56 bind SOCKADDR * listen TCP LISTENING int listen( SOCKET s, int backlog ); s bind IP backlog connection queue backlog SOMAXCONN SOCKADDR_IN serveraddr;... retval = bind(listen_sock, (SOCKADDR *)&serveraddr, sizeof(sockaddr_in)); TCPServer listen 059 retval = listen(listen_sock, SOMAXCONN); 060 if(retval == SOCKET_ERROR) err_quit("listen()"); SOCKADDR_IRDA serveraddr;... retval = bind(listen_sock, (SOCKADDR *)&serveraddr, sizeof(sockaddr_irda));... 59 60 backlog listen SOCKADDR_IRDA serveraddr;... retval = bind(listen_sock, (SOCKADDR *)&serveraddr, sizeof(serveraddr)); accept IP IP IP 108 109

s SOCKET accept( SOCKET s, struct sockaddr* addr, int* addrlen ); addr accept addr IP addrlen addr accept addrlen accept wait state NT 2000 CPU 0 [ 4 22] accept TCPServer accept 062 // 063 SOCKET client_sock; 064 SOCKADDR_IN clientaddr; 065 int addrlen;... 068 while(1){ 069 // accept() 070 addrlen = sizeof(clientaddr); 071 client_sock = accept(listen_sock, (SOCKADDR *) &clientaddr, &addrlen); 072 if(client_sock == INVALID_SOCKET){ 073 err_display("accept()"); 074 continue; 075 } 076 printf("\n[tcp ] : IP =%s, =%d\n", 077 inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); 078 079 // 080 while(1){... 101 } 102 103 // closesocket() 104 closesocket(client_sock); 105 printf("[tcp ] : IP =%s, =%d\n", 106 inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); 107 } 63 accept SOCKET 64 accept accept IP 65 accept 68 110 111

70 accept addrlen clientaddr 71 75 accept err_display 67 76 77 IP inet_ntoa ntohs 3 2 TCP [ 4 23] socket connect send recv closesocket 80 101 accept send recv 104 106 IP TCP socket closesocket send recv connect connect TCP int connect( SOCKET s, const struct sockaddr* name, int namelen ); 112 113

s name IP namelen bind bind connect IP 1024 5000 [ 4 24] TCP UDP 6 IP send buffer receive buffer socket buffer send recv TCPClient connect 070 SOCKADDR_IN serveraddr; 071 serveraddr.sin_family = AF_INET; 072 serveraddr.sin_port = htons(9000); 073 serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1"); 074 retval = connect(sock, (SOCKADDR *)&serveraddr, sizeof(serveraddr)); 075 if(retval == SOCKET_ERROR) err_quit("connect()"); 70 73 IP 74 75 connect TCP 100 200 300 100 200 300 350 250 TCP 3 send recv WSA* send TCP IP send send 114 115

s int send( SOCKET s, const char* buf, int len, int flags ); connected recv int recv( SOCKET s, char* buf, int len, int flags ); buf len flags send 0 MSG_DONTROUTE 7 SO_DONTROUTE MSG_OOB 9 send blocking send send len wait state len send send len Nonblocking 9 ioctlsocket send send 1 len send recv s connected buf len buf flags recv 0 MSG_PEEK MSG_OOB 9 recv MSG_PEEK recv recv len len closesocket TCP recv 0 recv 0 normal close = graceful close 116 117

recv len TCP recv recvn [ 4 25] 53 left 0 len 037 int recvn(socket s, char *buf, int len, int flags) 038 { 039 int received; 040 char *ptr = buf; 041 int left = len; 042 043 while(left > 0){ 044 received = recv(s, ptr, left, flags); 045 if(received == SOCKET_ERROR) 046 return SOCKET_ERROR; 047 else if(received == 0) 048 break; 049 left -= received; 050 ptr += received; 051 } 052 053 return (len - left); 054 } 37 recvn recv 39 recv 40 ptr ptr 41 left 43 44 46 recv 47 48 recv 0 49 50 ptr left TCPClient send recv 078 char buf[bufsize+1]; 079 int len;... 082 while(1){ 083 // 084 ZeroMemory(buf, sizeof(buf)); 085 printf("\n[ ]"); 086 if(fgets(buf, BUFSIZE+1, stdin) == NULL) 087 break; 088 089 // '\n' 090 len = strlen(buf); 091 if(buf[len-1] == '\n') 092 buf[len-1] = '\0'; 093 if(strlen(buf) == 0) 094 break; 095 096 // 097 retval = send(sock, buf, strlen(buf), 0); 098 if(retval == SOCKET_ERROR){ 099 err_display("send()"); 100 break; 101 } 102 printf("[tcp ] %d.\n", retval); 118 119

103 104 // 105 retval = recvn(sock, buf, retval, 0); 106 if(retval == SOCKET_ERROR){ 107 err_display("recv()"); 108 break; 109 } 110 else if(retval == 0) 111 break; 112 113 // 114 buf[retval] = '\0'; 115 printf("[tcp ] %d.\n", retval); 116 printf("[ ] %s\n", buf); 117 } 78 = 79 84 87 fgets 90 92 \n 93 94 Enter 97 102 send send strlen buf 105 111 recvn recvn 114 116 \0 TCPServer send recv client_sock accept 066 char buf[bufsize+1];... 080 while(1){ 081 // 082 retval = recv(client_sock, buf, BUFSIZE, 0); 083 if(retval == SOCKET_ERROR){ 084 err_display("recv()"); 085 break; 086 } 087 else if(retval == 0) 088 break; 089 090 // 091 buf[retval] = '\0'; 092 printf("[tcp/%s:%d] %s\n", inet_ntoa(clientaddr.sin_addr), 093 ntohs(clientaddr.sin_port), buf); 094 095 // 096 retval = send(client_sock, buf, retval, 0); 097 if(retval == SOCKET_ERROR){ 098 err_display("send()"); 099 break; 100 } 101 } 66 80 recv 0 SOCKET_ERROR 82 88 recv recvn 91 93 \0 96 100 send 120 121

TCP TCP TCP 1 application level [ 4 26] struct DrawMessage1 { int x1, y1; // int x2, y2; // int width; // int color; // }; struct DrawMessage2 { int x1, y1; // int r; // int fillcolor; // int width; // int color; // }; 122 123

struct DrawMessage1 { int type; // = LINE int x1, y1; // int x2, y2; // int width; // int color; // }; struct DrawMessage2 { int type; // = CIRCLE int x1, y1; // int r; // int fillcolor; // int width; // int color; // }; [ ] EOR EOR EOR EOR [ 4 27] recvn 2 TCP [ ] EOR End Of Record 3 124 125

member alignment sizeof msg 10 =4+1+4+1 16 [ 4 28] msg struct MyMessage { int a; // 4 char b; // 1 int c; // 4 char d; // 1 }; MyMessage msg; //... send(sock, (char *)&msg, sizeof(msg), 0); int a; // 4 char b; // 1 int c; // 4 char d; // 1 }; #pragma pack() // MyMessage msg; //... send(sock, (char *)&msg, sizeof(msg), 0); 10 #pragma pack msg [ 4 29] #pragma pack(1) // : 1 struct MyMessage { 126 127

3 TCP IP [ 4 32] 256 4 001 #include <winsock2.h> 002 #include <stdlib.h> 003 #include <stdio.h> 004 005 #define BUFSIZE 4096 006 007 // 008 void err_quit(char *msg) 009 { 010 LPVOID lpmsgbuf; 011 FormatMessage( 012 FORMAT_MESSAGE_ALLOCATE_BUFFER 013 FORMAT_MESSAGE_FROM_SYSTEM, 014 NULL, WSAGetLastError(), 015 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 016 (LPTSTR)&lpMsgBuf, 0, NULL); 017 MessageBox(NULL, (LPCTSTR)lpMsgBuf, msg, MB_ICONERROR); 018 LocalFree(lpMsgBuf); 019 exit(-1); 020 } 021 022 // 023 void err_display(char *msg) 024 { 025 LPVOID lpmsgbuf; 026 FormatMessage( 027 FORMAT_MESSAGE_ALLOCATE_BUFFER 028 FORMAT_MESSAGE_FROM_SYSTEM, 029 NULL, WSAGetLastError(), 030 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 031 (LPTSTR)&lpMsgBuf, 0, NULL); 128 129

032 printf("[%s] %s", msg, (LPCTSTR)lpMsgBuf); 033 LocalFree(lpMsgBuf); 034 } 035 036 int main(int argc, char* argv[]) 037 { 038 int retval; 039 040 if(argc < 2){ 041 fprintf(stderr, "Usage: %s [FileName]\n", argv[0]); 042 return -1; 043 } 044 045 // 046 WSADATA wsa; 047 if(wsastartup(makeword(2,2), &wsa)!= 0) 048 return -1; 049 050 // socket() 051 SOCKET sock = socket(af_inet, SOCK_STREAM, 0); 052 if(sock == INVALID_SOCKET) err_quit("socket()"); 053 054 // connect() 055 SOCKADDR_IN serveraddr; 056 serveraddr.sin_family = AF_INET; 057 serveraddr.sin_port = htons(9000); 058 serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1"); 059 retval = connect(sock, (SOCKADDR *)&serveraddr, sizeof(serveraddr)); 060 if(retval == SOCKET_ERROR) err_quit("connect()"); 061 062 // 063 FILE *fp = fopen(argv[1], "rb"); 064 if(fp == NULL){ 065 perror(" "); 066 return -1; 067 } 068 069 // 070 char filename[256]; 071 ZeroMemory(filename, 256); 072 sprintf(filename, argv[1]); 073 retval = send(sock, filename, 256, 0); 074 if(retval == SOCKET_ERROR) err_quit("send()"); 075 076 // 077 fseek(fp, 0, SEEK_END); 078 int totalbytes = ftell(fp); 079 080 // 081 retval = send(sock, (char *)&totalbytes, sizeof(totalbytes), 0); 082 if(retval == SOCKET_ERROR) err_quit("send()"); 083 084 // 085 char buf[bufsize]; 086 int numread; 087 int numtotal = 0; 088 089 // 090 rewind(fp); // 091 while(1){ 092 numread = fread(buf, 1, BUFSIZE, fp); 093 if(numread > 0){ 094 retval = send(sock, buf, numread, 0); 095 if(retval == SOCKET_ERROR){ 096 err_display("send()"); 097 break; 098 } 099 numtotal += numread; 130 131

100 } 101 else if(numread == 0 && numtotal == totalbytes){ 102 printf("!: %d \n", numtotal); 103 break; 104 } 105 else{ 106 perror(" "); 107 break; 108 } 109 } 110 fclose(fp); 111 112 // closesocket() 113 closesocket(sock); 114 115 // 116 WSACleanup(); 117 return 0; 118 } 001 #include <winsock2.h> 002 #include <stdlib.h> 003 #include <stdio.h> 004 005 #define BUFSIZE 4096 006 007 // 008 void err_quit(char *msg) 009 { 010 LPVOID lpmsgbuf; 011 FormatMessage( 012 FORMAT_MESSAGE_ALLOCATE_BUFFER 013 FORMAT_MESSAGE_FROM_SYSTEM, 014 NULL, WSAGetLastError(), 015 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 016 (LPTSTR)&lpMsgBuf, 0, NULL); 017 MessageBox(NULL, (LPCTSTR)lpMsgBuf, msg, MB_ICONERROR); 018 LocalFree(lpMsgBuf); 019 exit(-1); 020 } 021 022 // 023 void err_display(char *msg) 024 { 025 LPVOID lpmsgbuf; 026 FormatMessage( 027 FORMAT_MESSAGE_ALLOCATE_BUFFER 028 FORMAT_MESSAGE_FROM_SYSTEM, 029 NULL, WSAGetLastError(), 030 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 031 (LPTSTR)&lpMsgBuf, 0, NULL); 032 printf("[%s] %s", msg, (LPCTSTR)lpMsgBuf); 033 LocalFree(lpMsgBuf); 034 } 035 036 // 037 int recvn(socket s, char *buf, int len, int flags) 038 { 039 int received; 040 char *ptr = buf; 041 int left = len; 042 043 while(left > 0){ 044 received = recv(s, ptr, left, flags); 045 if(received == SOCKET_ERROR) 046 return SOCKET_ERROR; 047 else if(received == 0) 048 break; 132 133

049 left -= received; 050 ptr += received; 051 } 052 053 return (len - left); 054 } 055 056 int main(int argc, char* argv[]) 057 { 058 int retval; 059 060 // 061 WSADATA wsa; 062 if(wsastartup(makeword(2,2), &wsa)!= 0) 063 return -1; 064 065 // socket() 066 SOCKET listen_sock = socket(af_inet, SOCK_STREAM, 0); 067 if(listen_sock == INVALID_SOCKET) err_quit("socket()"); 068 069 // bind() 070 SOCKADDR_IN serveraddr; 071 ZeroMemory(&serveraddr, sizeof(serveraddr)); 072 serveraddr.sin_family = AF_INET; 073 serveraddr.sin_port = htons(9000); 074 serveraddr.sin_addr.s_addr = htonl(inaddr_any); 075 retval = bind(listen_sock, (SOCKADDR *)&serveraddr, sizeof(serveraddr)); 076 if(retval == SOCKET_ERROR) err_quit("bind()"); 077 078 // listen() 079 retval = listen(listen_sock, SOMAXCONN); 080 if(retval == SOCKET_ERROR) err_quit("listen()"); 081 082 // 083 SOCKET client_sock; 084 SOCKADDR_IN clientaddr; 085 int addrlen; 086 char buf[bufsize]; 087 088 while(1){ 089 // accept() 090 addrlen = sizeof(clientaddr); 091 client_sock = accept(listen_sock, (SOCKADDR *)&clientaddr, &addrlen); 092 if(client_sock == INVALID_SOCKET){ 093 err_display("accept()"); 094 continue; 095 } 096 printf("\nfilesender : IP =%s, =%d\n", 097 inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); 098 099 // 100 char filename[256]; 101 ZeroMemory(filename, 256); 102 retval = recvn(client_sock, filename, 256, 0); 103 if(retval == SOCKET_ERROR){ 104 err_display("recv()"); 105 closesocket(client_sock); 106 continue; 107 } 108 printf("-> : %s\n", filename); 109 110 // 111 int totalbytes; 112 retval = recvn(client_sock, (char *)&totalbytes, sizeof(totalbytes), 0); 113 if(retval == SOCKET_ERROR){ 114 err_display("recv()"); 134 135

115 closesocket(client_sock); 116 continue; 117 } 118 printf("-> : %d\n", totalbytes); 119 120 // 121 FILE *fp = fopen(filename, "wb"); 122 if(fp == NULL){ 123 perror(" "); 124 closesocket(client_sock); 125 continue; 126 } 127 128 // 129 int numtotal = 0; 130 while(1){ 131 retval = recvn(client_sock, buf, BUFSIZE, 0); 132 if(retval == SOCKET_ERROR){ 133 err_display("recv()"); 134 break; 135 } 136 else if(retval == 0) 137 break; 138 else{ 139 fwrite(buf, 1, retval, fp); 140 if(ferror(fp)){ 141 perror(" "); 142 break; 143 } 144 numtotal += retval; 145 } 146 } 147 fclose(fp); 148 149 // 150 if(numtotal == totalbytes) 151 printf("->!\n"); 152 else 153 printf("->!\n"); 154 155 // closesocket() 156 closesocket(client_sock); 157 printf("filesender : IP =%s, =%d\n", 158 inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); 159 } 160 161 // closesocket() 162 closesocket(listen_sock); 163 164 // 165 WSACleanup(); 166 return 0; 167 } 136 137

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 138 139

1 2 3 4 5 6 7 140