Top Banner
Socket Programming in C Socket Programming in C Kyounghee Lee [email protected] Information and Communications Univ
44

Socket Programming in C

Jan 04, 2016

Download

Documents

ulric-perez

Socket Programming in C. Kyounghee Lee [email protected] Information and Communications Univ. Outline. TCP/IP introduction TCP/IP overview Transport layer: TCP & UDP Socket fundamentals Socket address and port numbers Network byte ordering & address conversion Socket creation - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Socket Programming in C

Socket Programming in CSocket Programming in C

Kyounghee Lee

[email protected]

Information and Communications Univ

Page 2: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

OutlineOutline TCP/IP introduction

– TCP/IP overview– Transport layer: TCP & UDP

Socket fundamentals– Socket address and port numbers– Network byte ordering & address conversion– Socket creation

Socket functions– Elementary TCP socket functions– TCP client-server example– Elementary UDP socket functions– UDP client-server example

Programming assignment #01– Program description– Assignment evaluation

Page 3: Socket Programming in C

TCP/IP IntroductionTCP/IP Introduction

ICUICUInformation and Communications UniversityInformation and Communications University

Page 4: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Overview of TCP/IP ProtocolsOverview of TCP/IP Protocols

Page 5: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

UDP & TCPUDP & TCP

UDP– Datagram transmission

– Connection less: delivery guarantee (X)

– Short-term relationship between client & server

TCP– Connection-oriented: reliability, packet sequence

– Flow control & congestion control

– Full-duplex

– Long-term relationship

Page 6: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

TCP ConnectionTCP Connection

Simultaneousclose

Three-wayhandshake

Page 7: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

TCP Client-ServerTCP Client-Server

Page 8: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

UDP Client-ServerUDP Client-Server

UDP Client

socket()

sendto()

recvfrom()

close()

UDP Server

socket()

bind()

recvfrom()

sendto()

blocks until datagramreceived from a client

data(request)

process request

data(reply)

Page 9: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Common Internet ApplicationsCommon Internet Applications

Page 10: Socket Programming in C

Socket FundamentalsSocket Fundamentals

Page 11: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Socket PairSocket Pair

Socket identification– IP address + port number

TCP connection identification– Socket pair

– 4-tuple definition• IP address and port number of each endpoint• e.g.) {210.107.128.31.21, 210.107.132.195.1500}

Page 12: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Port numbersPort numbers

16-bit integer Differentiate a socket-related process from another Ranges

– Well-known ports (0 ~1023): assigned by IANA• e.g.) FTP (21), web server (80), …

– Registered ports (1024 ~ 49151): recommendation list• e.g.) X Window server (6000 ~ 6003)

– Dynamic or private ports (49152 ~ 65535)

Page 13: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Socket Address Structure (1)Socket Address Structure (1)

Generic IPv4struct sockaddr {

uint8_t sa_len;sa_family_t sa_family; /* address family: AF_XXX value */char sa_data[14]; /* protocol-specific address */

};

Posix.1gstruct in_addr {

in_addr_t s_addr; /* 32 bit IP address */ }; struct sockaddr_in {

uint8_t sin_len; /* length of structure (16) */sa_famility_t sin_family; /* AF_INET */in_port_t sin_port; /* 16 bit TCP or UDP port number */struct in_addr sin_addr; /* 32 bit IPv4 address */char sin_zero[8]; /* unused */

};

Page 14: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Socket Address Structure (2)Socket Address Structure (2)

Data types in Posix.1g

Page 15: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Byte OrderingByte Ordering

Big & little-endian byte order

• No standard between two types

Page 16: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Network Byte OrderingNetwork Byte Ordering

Exchanging multi-byte data type– Two end protocol stack must agree on the order type

– IP uses big-endian byte ordering

Byte ordering functions

Page 17: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Byte Manipulation FunctionsByte Manipulation Functions

Berkeley-derived functions

ANSI C

Page 18: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Address Conversion FunctionsAddress Conversion Functions

Convert IPv4 address– Between a dotted-decimal string and its 32-bit network byte ordered

binary value

Page 19: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Getting an Address of a SocketGetting an Address of a Socket

Function definition

• Retrieves the address binded to a socket with its descriptor

Page 20: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Socket() FunctionSocket() Function

Definition

Protocol family constants & Socket type

• Protocol argument is normally set to 0 except for raw socket

Page 21: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Socket CreationSocket Creation

Example#include <sys/types.h>#include <sys/socket.h>….int sockfd;….sockfd = socket(AF_INET, SOCK_DGRAM, 0);….

Page 22: Socket Programming in C

Socket FunctionsSocket Functions

Page 23: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Connect() FunctionConnect() Function

Definition

• Generally cast sockaddr_in with (sockaddr *)• Variable ‘errno’ is set to the corresponding error code

Page 24: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Bind() FunctionBind() Function

Definition

• Specifies a port number and an IP address for a socket• Servers generally bind their well-known port when they start• Clients let the kernel choose an ephemeral port when either connect() or listen()

is called

Page 25: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Listen() FunctionListen() Function

Definition

Two queues in the kernel for backlog– Incomplete connection queue: SYN_RCVD state– Completed connection queue: ESTABLISHED state

Page 26: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Accept() FunctionAccept() Function

Definition

• Variable cliaddr is set to the corresponding client IP address and port number after a successful return

Page 27: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Close() FunctionClose() Function

Definition

Page 28: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Basic TCP Socket I/OBasic TCP Socket I/O

Read()

# include <unistd.h>

int read(int sockfd, char *ptr, size_t nbytes);

Returns: number of bytes read, -1 on error

Write()

# include <unistd.h>

int write(int sockfd, char *ptr, size_t nbytes);

