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

Slides:



Advertisements
Similar presentations
Python Socket/HTTP overmania. 목표  소켓을 이용하여 기본적인 서버 - 클라이언트 모델을 구현할 수 있다.  간단한 웹서버를 소켓을 이용하여 작성할 수 있다.
Advertisements

TCP 서버/클라이언트 동작 원리 - (1) TCP 서버/클라이언트 예 웹 서버 웹 클라이언트 웹 클라이언트
Chapter 7 ARP and RARP.
TCP/IP 통신망 특론 3장 인터넷프로토콜( IP ).
Understanding of Socket and File I/O
TCP/IP Network Experimental Programming [IPv6에 의한 통신 실험]
13장 소켓.
Chapter 06. UDP 서버/클라이언트.
22 장 프로세스간 전달 : UDP와 TCP 22.1 프로세스간 전달 22.2 사용자 데이터그램 프로토콜
TCP/IP Socket Cover Slide 조태문.
TCP/IP 소켓 프로그래밍 - C 버전 중에서
Department of Computer Engineering
Internet Control Message Protocol (ICMP)
소켓 모델 주소 지정 in_addr_t inet_addr(const char *ip_address) 연결 지향 모델 (TCP)
4장. 소켓 유형과 프로토콜 Network Lab. 이 원 구 1.
PHP 웹 프로그래밍 (PHP Web Programming) 네트워크 프로그래밍 문양세 강원대학교 IT대학 컴퓨터과학전공.
TCP/IP Socket Cover Slide 조태문.
Chapter 03. 소켓 주소 구조체 다루기.
Domain Name System (DNS)
TCP Client/Server Program
Network Lab. Seoung Hyeon, Lee
얇지만 얇지 않은 TCP/IP 소켓 프로그래밍 C 2판
호스트이름과 네트워크이름 찾기 (Hostname and Network Name Lookups)
Chapter 11. Raw 소켓.
Chapter 2 OSI 모델과 TCP/IP 프로토콜.
Internet Address Conversion Functions
3장. 소켓 주소 구조체 다루기 소켓 주소 구조체의 정의와 초기화 방법을 익힌다.
6장 비연결형 지향 프로토콜 Database Lab 강 우 석.
11 소켓 프로그래밍 기초.
인터넷 주소 변환 School of Electronics and Information. Kyung Hee University.
14장 소켓.
JAVA 프로그래밍 12장 네트워킹(Networking).
Using Standard I/O on Sockets
PART 02 프로토콜 컴퓨터 네트워크 chapter 06 트랜스포트 계층 임효택.
Department of Computer Engineering
(Web Programming & Practice)
Socket Address Structure and Byte Ordering Functions
Department of Computer Engineering
Socket Address Structure and Byte Ordering Functions
Homework 6… 12월 2일(금) 11:59pm까지 자신의 이름과 학번을 출력해 주는 유닉스/리눅스 네트워크 소켓 서버 프로그램 과 클라이언트 프로그램 을 작성해 보세요 참고 (실습1) Hello 프로그램 helloserver.c helloclient.c 컴파일.
Internet Address Conversion Functions
7장. UDP 서버-클라이언트 UDP 서버-클라이언트의 기본 구조와 동작 원리를 이해한다.
Chapter 8 연결형 프로토콜 서버 발표자 : SE Lab 황 성 하
Department of Computer Engineering
Department of Computer Engineering
Chapter 03. 소켓 주소 구조체 다루기.
Socket Address Structure and Byte Ordering Functions
Network Programming(1)
Internet Address Conversion Functions
Socket Address Structure and Byte Ordering Functions
7장. UDP 서버-클라이언트 UDP 서버-클라이언트의 기본 구조와 동작 원리를 이해한다.
네트워크와 소켓 프로그래밍 Chapter 01. * 학습목표 TCP/IP 프로토콜의 동작 원리를 개관 소켓의 기본 개념을 이해
Internet Address Conversion Functions
School of Electronics and Information. Kyung Hee University.
네트워크 프로그래밍의 이해 School of Electronics and Information.
Transmission Control Protocol (TCP)
User Datagram Protocol (UDP)
윤성우의 열혈 TCP/IP 소켓 프로그래밍 윤성우 저 열혈강의 TCP/IP 소켓 프로그래밍 개정판
Chapter 16 Socket Interface.
Department of Computer Engineering
윤성우의 열혈 TCP/IP 소켓 프로그래밍 윤성우 저 열혈강의 TCP/IP 소켓 프로그래밍 개정판
인터넷 주소변환 School of Electronics and Information. Kyung Hee University.
Operating System Multiple Access Chatting Program using Multithread
Internet & WWW Protocols
제 11장 User Datagram Protocol(UDP)
제 9 장 ICMP 9.1 메시지 유형 9.2 메시지 형식 9.3 오류 보고 9.4 질의 9.5 검사합 9.6 ICMP 설계
바이트 순서 변환 함수 주소 변환 함수 바이트 조작 함수 원격지 호스트 정보를 얻는 함수
Chapter 03. 소켓 주소 구조체 다루기.
소켓의 생성과 프로토콜의 설정 School of Electronics and Information.
Department of Computer Engineering
Presentation transcript:

컴퓨터 네트워크 PART 03 프로그래밍 (chapter 01 Socket 프로그래밍) 임효택 E-mail : htlim@dongseo.ac.kr Home page : http://kowon.dongseo.ac.kr/~htlim

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

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

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

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

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

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

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, Email, Telnet

Network Addressing Analogy PART 03 프로그래밍 Network Addressing Analogy Telephone Call Network Programming Faculty at NCST Applications/Servers 080-852-3300 ext.2201 080-852-2590 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

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 0-1023) Dynamic or private (port 1024-65535) 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

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>

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

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 */

주소 변환 함수 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’ 로 표현 시 ‘255.255.255.255’ 이므로 유효성 검사가 반드시 필요

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' 형태의 문자열로 변경 반환되는 문자열은 정적으로 할당된 버퍼에 저장 함수의 연속적인 호출은 버퍼를 중복하여 덮어 쓰므로 주의

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; /* 128.2.194.95 */ 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

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);

바이트 순서 변환 함수 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비트 기반에 네트워크 형식을 호스트 형식으로 변환하는 함수

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); }

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 */

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

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

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...

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...

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

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?

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); }

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

Dealing with IP Addresses PART 03 프로그래밍 Dealing with IP Addresses IP Addresses are commonly written as strings (“128.2.35.50”), but programs deal with IP addresses as integers. Converting strings to numerical address: struct sockaddr_in srv; srv.sin_addr.s_addr = inet_addr(“172.2.1.50”); 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); }

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 = “www.ncb.ernet.in”; peeraddr.sin_family = AF_INET; hp = gethostbyname(name) peeraddr.sin_addr.s_addr = ((struct in_addr*)(hp->h_addr))->s_addr;

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 “128.2.35.50” */ srv.sin_addr.s_addr = inet_addr(“128.2.35.50”); if(connect(fd, (struct sockaddr*) &srv, sizeof(srv)) < 0) { perror(”connect"); exit(1); }

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); }

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 */

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()

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

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

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…

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); }

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

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

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 “128.2.35.50” port 80 */ srv.sin_family = AF_INET; srv.sin_port = htons(80); srv.sin_addr.s_addr = inet_addr(“128.2.35.50”); nbytes = sendto(fd, buf, sizeof(buf), 0 /* flags */, (struct sockaddr*) &srv, sizeof(srv)); if(nbytes < 0) { perror(“sendto”); exit(1); }

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()

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

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?