Presentation is loading. Please wait.

Presentation is loading. Please wait.

컴퓨터 네트워크 PART 03 프로그래밍 (chapter 01 Socket 프로그래밍) 임효택

Similar presentations


Presentation on theme: "컴퓨터 네트워크 PART 03 프로그래밍 (chapter 01 Socket 프로그래밍) 임효택"— Presentation transcript:

1 컴퓨터 네트워크 PART 03 프로그래밍 (chapter 01 Socket 프로그래밍) 임효택
Home page :

2 Chapter 01 Socket 프로그래밍 TCP/IP 프로그래밍 기초
PART 03 프로그래밍 TCP/IP 프로그래밍 기초 1.1.1 연결(Association) 클라이언트와 서버간의 정보 교환이 이루어지기 전에 요구되는 다섯가지 정보 프로토콜 식별자 로컬 인터넷 주소 로컬 포트 번호 원격 인터넷 주소 원격 포트 번호 1.1.2 트랜스포트 계층 프로토콜 포트 주어진 호스트에 TCP/IP 트랜스포트 계층 프로토콜의 서비스를 사용하는 각 프로세스는 하나의 포트 번호가 할당 된다. 포트 0 : 사용되지 않음 포트 : 잘알려진(well-known) 포트 번호 포트 : 예약된(reserved) 포트 번호 포트 : 잠시 사용하는 클라이언트 포트 번호 포트 : 사용자 정의 서버 포트 번호

3 Chapter 01 Socket 프로그래밍 Socket 시스템 호출 RPC 기능 TLI
PART 03 프로그래밍 1.1.3 통신 응용 프로그램 인터페이스(API) Socket 시스템 호출 RPC 기능 TLI Socket 인터페이스는 보통 두개의 응용 프로그램이 다른 컴퓨팅 시스템 에서 실행 될 때 이들 간에 클라이언트서버 관계를 구현하기 위해 사용. Socket API는 TCP/IP 이외의 프로토콜에 대한 접근을 제공하기 위해 사용.

4 Chapter 01 Socket 프로그래밍 Socket의 세 가지 형태
PART 03 프로그래밍 Socket의 세 가지 형태 1.2.1 stream socket TCP 트랜스포트 계층 프로토콜을 사용하여 통신하는 소켓 연결-지향 형태를 지원 1.2.2 데이터그램 소켓 UDP 트랜스포트 계층 프로토콜을 사용하여 통신하는 소켓 신뢰적이지 못한 데이터그램 형태를 지원 1.2.3 원시 소켓 하위의 IP와 ICMP로의 접근을 제공하는 소켓 특정 목적을 위해 사용

5 Chapter 01 Socket 프로그래밍 응용 프로토콜 비연결 응용 프로토콜을 구현하는 클라이언트-서버 응용은 UDP를 이용
PART 03 프로그래밍 응용 프로토콜 1.3.1 비연결(Connectionless) 응용 프로토콜 비연결 응용 프로토콜을 구현하는 클라이언트-서버 응용은 UDP를 이용 하여 통신하는 데이터그램 소켓을 사용한다. 1.3.2 연결-지향 (Connection-oriented) 응용 프로토콜 연결-지향 응용 프로토콜을 구현하는 클라이언트-서버 응용은 TCP 연결 상에서 통신하기 위하여 스트림 소켓을 이용

6 PART 03 프로그래밍 Server and Client TCP/UDP IP Ethernet Adapter Server Clients Server and Client exchange messages over the network through a common Socket API Socket API hardware kernel space user ports

7 User Datagram Protocol(UDP): An Analogy
PART 03 프로그래밍 User Datagram Protocol(UDP): An Analogy UDP Single socket to receive messages No guarantee of delivery Not necessarily in-order delivery Datagram – independent packets Must address each packet Postal Mail Single mailbox to receive messages Unreliable  Not necessarily in-order delivery Each letter is independent Must address each reply Example UDP applications Multimedia, voice over IP

8 Example TCP applications
PART 03 프로그래밍 TCP: An Analogy TCP Reliable – guarantee delivery Byte stream – in-order delivery Connection-oriented – single socket per connection Setup connection followed by data transfer Telephone Call Guaranteed delivery In-order delivery Connection-oriented Setup connection followed by conversation Example TCP applications Web, , Telnet

