Computer Networks Practice Socket 1 DK Han Junghwan Song dkhan@mmlab.snu.ac.kr jhsong@mmlab.snu.ac.kr 2012-3-26 Multimedia and Mobile communications Laboratory
Introduction Client / Server model Server waits client s connection request and response Client requests and waits server s response Server and client are not machines, but programs Request Response Server Client 2/24
What is a socket? API by which server and client can communicate Abstraction which connects two end hosts which provides full-duplex channel Kernel: the end point of communication Application: file descriptor for network r/w operations FILE *fp; fp = fopen( data.txt, w );...... fprintf(fp, result = %d \n, x); int Csocket; Csocket = socket ( );...... write(csocket, buf, buf_len); 3/24
TCP socket / UDP socket Transport layer protocol is responsible for Process to process delivery Segmentation and reassembly A segment into packets / Packets into a segment Flow control, error control TCP Connection-oriented Ordered packet delivery Flow control UDP Connection-less No order x 4/24
Flow TCP socket Connection oriented 5/24
Server socket Telephone 1. 전화기구입 Server Socket 1. 소켓생성 2. 전화번호할당 2. IP 주소할당. 3. 케이블에연결 3. 연결요청대기상태 4. 수화기든다! 4. 연결수락! 6/24
Server socket procedure (1/2) Step1: 전화를걸고싶은데무엇이필요합니까? 소켓생성요구 #include <sys/types.h> #include <sys/socket.h> int socket (int domain, int type, int protocol) Step2: 당신의전화번호는어떻게되나요? 주소할당요구 (IP 주소, Port 정보 ) #include <sys/socket.h> int bind(int sockfd, struct sockaddr *myaddr, int addrlen) 7/24
Server socket procedure (1/2) Step3: 전화기를연결하시겠습니까? 연결요청대기상태로진입 #include <sys/socket.h> int listen(int sockfd, int backlog) Step4: 전화벨이울립니다. 어서전화받으세요! 연결요청수락 #include <sys/socket.h> int accept(int sockfd, struct sockaddr *addr, int *addrlen) 8/24
Client socket procedure Step1: 전화를걸고싶은데무엇이필요합니까? 소켓의생성 Step2: 전화를걸어요 연결요청 #include <sys/socket.h> int connect(int sockfd, struct sockaddr *serv_addr, int addrlen) 9/24
socket() int socket( int domain, int type, int protocol ); 소켓을생성하고이에대한파일디스크립터를받는다 파라미터 domain : 통신을하기위해사용할프로토콜체계 type : 사용하게되는전송타입 protocol : 특정프로토콜을지정 TCP 의경우 (PF_INET, SOCK_STREAM, IPPROTO_TCP) 리턴값 생성된소켓의파일디스크립터 10/24
socket() code 11/24
connect() int connect( int sockfd, const struct sockaddr* serv_addr, socklen_t addrlen ); 원격지의서버에연결을설정하기위해사용함 파라미터 sockfd : socket() 에의해서생성된파일디스크립터 serv_addr : 연결할서버의 IP 주소와 TCP 포트 구조체의포인터를강제캐스트해서전달 addrlen : serv_addr 의크기 리턴값 성공하면 0, 실패하면 -1 12/24
Socket Address (1/2) Socket Address Structure struct sockaddr { u_short sa_family; char sa_data[14]; }; //address family //protocol specific address Socket Address Structure for Internet struct sockaddr_in { short sin_family; u_short sin_port; struct sin_addr; char sin_zero[8]; }; //AF_INET for ipv4 //16-bit port # (network byte ordered) //32-bit internet address //(network byte ordered) //dummy 13/24
Socket Address (2/2) 엔디안변환 호스트바이트순서 네트워크바이트순서변환 short(16bit) / long(32bit) 정수변환 htons() : Host 시스템에서 Network 로 short 형데이터를보낼때바이트오더를바꾸어주는함수 htonl() : long 형데이터의바이트오더를바꾸어주는함수 ntohs() : Network 에서 Host 로 short 형데이터의바이트오더를바꾸어주는함수 ntohl() : long 형데이터의바이트오더를바꾸어주는함수 14/24
bind() int bind( int sockfd, struct sockaddr* my_addr, socklen_t addrlen ); 소켓에주소를지정한다. 서버가자신이제공하는서비스의포트를지정하기위해서사용한다. 파라미터 sockfd : socket() 에의해서생성된파일디스크립터 my_addr : 소켓에지정할 IP 주소와 TCP 포트 구조체의포인터를강제캐스트해서전달 addrlen : my_addr 의크기 리턴값 성공하면 0, 실패하면 -1 15/24
listen() int listen( int sockfd, int backlog ); 이소켓에서연결을기다리겠다고커널에알린다. 즉시리턴된다. 파라미터 sockfd : socket() 에의해서생성된파일디스크립터 backlog : 연결요청대기큐의최대길이 서버가다른작업을진행하느라바로 accept 를못하는동안대기시킬연결의최대개수 일반적으로 5 를사용해왔으나연결요청이잦은서버는비교적큰값으로설정한다. 리턴값 성공하면 0, 실패하면 -1 16/24
accept() int accept( int sockfd, struct sockaddr* addr, socklen_t* addrlen ); 연결요청을받아들인다. 새로연결을요청한상대가없으면요청이들어올때까지블록된다. 파라미터 sockfd : socket() 에의해서생성된파일디스크립터 addr : 연결을요청한상대의주소를얻어온다. 필요없으면 NULL addrlen : addr 의길이를얻어온다. 리턴값 성공하면새로운소켓을나타내는파일디스크립터, 실패하면 -1 17/24
Assignment #1 : Simple client/server application Connection establishment Message transmission / reception Disconnect detection 18/24
Requirements 서버실행 :./server 57300 57300 포트에서접속을기다린다. 클라이언트실행 :./client 127.0.0.1 57300 서버를실행시켜놓고클라이언트를실행시키면 New connection 메시지가서버의터미널에출력 클라이언트가어떠한 String 을입력하면서버는그 String 를터미널에출력 클라이언트를강제종료시 Disconnect 메시지가서버의터미널에출력 (ctrl+c, /quit 칠경우 ) Localhost 에서만접속 19/24
Constraints Server / Client program should be implemented independently (You can simply run 2 process using 2 cmd windows) Copying file or report is strongly prohibited 20/24
Submission You should summit.. Source files Make file ( if you have ) Executable files Report: 1 page. usage & simple flow chart (5 th slide) to TA s E-mail address ( dkhan@mmlab.snu.ac.kr ) Till 4/4 24:00 (midnight) Using title [CN_s1] student ID _ Name Your assignment program will be extended to chatting / p2p file transfer program 21/24
Submission (ccnx) You should summit.. Paper (Content centric networking)summary report to TA s E-mail address ( dkhan@mmlab.snu.ac.kr ) Till 4/4 24:00 (midnight) Using title [CN_c1] student ID _ Name 22/24
Tip: Port reuse option socket 생성이후, bind() 이전에.. int isockopt=1; //socket reuse setsockopt (serv_sock, SOL_SOCKET, SO_REUSEADDR, &isockopt,sizeof(isockopt)); 23/24
Next time, We will see more detail about socket programming 24/24