Returns: number of bytes written, -1 on error

Page 29: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Typical I/O ExampleTypical I/O Example

int readn(int fd, void *vptr, size_t n) {size_t nleft, nread;char *ptr;

ptr = vptr;nleft = n;while(nleft > 0) {

if((nread = read(fd, ptr, nleft)) < 0) {if(errno == EINTR) nread = 0;else return –1;

} else if (nread == 0)break;

nleft -= nread;ptr += nread;

}return n;

}

Page 30: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

TCP Server ExampleTCP Server Example

Outline for typical concurrent server

Page 31: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

TCP Socket DescriptorTCP Socket Descriptor

Status transition

*after return from accept

*after fork()returns

*after socketclose()

Page 32: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Functions for ConcurrencyFunctions for Concurrency

‘exec’ functions

Difference in 6 functions is– whether the file to execute is specified by a filename or pathname– whether the arguments are passed one by one or array of pointers– whether the environment of the calling process is passed or whether new

environment is specified

Page 33: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Simple TCP Server Example (1)Simple TCP Server Example (1)

TCP echo server

Page 34: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Simple TCP Server Example (2)Simple TCP Server Example (2)

‘str_echo’ function

Page 35: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Simple TCP Client ExampleSimple TCP Client Example

TCP echo client

Page 36: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Basic UDP Socket I/O (1)Basic UDP Socket I/O (1)

sendto()

# include <sys/socket.h>

int sendto(int s, const void *msg, int len, unsigned int flags, const struct sockaddr *to, int tolen);

Returns: number of bytes sent, -1 on error

recvfrom()

# include <sys/socket.h>

int recvfrom(int s, void *buf, int len, unsigned int flags, struct sockaddr *from, int *fromlen);

Returns: number of bytes received, -1 on error

Page 37: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Basic UDP Socket I/O (2)Basic UDP Socket I/O (2)

“flags” for socket I/O functions– Either 0 or formed by logically OR’ing one or more of the constants shown in the

following table

Remark– MSG_DONTROUTE: destination is in the local network– MSG_OOB: message has higher priority than in-band data– MSG_PEEK: let the received data seem to be still available to be read (do not discard

from the queue)– MSG_WAITALL:tell to kernel not to return until the request number of bytes have been

read

Flags Description recvfrom sendto

MSG_DONTROUTE

MSG_DONTWAIT

MSG_OOB

MSG_PEEK

MSG_WAITALL

Bypass routing table lookup

Socket operation is non-blocking

Send or receive out of band data

Peek at incoming message

Wait for all the data

Page 38: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Simple UDP Server ExampleSimple UDP Server Example#include <sys/socket.h>#include <sys/types.h>

int main(int argc, char **argv){ int sockfd, n, len; char msg[80]; struct sockaddr_in servaddr, cliaddr;

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(1500);

bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

len = sizeof(cliaddr); while(1) { n = recvfrom(sockfd, msg, 80, 0, (struct sockaddr *)&cliaddr, &len); sendto(sockfd, msg, n, 0, (struct sockaddr *)&cliaddr, len); }}

Page 39: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Simple UDP Client Example (1)Simple UDP Client Example (1)#include <sys/socket.h>#include <sys/types.h>#include <string.h>

int main(int argc, char **argv){ int sockfd, n; char sendline[80], recvline[80]; struct sockaddr_in servaddr;

if(argc != 2) { printf(“Usage: uecho <IP address>\n”); exit(0); }

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr(argv[1]); servaddr.sin_port = htons(1500);

Page 40: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Simple UDP Client Example (2)Simple UDP Client Example (2) while(gets(sendline) != NULL) { sendto(sockfd, sendline, strlen(sendline), 0, (struct sockaddr *)&servaddr, sizeof(servaddr);

n = recvfrom(sockfd, recvline, 80, 0, NULL, NULL);

puts(recvline); }}

Page 41: Socket Programming in C

Programming Assignment Programming Assignment #01#01

Page 42: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Program DescriptionProgram Description Baseball game

– User finds three blind numbers (1~9) given by server (e.g. 7 5 9)– User tries 12 times and server replies with X ball Y strike

(e.g. 2 5 7 1 ball & 1 strike)– If a user finds the sequence of 3 numbers before 12 tries, win!

Requirements– Multi-client support (concurrent server)– Both TCP and UDP socket should be used * UDP: request of game start (designated port, 9000), reply to the request (user full or accept with port number for connecting) * TCP: user tries & server replies for game proceeding– Use C or C++ language on UNIX/LINUX systems

Page 43: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Assignment Evaluation (1)Assignment Evaluation (1)

Due date– Mar 21, 11:00 PM– Late submission will be assessed a penalty of 10% for a day

Submission– Implementation report– Full source codes– Send an email to TA ([email protected])

Evaluation factors– Originality (‘S’ or ‘F’)– Operability (40)– Readability (30)– Efficiency (30)

Recommended reference– “UNIX Network Programming”, W. R.Stevens, Prentice Hall

Page 44: Socket Programming in C

ICE1230 – Computer Networks

ICUICUInformation and Communications UniversityInformation and Communications University

Assignment Evaluation (2)Assignment Evaluation (2)

Implementation Report– Your name and affiliation– Assignment objective

– Program functionality– Program design– Implementation environment (platform, OS, programming library, etc.)– Results

• How to compile/execute your program• Display the execution results that you have tested• Pros and cons of your implementation

– MS Word or PDF file with name of “studentID.doc” or “studentID.pdf” Source codes

– Detailed comments

– Including a ‘Makefile’– All the files should be compressed with a ‘tar’ or ‘zip’ program– The compressed file should be named with “studentID.*”