9 Network Addressing Analogy
PART 03 프로그래밍 Network Addressing Analogy Telephone Call Network Programming Faculty at NCST Applications/Servers ext.2201 ext.2202 Web Port 80 Mail Port 25 Extension Port No. Telephone No IP Address Central Number Network No. Exchange Host Number Area Code PGDST Students Clients

10 Concept of Port Numbers
PART 03 프로그래밍 Concept of Port Numbers Port numbers are used to identify “entities” on a host Port numbers can be Well-known (port ) Dynamic or private (port ) Servers/daemons usually use well-known ports Any client can identify the server/service HTTP = 80, FTP = 21, Telnet = 23, ... /etc/service defines well-known ports Clients usually use dynamic ports Assigned by the kernel at run time NTP daemon Web server port 123 port 80 TCP/UDP IP Ethernet Adapter

11 POSIX data types DATATYPES DESCRIPTION HEADER int8_t uint8_t int16_t
PART 03 프로그래밍 POSIX data types DATATYPES DESCRIPTION HEADER int8_t uint8_t int16_t uint16_t int32_t uint32_t Signed 8-bit integer Unsigned 8-bit integer Signed 16-bit integer Unsigned 16-bit integer Signed 32-bit integer <sys/types.h> sa_family_t socklen_t Address family of socket address structure Length of socket address structure. (uint32_t) <sys/socket.h> in_addr_t in_port_t IPv4 address. (uint32_t) TCP/UDP port. (uint16_t) <netinet/in.h>

12 Internet Addressing Data Structure
PART 03 프로그래밍 Internet Addressing Data Structure #include <netinet/in.h> /* Internet address structure */ struct in_addr { u_long s_addr; /* 32-bit IPv4 address */ }; /* network byte ordered */ /* Socket address, Internet style. */ struct sockaddr_in { u_char sin_family; /* Address Family */ u_short sin_port; /* UDP or TCP Port# */ /* network byte ordered */ struct in_addr sin_addr; /* Internet Address */ char sin_zero[8]; /* unused */ }; sin_family = AF_INET selects Internet address family

13 Address Conversion Functions
PART 03 프로그래밍 Address Conversion Functions #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int inet_aton(const char* strptr, struct in_addr* addrptr); /* Returns non-zero value if valid; otherwise 0 */ in_addr_t inetaddr(const char* strptr); /* Returns 32-bit binary network byte ordered IPv4 address; INADDR_NONE if error. Deprecated */ char* inet_ntoa(struct in_addr inaddr); /* Returns pointer to dotted-decimal string */

14 주소 변환 함수 unsigned long int inet_addr (const char * strptr);
PART 03 프로그래밍 주소 변환 함수 32비트 이진 바이너리 주소를 ‘Dotted Decimal' 형식의 문자열로 또는 그 반대로 변환하여 주는 기능 unsigned long int inet_addr (const char * strptr); ‘Dotted Decimal' 문자열 형태의 주소를 네트워크 바이트 순서를 갖는 이진 바이너리로 바꾸는 함수 입력 값이 적절치 못할 경우 INADDR_NONE('-1')을 반환 ’-1‘은 ’Dotted Decimal’ 로 표현 시 ‘ ’ 이므로 유효성 검사가 반드시 필요

15 int inet_aton (const char * strptr, struct in_addr * addrptr);
PART 03 프로그래밍 int inet_aton (const char * strptr, struct in_addr * addrptr); 'Dotted Decimal' 형태의 문자열을 바이너리 형태로 바꾸는 함수 ‘strptr’ 로 들어온 ‘Dotted Decimal' 형태의 문자열은 변환되어 'in_addr' 타입의 ’addrptr‘ 에 저장됨 - 주소가 올바르다면 ‘0’ 이 아닌 값, 그렇지 않다면 ‘0’ 을 반환 char * inet_ntoa (struct in_addr inaddr);  'in_addr' 형의 바이너리 주소 ‘inaddr’을  ‘Dotted Decimal' 형태의 문자열로 변경 반환되는 문자열은 정적으로 할당된 버퍼에 저장 함수의 연속적인 호출은 버퍼를 중복하여 덮어 쓰므로 주의

16 Byte Ordering c[0] c[1] c[2] c[3] union {
PART 03 프로그래밍 Byte Ordering union { u_int32_t addr; /* 4 bytes address */ char c[4]; } un; /* */ un.addr = 0x8002c25f; /* c[0] = ? */ c[0] c[1] c[2] c[3] Big Endian Sun Solaris, PowerPC, ... Little Endian i386, alpha, ... 128 2 194 95 95 194 2 128

17 Byte Ordering Functions
PART 03 프로그래밍 Byte Ordering Functions Converts between host byte order and network byte order ‘h’ = host byte order ‘n’ = network byte order ‘l’ = long (4 bytes), converts IP addresses ‘s’ = short (2 bytes), converts port numbers #include <netinet/in.h> unsigned long int htonl(unsigned long int hostlong); unsigned short int htons(unsigned short int hostshort); unsigned long int ntohl(unsigned long int netlong); unsigned short int ntohs(unsigned short int netshort);

18 바이트 순서 변환 함수 unsigned short int htons (unsigned short int hostshort);
PART 03 프로그래밍 바이트 순서 변환 함수 unsigned short int htons (unsigned short int hostshort); 16비트 기반에 호스트 형식을 네트워크 형식으로 변환하는 함수 unsigned long int htonl (unsigned  long int hostlong); 32비트 기반에 호스트 형식을 네트워크 형식으로 변환하는 함수 unsigned short int ntohs (unsigned short int netshort); - 16비트 기반에 네트워크 형식을 호스트 형식으로 변환하는 함수 unsigned long int  ntohl (unsigned long int netlong); - 32비트 기반에 네트워크 형식을 호스트 형식으로 변환하는 함수

19 PART 03 프로그래밍 What is a Socket? A socket is a file descriptor that lets an application read/write data from/to the network socket returns an integer (socket descriptor) fd < 0 indicates that an error occurred socket descriptors are similar to file descriptors AF_INET: associates a socket with the Internet protocol family SOCK_STREAM: selects the TCP protocol SOCK_DGRAM: selects the UDP protocol int fd; /* socket descriptor */ if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) } perror(“socket”); exit(1); }

20 Socket Address Structure
PART 03 프로그래밍 Socket Address Structure struct sockaddr { sa_family_t sa_family; /* Address Family, AF_XXX */ char sa_data[14]; /* 14 bytes of protocol address */ }; struct sockaddr_in { sa_family_t sin_family; /* AF_INET */ in_port sin_port; /* Port Number */ struct in_addr sin_addr; char sin_zero[8]; /* Not used; 0 */ struct in_addr { in_addr_t s_addr; } /* 32 bit IPv4 address network byte ordered */

21 TCP Server For example: web server Web Server Port 80 TCP IP
PART 03 프로그래밍 TCP Server For example: web server What does a web server need to do so that a web client can connect to it? Web Server Port 80 TCP IP Ethernet Adapter

22 PART 03 프로그래밍 Socket I/O: socket() Since web traffic uses TCP, the web server must create a socket of type SOCK_STREAM int fd; /* socket descriptor */ if((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror(“socket”); exit(1); } socket returns an integer (socket descriptor) fd < 0 indicates that an error occurred AF_INET associates a socket with the Internet protocol family SOCK_STREAM selects the TCP protocol

23 Socket I/O: bind() A socket can be bound to a port
PART 03 프로그래밍 Socket I/O: bind() A socket can be bound to a port int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by bind() */ /* create the socket */ srv.sin_family = AF_INET; /* use the Internet addr family */ srv.sin_port = htons(80); /* bind socket ‘fd’ to port 80*/ /* bind: a client may connect to any of my addresses */ srv.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(fd, (struct sockaddr*) &srv, sizeof(srv)) < 0) { perror("bind"); exit(1); } Still not quite ready to communicate with a client...

24 PART 03 프로그래밍 Socket I/O: listen() listen indicates that the server will accept a connection int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by bind() */ /* 1) create the socket */ /* 2) bind the socket to a port */ if(listen(fd, 5) < 0) { perror(“listen”); exit(1); } Still not quite ready to communicate with a client...

25 Socket I/O: accept() accept blocks waiting for a connection
PART 03 프로그래밍 Socket I/O: accept() accept blocks waiting for a connection int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by bind() */ struct sockaddr_in cli; /* used by accept() */ int newfd; /* returned by accept() */ int cli_len = sizeof(cli); /* used by accept() */ /* 1) create the socket */ /* 2) bind the socket to a port */ /* 3) listen on the socket */ newfd = accept(fd, (struct sockaddr*) &cli, &cli_len); if(newfd < 0) { perror("accept"); exit(1); } accept returns a new socket (newfd) with the same properties as the original socket (fd) newfd < 0 indicates that an error occurred

26 Socket I/O: accept() continued...
PART 03 프로그래밍 Socket I/O: accept() continued... struct sockaddr_in cli; /* used by accept() */ int newfd; /* returned by accept() */ int cli_len = sizeof(cli); /* used by accept() */ newfd = accept(fd, (struct sockaddr*) &cli, &cli_len); if(newfd < 0) { perror("accept"); exit(1); } How does the server know which client it is? cli.sin_addr.s_addr contains the client’s IP address cli.sin_port contains the client’s port number Now the server can exchange data with the client by using read and write on the descriptor newfd. Why does accept need to return a new descriptor?

27 Socket I/O: read() read can be used with a socket
PART 03 프로그래밍 Socket I/O: read() read can be used with a socket read blocks waiting for data from the client but does not guarantee that sizeof(buf) is read int fd; /* socket descriptor */ char buf[512]; /* used by read() */ int nbytes; /* used by read() */ /* 1) create the socket */ /* 2) bind the socket to a port */ /* 3) listen on the socket */ /* 4) accept the incoming connection */ if((nbytes = read(newfd, buf, sizeof(buf))) < 0) { perror(“read”); exit(1); }

28 TCP Client For example: web client 2 Web Clients TCP IP
PART 03 프로그래밍 TCP Client For example: web client How does a web client connect to a web server? 2 Web Clients TCP IP Ethernet Adapter

29 Dealing with IP Addresses
PART 03 프로그래밍 Dealing with IP Addresses IP Addresses are commonly written as strings (“ ”), but programs deal with IP addresses as integers. Converting strings to numerical address: struct sockaddr_in srv; srv.sin_addr.s_addr = inet_addr(“ ”); if(srv.sin_addr.s_addr == (in_addr_t) -1) { fprintf(stderr, "inet_addr failed!\n"); exit(1); } Converting a numerical address to a string: struct sockaddr_in srv; char *t = inet_ntoa(srv.sin_addr); if(t == 0) { fprintf(stderr, “inet_ntoa failed!\n”); exit(1); }

30 Translating Names to Addresses
PART 03 프로그래밍 Translating Names to Addresses Gethostbyname provides interface to DNS Additional useful calls Gethostbyaddr – returns hostent given sockaddr_in Getservbyname Used to get service description (typically port number) Returns servent based on name #include <netdb.h> struct hostent *hp; /*ptr to host info for remote*/ struct sockaddr_in peeraddr; char *name = “ peeraddr.sin_family = AF_INET; hp = gethostbyname(name) peeraddr.sin_addr.s_addr = ((struct in_addr*)(hp->h_addr))->s_addr;

31 PART 03 프로그래밍 Socket I/O: connect() connect allows a client to connect to a server... int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by connect() */ /* create the socket */ /* connect: use the Internet address family */ srv.sin_family = AF_INET; /* connect: socket ‘fd’ to port 80 */ srv.sin_port = htons(80); /* connect: connect to IP Address “ ” */ srv.sin_addr.s_addr = inet_addr(“ ”); if(connect(fd, (struct sockaddr*) &srv, sizeof(srv)) < 0) { perror(”connect"); exit(1); }

32 Socket I/O: write() write can be used with a socket
PART 03 프로그래밍 Socket I/O: write() write can be used with a socket int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by connect() */ char buf[512]; /* used by write() */ int nbytes; /* used by write() */ /* 1) create the socket */ /* 2) connect() to the server */ /* Example: A client could “write” a request to a server */ if((nbytes = write(fd, buf, sizeof(buf))) < 0) { perror(“write”); exit(1); }

33 Socket I/O: close() Used to close a connection on socket descriptor
PART 03 프로그래밍 Socket I/O: close() Used to close a connection on socket descriptor close(sockfd); /* Prevents any more read or write on the socket */ int shoutdown(int sockfd, int how); /* 0 – No further read allowed */ /* 1 – No further write allowed */ /* 2 – No further read or write allowed */ /* Returns 0 on success; otherwise –1 */

34 TCP Client-Server Interaction
PART 03 프로그래밍 TCP Client-Server Interaction TCP Server socket() bind() TCP Client listen() socket() accept() connection establishment connect() data request read() write() data reply write() read() end-of-file notification read() close() close()

35 UDP Server Example For example: NTP daemon NTP daemon Port 123 UDP IP
PART 03 프로그래밍 UDP Server Example For example: NTP daemon What does a UDP server need to do so that a UDP client can connect to it? NTP daemon Port 123 UDP IP Ethernet Adapter

36 Socket I/O: socket() The UDP server must create a datagram socket…
PART 03 프로그래밍 Socket I/O: socket() The UDP server must create a datagram socket… int fd; /* socket descriptor */ if((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror(“socket”); exit(1); } socket returns an integer (socket descriptor) fd < 0 indicates that an error occurred AF_INET: associates a socket with the Internet protocol family SOCK_DGRAM: selects the UDP protocol

37 Socket I/O: bind() A socket can be bound to a port
PART 03 프로그래밍 Socket I/O: bind() A socket can be bound to a port int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by bind() */ /* create the socket */ /* bind: use the Internet address family */ srv.sin_family = AF_INET; /* bind: socket ‘fd’ to port 80*/ srv.sin_port = htons(80); /* bind: a client may connect to any of my addresses */ srv.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(fd, (struct sockaddr*) &srv, sizeof(srv)) < 0) { perror("bind"); exit(1); } Now the UDP server is ready to accept packets…

38 Socket I/O: recvfrom()
PART 03 프로그래밍 Socket I/O: recvfrom() read does not provide the client’s address to the UDP server int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by bind() */ struct sockaddr_in cli; /* used by recvfrom() */ char buf[512]; /* used by recvfrom() */ int cli_len = sizeof(cli); /* used by recvfrom() */ int nbytes; /* used by recvfrom() */ /* 1) create the socket */ /* 2) bind to the socket */ nbytes = recvfrom(fd, buf, sizeof(buf), 0 /* flags */, (struct sockaddr*) &cli, &cli_len); if(nbytes < 0) { perror(“recvfrom”); exit(1); }

39 Socket I/O: recvfrom() continued...
PART 03 프로그래밍 Socket I/O: recvfrom() continued... nbytes = recvfrom(fd, buf, sizeof(buf), 0 /* flags */, (struct sockaddr*) cli, &cli_len); The actions performed by recvfrom returns the number of bytes read (nbytes) copies nbytes of data into buf returns the address of the client (cli) returns the length of cli (cli_len) don’t worry about flags

40 UDP Client Example 2 UDP Clients ports TCP IP Ethernet Adapter
PART 03 프로그래밍 UDP Client Example How does a UDP client communicate with a UDP server? 2 UDP Clients ports TCP IP Ethernet Adapter

41 Socket I/O: sendto() int fd; /* socket descriptor */
PART 03 프로그래밍 Socket I/O: sendto() write is not allowed Notice that the UDP client does not bind a port number a port number is dynamically assigned when the first sendto is called int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by sendto() */ /* 1) create the socket */ /* sendto: send data to IP Address “ ” port 80 */ srv.sin_family = AF_INET; srv.sin_port = htons(80); srv.sin_addr.s_addr = inet_addr(“ ”); nbytes = sendto(fd, buf, sizeof(buf), 0 /* flags */, (struct sockaddr*) &srv, sizeof(srv)); if(nbytes < 0) { perror(“sendto”); exit(1); }

42 UDP Client-Server Interaction
PART 03 프로그래밍 UDP Client-Server Interaction UDP Server socket() bind() UDP Client recvfrom() socket() blocks until datagram received from a client sendto() data request data reply sendto() recvfrom() close()

43 The UDP Server UDP Server Port 3000 Port 2000 UDP IP Ethernet Adapter
PART 03 프로그래밍 The UDP Server UDP Server How can the UDP server service multiple ports simultaneously? Port 3000 Port 2000 UDP IP Ethernet Adapter

44 UDP Server: Servicing Two Ports
PART 03 프로그래밍 UDP Server: Servicing Two Ports int s1; /* socket descriptor 1 */ int s2; /* socket descriptor 2 */ /* 1) create socket s1 */ /* 2) create socket s2 */ /* 3) bind s1 to port 2000 */ /* 4) bind s2 to port 3000 */ while(1) { recvfrom(s1, buf, sizeof(buf), ...); /* process buf */ recvfrom(s2, buf, sizeof(buf), ...); } What problems does this code have?


Download ppt "컴퓨터 네트워크 PART 03 프로그래밍 (chapter 01 Socket 프로그래밍) 임효택"

Similar presentations


Ads by Google