np sockets

70
1 Netprog: Sockets API Sockets Programming Sockets Programming

Upload: om18sahu

Post on 12-Nov-2014

134 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: NP Sockets

1Netprog: Sockets API

Sockets ProgrammingSockets Programming

Page 2: NP Sockets

2Netprog: Sockets API

Network Application Network Application Programming Interface (API)Programming Interface (API)

• The services provided (often by the operating The services provided (often by the operating system) that provide the interface between system) that provide the interface between application and protocol software.application and protocol software.

ApplicationApplication

Network APINetwork API

Protocol AProtocol A Protocol BProtocol B Protocol CProtocol C

Page 3: NP Sockets

3Netprog: Sockets API

Network API wish listNetwork API wish list

• Generic Programming Interface.Generic Programming Interface.

• Support for message oriented and Support for message oriented and connection oriented communication.connection oriented communication.

• Work with existing I/O services (when Work with existing I/O services (when this makes sense).this makes sense).

• Operating System independence.Operating System independence.

• Presentation layer servicesPresentation layer services

Page 4: NP Sockets

4Netprog: Sockets API

Generic Programming Generic Programming InterfaceInterface

• Support multiple communication Support multiple communication protocol suites (families).protocol suites (families).

• Address (endpoint) representation Address (endpoint) representation independence.independence.

• Provide special services for Client and Provide special services for Client and Server?Server?

Page 5: NP Sockets

5Netprog: Sockets API

TCP/IPTCP/IP

• TCP/IP does not include an API TCP/IP does not include an API definition.definition.

• There are a variety of APIs for use with There are a variety of APIs for use with TCP/IP:TCP/IP:– SocketsSockets– WinsockWinsock– MacTCPMacTCP

Page 6: NP Sockets

6Netprog: Sockets API

Functions needed:Functions needed:

• Specify local and remote Specify local and remote communication endpointscommunication endpoints

• Initiate a connectionInitiate a connection

• Wait for incoming connectionWait for incoming connection

• Send and receive dataSend and receive data

• Terminate a connection gracefullyTerminate a connection gracefully

• Error handlingError handling

Page 7: NP Sockets

7Netprog: Sockets API

Berkeley SocketsBerkeley Sockets

• Generic:Generic:– support for multiple protocol families.support for multiple protocol families.– address representation independenceaddress representation independence

• Uses existing I/O programming interface Uses existing I/O programming interface as much as possible.as much as possible.

Page 8: NP Sockets

8Netprog: Sockets API

SocketSocket

• A socket is an abstract representation A socket is an abstract representation of a communication endpoint.of a communication endpoint.

• Sockets work with Unix I/O services Sockets work with Unix I/O services just like files, pipes & FIFOs.just like files, pipes & FIFOs.

• Sockets (obviously) have special needs:Sockets (obviously) have special needs:– establishing a connectionestablishing a connection– specifying communication endpoint specifying communication endpoint

addressesaddresses

Page 9: NP Sockets

9Netprog: Sockets API

Unix Descriptor TableUnix Descriptor TableDescriptor TableDescriptor Table

0

1

2

3

4

Data structure for file 0Data structure for file 0

Data structure for file 1Data structure for file 1

Data structure for file 2Data structure for file 2

Page 10: NP Sockets

10Netprog: Sockets API

Socket Descriptor Data Socket Descriptor Data StructureStructure

Descriptor TableDescriptor Table

0

1

2

3

4

Family: PF_INETFamily: PF_INETService: SOCK_STREAMService: SOCK_STREAMLocal IP: 111.22.3.4Local IP: 111.22.3.4Remote IP: 123.45.6.78Remote IP: 123.45.6.78Local Port: 2249Local Port: 2249Remote Port: 3726Remote Port: 3726

Family: PF_INETFamily: PF_INETService: SOCK_STREAMService: SOCK_STREAMLocal IP: 111.22.3.4Local IP: 111.22.3.4Remote IP: 123.45.6.78Remote IP: 123.45.6.78Local Port: 2249Local Port: 2249Remote Port: 3726Remote Port: 3726

Page 11: NP Sockets

11Netprog: Sockets API

Creating a SocketCreating a Socket

int socket(int family,int type,int proto);int socket(int family,int type,int proto);

• familyfamily specifies the protocol family specifies the protocol family ((PF_INETPF_INET for TCP/IP). for TCP/IP).

• typetype specifies the type of service specifies the type of service ((SOCK_STREAMSOCK_STREAM, , SOCK_DGRAMSOCK_DGRAM).).

• protocolprotocol specifies the specific protocol specifies the specific protocol (usually 0, which means (usually 0, which means the defaultthe default).).

Page 12: NP Sockets

12Netprog: Sockets API

socket()socket()

• The The socket()socket() system call returns a system call returns a socket descriptor (small integer) or -1 socket descriptor (small integer) or -1 on error.on error.

• socket()socket() allocates resources needed allocates resources needed for a communication endpoint - but it for a communication endpoint - but it does not deal with endpoint addressing.does not deal with endpoint addressing.

Page 13: NP Sockets

13Netprog: Sockets API

Specifying an Endpoint Specifying an Endpoint AddressAddress

• Remember that the sockets API is Remember that the sockets API is generic.generic.

• There must be a generic way to specify There must be a generic way to specify endpoint addresses.endpoint addresses.

• TCP/IP requires an IP address and a TCP/IP requires an IP address and a port number for each endpoint address.port number for each endpoint address.

• Other protocol suites (families) may use Other protocol suites (families) may use other schemes.other schemes.

Page 14: NP Sockets

14Netprog: Sockets API

Necessary Background Information: Necessary Background Information: POSIX data typesPOSIX data types

int8_tint8_t signed 8bit intsigned 8bit intuint8_tuint8_t unsigned 8 bit intunsigned 8 bit intint16_tint16_t signed 16 bit intsigned 16 bit intuint16_tuint16_t unsigned 16 bit intunsigned 16 bit intint32_tint32_t signed 32 bit intsigned 32 bit intuint32_tuint32_t unsigned 32 bit intunsigned 32 bit int

u_char, u_short, u_int, u_longu_char, u_short, u_int, u_long

Page 15: NP Sockets

15Netprog: Sockets API

More POSIX data typesMore POSIX data types

sa_family_tsa_family_t address familyaddress family

socklen_tsocklen_t length of structlength of struct

in_addr_tin_addr_t IPv4 addressIPv4 address

in_port_tin_port_t IP port numberIP port number

Page 16: NP Sockets

16Netprog: Sockets API

Overview of Socket InterfaceOverview of Socket Interface

• Client-server modelClient-server model– local system (a client)local system (a client)– remote system (a server)remote system (a server)

• These two machines need to communicate with one anotherThese two machines need to communicate with one another• socket provide a standard interface, API, for programmer to socket provide a standard interface, API, for programmer to

write client-server applicationswrite client-server applications– declarationsdeclarations– definitionsdefinitions– proceduresprocedures

• There are several APIsThere are several APIs– socket interfacesocket interface– TLI (transport level interface)TLI (transport level interface)– RPC (remote procedure call)RPC (remote procedure call)

we only concentratesocket interface

Page 17: NP Sockets

17Netprog: Sockets API

Data types and Data structuresData types and Data structures

• 3 data types commonly used3 data types commonly used– u_char unsigned 8-bit characteru_char unsigned 8-bit character– u_short unsigned 16-bit integeru_short unsigned 16-bit integer– u_long unsigned 32-bit integeru_long unsigned 32-bit integer

• Internet AddressInternet Address– IPv4 define a structure call IPv4 define a structure call in_addrin_addr– 32 bit binary number32 bit binary number– struct in_addrstruct in_addr

{ { u_long s_addr;u_long s_addr;

}}

Page 18: NP Sockets

18Netprog: Sockets API

Internet Socket Address StructureInternet Socket Address Structure

• TCP/IP protocol suite need a structure called socket address to TCP/IP protocol suite need a structure called socket address to holds IP address, port number, protocol type and protocol familyholds IP address, port number, protocol type and protocol family

• A socket is an abstract representation of a communication A socket is an abstract representation of a communication endpoint.endpoint.– acts a an end-portacts a an end-port– two processes need a socket at each end to communicate with each two processes need a socket at each end to communicate with each

otherother

• Sockets work with Unix I/O services just like files, pipes & FIFOs.Sockets work with Unix I/O services just like files, pipes & FIFOs.• Socket structureSocket structure

– familyfamily– typetype– protocolprotocol– local socket addresslocal socket address– remote socket addressremote socket address

start from socketaddress

Page 19: NP Sockets

19Netprog: Sockets API

Internet socket address Internet socket address structurestructure

• Struct sockaddr_inStruct sockaddr_in

{{u_charu_char sin_len;sin_len;

u_shortu_short sin_family;sin_family;

u_shortu_short sin_port;sin_port;

struct in_addrstruct in_addr sin_addr;sin_addr;

charchar sin_zero[8];sin_zero[8];

}}

sin_len sin_family sin_port sin_addr sin_zero

Page 20: NP Sockets

20Netprog: Sockets API

Socket structureSocket structure• Socket structure (it is a bigger picture!!)Socket structure (it is a bigger picture!!)

– familyfamily– typetype– protocolprotocol– local socket addresslocal socket address– remote socket addressremote socket address

sin_len sin_family sin_port sin_addr sin_zero

sin_len sin_family sin_port sin_addr sin_zero

Family Type Protocol

local

remote

Page 21: NP Sockets

21Netprog: Sockets API

Socket typesSocket types

• three typesthree types– stream socketstream socket

• connection-oriented protcol such as TCPconnection-oriented protcol such as TCP• TCP uses a pair of stream sockets to connect one application program to anther over the InternetTCP uses a pair of stream sockets to connect one application program to anther over the Internet

– datagram socketdatagram socket• connectionless protocol such as UDPconnectionless protocol such as UDP• UDP uses a pair of datagram sockets to send message from one applications program to another over UDP uses a pair of datagram sockets to send message from one applications program to another over

the Internetthe Internet

– raw socketraw socket• designed for services and application such as ICMP or OSFP designed for services and application such as ICMP or OSFP

Page 22: NP Sockets

22Netprog: Sockets API

Socket typesSocket types

Physical and data link layers

IP

TCP UDP

application programstreamsocketinterface

datagramsocketinterface

raw socketinterface

Page 23: NP Sockets

23Netprog: Sockets API

overview of API functionsoverview of API functions

• byte order transformation (byte order transformation (htons, htonl, ntohs htons, htonl, ntohs and ntohl)and ntohl)

• address transformation (inet_aton, inet_ntoa)address transformation (inet_aton, inet_ntoa)• byte manipulation (memset, memcpy, byte manipulation (memset, memcpy,

memcmp)memcmp)• get information about remote host get information about remote host

(gethostbyname)(gethostbyname)• socket system calls (socket, bind, connect, socket system calls (socket, bind, connect,

listen, accept, sendto, recvfrom, read, write, listen, accept, sendto, recvfrom, read, write, close)close)

Page 24: NP Sockets

24Netprog: Sockets API

Byte orderingByte ordering

• two typestwo types– big-endianbig-endian

• MSB firstMSB first

– little-endian little-endian • LSB firstLSB first

• IP address use big-endianIP address use big-endian– MSB firstMSB first

• To create portability in applications program, API provides To create portability in applications program, API provides a set of functions that transforms integers from a host byte a set of functions that transforms integers from a host byte order (big endian or little endian) to network type order (big order (big endian or little endian) to network type order (big endian)endian)

• Four functions are providedFour functions are provided– htons, htonl, ntohs and ntohlhtons, htonl, ntohs and ntohl

Page 25: NP Sockets

25Netprog: Sockets API

Byte order transformationByte order transformation

• u_short htons(u_short host_short)u_short htons(u_short host_short)– function function hhost to ost to nnetwork etwork sshort convert 16-bit integer from hort convert 16-bit integer from

host byte order to network byte orderhost byte order to network byte order

• u_short ntohs(u_short network_short)u_short ntohs(u_short network_short)– function function nnetwork to etwork to hhost ost sshort convert 16-bit integer from hort convert 16-bit integer from

host byte order to network byte orderhost byte order to network byte order

• u_long htonl(u_short host_long)u_long htonl(u_short host_long)– function function hhost to ost to nnetwork etwork llong convert 32-bit integer from ong convert 32-bit integer from

host byte order to network byte orderhost byte order to network byte order

• u_long ntohl(u_short network_long)u_long ntohl(u_short network_long)– function function nnetwork to etwork to hhost ost llong convert 32-bit integer from ong convert 32-bit integer from

network byte order to host byte ordernetwork byte order to host byte order

Page 26: NP Sockets

26Netprog: Sockets API

Byte order transformationByte order transformation

host byte order

htons ntons

16-bit 32-bit

network byte order16-bit 32-bit

htonl ntohl

Page 27: NP Sockets

27Netprog: Sockets API

Address transformationAddress transformation

• transform an IP address ASCII dotted decimal format to 32-bit transform an IP address ASCII dotted decimal format to 32-bit binary format and vice versabinary format and vice versa– int inet_aton(const char *strptr, struct in_addr *addrptr)int inet_aton(const char *strptr, struct in_addr *addrptr)

• transforms an ASCII string contains 4 segment separated by dots to a 32-transforms an ASCII string contains 4 segment separated by dots to a 32-bit binary address in network byte orderbit binary address in network byte order

– char *inet_nota(struct in_addr inaddr)char *inet_nota(struct in_addr inaddr)• transforms a 32bit binary address in network byte order to an ASCII string transforms a 32bit binary address in network byte order to an ASCII string

with 4 segments separated by dots.with 4 segments separated by dots.

32 bit binary address

inet_ntoa

dotted decimal address

inet_aton

Page 28: NP Sockets

28Netprog: Sockets API

byte manipulationbyte manipulation

• In network programming, we often need to initialize a In network programming, we often need to initialize a field, copy the contents of one field to another, or field, copy the contents of one field to another, or compare the contents of two fieldscompare the contents of two fields

• memsetmemset– void *memset(void *dest, int chr,int len);void *memset(void *dest, int chr,int len);– e.g memset(&x, 0, sizeof(x));e.g memset(&x, 0, sizeof(x));

• memcpymemcpy– void *memcpy(void *dest, const void *src, int len);void *memcpy(void *dest, const void *src, int len);– e.g. memcpy(&x, &y, sizeof(x));e.g. memcpy(&x, &y, sizeof(x));

• memcmpmemcmp– int memcmp (const void *first, const void *second, int len);int memcmp (const void *first, const void *second, int len);– e.g. memcmp(&x, &y, 10);e.g. memcmp(&x, &y, 10);

Page 29: NP Sockets

29Netprog: Sockets API

information about remote hostinformation about remote host

• In many instances, it is necessary to get In many instances, it is necessary to get information about a remote hostinformation about a remote host– struct hostent *gethostbyname(const char *hostname);struct hostent *gethostbyname(const char *hostname);– call to the DNS, this function accepts the domain name call to the DNS, this function accepts the domain name

of the host and returns structured information called of the host and returns structured information called hostent, a pointer to the hostent structure hostent, a pointer to the hostent structure

– struct hostentstruct hostent{{

char *h_name;char *h_name;char **h_aliases;char **h_aliases;int h_addrtype;int h_addrtype;int h_length;int h_length;char **h_addr_list;char **h_addr_list;

}}

Page 30: NP Sockets

30Netprog: Sockets API

Socket System CallsSocket System Calls

Page 31: NP Sockets

31Netprog: Sockets API

Socket System CallsSocket System Calls

• previous sectionsprevious sections– utilities for client-server program utilities for client-server program

• byte order transformation (byte order transformation (htons, htonl, ntohs and ntohl)htons, htonl, ntohs and ntohl)• address transformation (inet_aton, inet_ntoa)address transformation (inet_aton, inet_ntoa)• byte manipulation (memset, memcpy, memcmp)byte manipulation (memset, memcpy, memcmp)• get information about remote host (gethostbyname)get information about remote host (gethostbyname)

• this sectionthis section– Socket system calls used by application program to Socket system calls used by application program to

communicate with another application programcommunicate with another application program– socketsocket– bind, connect, bind, connect, – listen, accept, listen, accept, – sendto, recvfromsendto, recvfrom– read, write, closeread, write, close

Page 32: NP Sockets

32Netprog: Sockets API

Generic socket addressesGeneric socket addresses

struct sockaddr {struct sockaddr {

uint8_tuint8_t sa_len;sa_len;

sa_family_tsa_family_t sa_family; sa_family;

charchar sa_data[14];sa_data[14];

};};

• sa_familysa_family specifies the address type.specifies the address type.• sa_datasa_data specifies the address value.specifies the address value.

Used b

y ke

rnel

Page 33: NP Sockets

33Netprog: Sockets API

sockaddrsockaddr• An address that will allow me to use An address that will allow me to use

sockets to communicate with my kids.sockets to communicate with my kids.

• address type address type AF_DAVESKIDSAF_DAVESKIDS• address values:address values:

AndreaAndrea 11 MomMom 55

JeffJeff 22 DadDad 66

RobertRobert 33 DogDog 77

EmilyEmily 44

Page 34: NP Sockets

34Netprog: Sockets API

AF_DAVESKIDSAF_DAVESKIDS• Initializing a sockaddr structure to point Initializing a sockaddr structure to point

to Robert:to Robert:

struct sockaddr robster;struct sockaddr robster;

robster.sa_family = AF_DAVESKIDS;robster.sa_family = AF_DAVESKIDS;

robster.sa_data[0] = 3;robster.sa_data[0] = 3;

Page 35: NP Sockets

35Netprog: Sockets API

AF_INETAF_INET

• For AF_DAVESKIDS we only needed 1 For AF_DAVESKIDS we only needed 1 byte to specify the address.byte to specify the address.

• For AF_INET we need:For AF_INET we need:– 16 bit port number 16 bit port number – 32 bit IP address32 bit IP address

IPv4 only!

Page 36: NP Sockets

36Netprog: Sockets API

struct sockaddr_in (IPv4)struct sockaddr_in (IPv4)

struct sockaddr_in {struct sockaddr_in {

uint8_tuint8_t sin_len;sin_len;

sa_family_tsa_family_t sin_family;sin_family;

in_port_tin_port_t sin_port;sin_port;

struct in_addrstruct in_addr sin_addr; sin_addr;

charchar sin_zero[8];sin_zero[8];

};};

A special kind of sockaddr structureA special kind of sockaddr structure

Page 37: NP Sockets

37Netprog: Sockets API

struct in_addrstruct in_addr

struct in_addr {struct in_addr {

in_addr_tin_addr_t s_addr;s_addr;

};};

in_addrin_addr just provides a name for the ‘C’ type just provides a name for the ‘C’ type associated with IP addresses.associated with IP addresses.

Page 38: NP Sockets

38Netprog: Sockets API

Network Byte OrderNetwork Byte Order

• All values stored in a All values stored in a sockaddr_insockaddr_in must be in network byte order.must be in network byte order.– sin_portsin_port a TCP/IP port number.a TCP/IP port number.– sin_addrsin_addr an IP address.an IP address.

Page 39: NP Sockets

39Netprog: Sockets API

Network Byte Order FunctionsNetwork Byte Order Functions

‘‘hh’ : host byte order ‘’ : host byte order ‘nn’ : network byte order’ : network byte order

‘‘ss’ : short (16bit) ‘’ : short (16bit) ‘ll’ : long (32bit)’ : long (32bit)

uint16_t uint16_t hhtotonnss(uint16_t);(uint16_t);uint16_t uint16_t nntotohhss(uint_16_t);(uint_16_t);

uint32_t uint32_t hhtotonnll(uint32_t);(uint32_t);uint32_t uint32_t nntotohhll(uint32_t);(uint32_t);

Page 40: NP Sockets

40Netprog: Sockets API

TCP/IP AddressesTCP/IP Addresses

• We don’t need to deal with We don’t need to deal with sockaddr sockaddr structures since we will only deal with a structures since we will only deal with a real protocol family.real protocol family.

• We can use We can use sockaddr_insockaddr_in structures.structures.

BUT: The C functions that make up the BUT: The C functions that make up the sockets API expect structures of type sockets API expect structures of type sockaddrsockaddr..

Page 41: NP Sockets

41Netprog: Sockets API

sin_lensin_lensa_lensa_len

sa_familysa_family

sa_datasa_data

AF_INET

sin_port

sin_addr

sin_zero

sockaddrsockaddr sockaddr_insockaddr_in

Page 42: NP Sockets

42Netprog: Sockets API

Assigning an address to a Assigning an address to a socketsocket

• The The bind()bind() system call is used to assign system call is used to assign an address to an existing socket.an address to an existing socket.

int bind( int sockfd, int bind( int sockfd, const struct sockaddr const struct sockaddr

*myaddr, *myaddr, int addrlen);int addrlen);

• bindbind returns 0 if successful or -1 on error. returns 0 if successful or -1 on error.

const!

Page 43: NP Sockets

43Netprog: Sockets API

bind()bind()

• calling calling bind()bind() assigns the address assigns the address specified by the specified by the sockaddrsockaddr structure to structure to the socket descriptor.the socket descriptor.

• You can give You can give bind()bind() a a sockaddr_insockaddr_in structure:structure:

bind( mysock, bind( mysock, (struct sockaddr*) &myaddr,(struct sockaddr*) &myaddr, sizeof(myaddr) );sizeof(myaddr) );

Page 44: NP Sockets

44Netprog: Sockets API

bind()bind() Example Example

int mysock,err;int mysock,err;struct sockaddr_in myaddr;struct sockaddr_in myaddr;

mysock = socket(PF_INET,SOCK_STREAM,0);mysock = socket(PF_INET,SOCK_STREAM,0);myaddr.sin_family = AF_INET;myaddr.sin_family = AF_INET;myaddr.sin_port = htons( portnum );myaddr.sin_port = htons( portnum );myaddr.sin_addr = htonl( ipaddress);myaddr.sin_addr = htonl( ipaddress);

err=bind(mysock, (sockaddr *) &myaddr, err=bind(mysock, (sockaddr *) &myaddr, sizeof(myaddr));sizeof(myaddr));

Page 45: NP Sockets

45Netprog: Sockets API

Uses for Uses for bind()bind()

• There are a number of uses for There are a number of uses for bind()bind()::– Server would like to bind to a well known Server would like to bind to a well known

address (port number).address (port number).

– Client can bind to a specific port.Client can bind to a specific port.

– Client can ask the O.S. to assign Client can ask the O.S. to assign any any availableavailable port number. port number.

Page 46: NP Sockets

46Netprog: Sockets API

Port - who cares ?Port - who cares ?

• Clients typically don’t care what port Clients typically don’t care what port they are assigned.they are assigned.

• When you call bind you can tell it to When you call bind you can tell it to assign you any available port:assign you any available port:

myaddr.port = htons(0);myaddr.port = htons(0);

Page 47: NP Sockets

47Netprog: Sockets API

What is my IP address ?What is my IP address ?

• How can you find out what your IP address is How can you find out what your IP address is so you can tell so you can tell bind()bind() ? ?

• There is no realistic way for you to know the There is no realistic way for you to know the right IP address to give bind() - what if the right IP address to give bind() - what if the computer has multiple network interfaces?computer has multiple network interfaces?

• specify the IP address as: specify the IP address as: INADDR_ANYINADDR_ANY, , this tells the OS to take care of things.this tells the OS to take care of things.

Page 48: NP Sockets

48Netprog: Sockets API

IPv4 Address ConversionIPv4 Address Conversionint inet_aton( char *, struct in_addr *);int inet_aton( char *, struct in_addr *);

Convert ASCII dotted-decimal IP address to Convert ASCII dotted-decimal IP address to network byte order 32 bit value. Returns 1 network byte order 32 bit value. Returns 1 on success, 0 on failure.on success, 0 on failure.

char *inet_ntoa(struct in_addr);char *inet_ntoa(struct in_addr);

Convert network byte ordered value to Convert network byte ordered value to ASCII dotted-decimal (a string).ASCII dotted-decimal (a string).

Page 49: NP Sockets

49Netprog: Sockets API

Other socket system callsOther socket system calls

• General UseGeneral Use– read()read()– write()write()– close()close()

• Connection-oriented Connection-oriented (TCP)(TCP)– connect()connect()– listen()listen()– accept()accept()

• Connectionless (UDP)Connectionless (UDP)– send()send()– recv()recv()

Page 50: NP Sockets

50Netprog: Sockets API

Threads Threads • Threads are lightweight process which share the process Threads are lightweight process which share the process

instructions , global variables , open files , signal handlers and instructions , global variables , open files , signal handlers and signal dispositions , current working directory and user and group signal dispositions , current working directory and user and group IdsIds

• Each thread has its own thread ID , set of Registers, PC and Each thread has its own thread ID , set of Registers, PC and Stack pointer, stack , errno ,signal mask , priorityStack pointer, stack , errno ,signal mask , priority

• Basic Thread Functions : Creation and TerminationBasic Thread Functions : Creation and Termination• Int pthread_create(pthread_t *tid,const pthread_attr_t *attr,void Int pthread_create(pthread_t *tid,const pthread_attr_t *attr,void

*(*func)(void*), void *arg);*(*func)(void*), void *arg);• Int pthread_join(pthread_t tid,void **status); // Wait for a thread to Int pthread_join(pthread_t tid,void **status); // Wait for a thread to

terminateterminate• pthread_t pthread_self(void); //Returns thread ID of calling threadpthread_t pthread_self(void); //Returns thread ID of calling thread• Int pthread_detach(pthread_t pid);//We cannot wait for it to Int pthread_detach(pthread_t pid);//We cannot wait for it to

terminate, On its termination all resources are releasedterminate, On its termination all resources are released• Void pthread_exit(void *status);Void pthread_exit(void *status);

• Threads/tcpserv01.cThreads/tcpserv01.c

Page 51: NP Sockets

51Netprog: Sockets API

Thread SynchronizationThread Synchronization• Shared data can be protected using mutex locks provided by Shared data can be protected using mutex locks provided by

the pthread librarythe pthread library• int pthread_mutex_lock(pthread_mutex_t *mptr);int pthread_mutex_lock(pthread_mutex_t *mptr);• int pthread_mutex_unlock(pthread_mutex_t *mptr);int pthread_mutex_unlock(pthread_mutex_t *mptr);

• Threads/example02.cThreads/example02.c• Can use condition variables for signalling mechanismCan use condition variables for signalling mechanism• int pthread_cond_wait(pthread_cond_t *cptr,pthread_mutex_t int pthread_cond_wait(pthread_cond_t *cptr,pthread_mutex_t

*mptr);*mptr);• int pthread_cond_signal(pthread_cond_t *cptr);int pthread_cond_signal(pthread_cond_t *cptr);• Can also use System semaphores from <semaphores.h> See Can also use System semaphores from <semaphores.h> See

manualmanual

~syrotiuk/pthreads.cc~syrotiuk/pthreads.cc

Page 52: NP Sockets

52Netprog: Sockets API

QuizQuiz

1. The structure to define an IPv4 address 1. The structure to define an IPv4 address is called a _________ and contains a is called a _________ and contains a field called ___________.field called ___________.

a)a) u_long; s_addru_long; s_addr

b)b) s_addr; in_addrs_addr; in_addr

c)c) in_addr; s_addr in_addr; s_addr (***)

d)d) in_addr; u_longin_addr; u_long

Page 53: NP Sockets

53Netprog: Sockets API

QuizQuiz

2. The ______ socket is used with a 2. The ______ socket is used with a connection-orientation protocolconnection-orientation protocol

a)a) stream stream (***)

b)b) dataramdataram

c)c) rawraw

d)d) remoteremote

Page 54: NP Sockets

54Netprog: Sockets API

QuizQuiz

3. The ______ socket is used with a 3. The ______ socket is used with a connectionless protocolconnectionless protocol

a)a) stream stream

b)b) datagramdatagram(***)

c)c) rawraw

d)d) remoteremote

Page 55: NP Sockets

55Netprog: Sockets API

QuizQuiz

4. To convert a dotted decimal address to 4. To convert a dotted decimal address to a 32-bit binary address, use the a 32-bit binary address, use the _______ function_______ function

a)a) htonshtons

b)b) htolhtol

c)c) inet_ntoainet_ntoa

d)d) inet_aton inet_aton (****)

Page 56: NP Sockets

56Netprog: Sockets API

QuizQuiz

5. To convert a 32-bit integer from 5. To convert a 32-bit integer from network byte order to host byte order, network byte order to host byte order, use the _______ functionuse the _______ function

a)a) htonshtons

b)b) ntohsntohs

c)c) htonlhtonl

d)d) ntohl ntohl (****)

Page 57: NP Sockets

57Netprog: Sockets API

QuizQuiz

6. The ________ function provide 6. The ________ function provide information about the remote hostinformation about the remote host

a)a) hostenthostent

b)b) hostnamehostname

c)c) gethostbyname gethostbyname (****)

d)d) getnameofhostgetnameofhost

Page 58: NP Sockets

58Netprog: Sockets API

QuizQuiz

7. A connectionless process issues the 7. A connectionless process issues the ________ system call to receive, from ________ system call to receive, from the incoming queue, the datagrams the incoming queue, the datagrams sent by a remote process.sent by a remote process.

a)a) listenlistenb)b) receivereceivec)c) bindbindd)d) recvfrom recvfrom (***)

Page 59: NP Sockets

59Netprog: Sockets API

QuizQuiz

8. A connection-oriented process issues 8. A connection-oriented process issues the ________ system call to send the ________ system call to send datagrams to a remote process.datagrams to a remote process.

a)a) sendtosendto

b)b) bindbind

c)c) acceptaccept

d)d) write write (***)

Page 60: NP Sockets

60Netprog: Sockets API

Client/Server TCP Socket Client/Server TCP Socket Interaction: Pseudo-codeInteraction: Pseudo-code

Page 61: NP Sockets

61Netprog: Sockets API

Pseudo-code for a simple Pseudo-code for a simple server and clientserver and client

1.1. create an unnamed create an unnamed socketsocket

2.2. name the socketname the socket3.3. create a queue for create a queue for

hold client requestshold client requests4.4. accept a connection accept a connection

upon receive a upon receive a request from a request from a clientclient

5.5. communicate (R/W) communicate (R/W) with the client as with the client as neededneeded

6.6. close any open close any open sockets when donesockets when done

1.1. create an unnamed create an unnamed socketsocket

2.2. name the socket to name the socket to agree with the server agree with the server choiceschoices

3.3. request connection request connection from the server (upon from the server (upon success, the success, the connection is connection is established)established)

4.4. communicate (W/R) communicate (W/R) with the server as with the server as neededneeded

5.5. close any open close any open sockets when donesockets when done

Page 62: NP Sockets

62Netprog: Sockets API

Basic Socket API in C – cont.Basic Socket API in C – cont.

The following consists of declaring a structure to hold the name information, The following consists of declaring a structure to hold the name information, filling out that structure, and then making the bind call to bind the structure filling out that structure, and then making the bind call to bind the structure to the formerly unnamed socket.to the formerly unnamed socket.

Int serv_len, result;Int serv_len, result;struct sockaddr_in serv_addr;struct sockaddr_in serv_addr;

serv_sock_desc=socket(AF_INET, SOCK_STREAM,0);serv_sock_desc=socket(AF_INET, SOCK_STREAM,0);serv_addr.sin_family=AF_INET;serv_addr.sin_family=AF_INET;result=inet_aton(“127.0.0.1”, &serv_addr.sin_addr);result=inet_aton(“127.0.0.1”, &serv_addr.sin_addr);if (result==0) {if (result==0) {

perror(“inet_aton error”);perror(“inet_aton error”);exit(0);exit(0);

}}serv_addr.sin_port=htons(4242);serv_addr.sin_port=htons(4242);serv_len=sizeof(serv_addr);serv_len=sizeof(serv_addr);bind(serv_sock_desc, (struct sockaddr *)&serv_addr, serv_len);bind(serv_sock_desc, (struct sockaddr *)&serv_addr, serv_len);

Page 63: NP Sockets

63Netprog: Sockets API

Basic Socket API in C – cont.Basic Socket API in C – cont.

a socket to a port addressa socket to a port addressFORMAT: int FORMAT: int bindbind(int (int serv_sock_descserv_sock_desc,(struct ,(struct sockaddrsockaddr *)& *)&serv_adserv_addr, int dr, int

serv_lenserv_len))

The bind function takes three arguments:The bind function takes three arguments:– The The socket descriptorsocket descriptor returned by an earlier call to socket returned by an earlier call to socket– The address of the The address of the sockaddrsockaddr structure holding the name structure holding the name

informationinformation– The The lengthlength of that name structure of that name structure

The name information in the The name information in the sockaddrsockaddr structure includes: structure includes:– domain (AF_INET)domain (AF_INET)– internet address of the socket (127.0.0.1)internet address of the socket (127.0.0.1)– port number to be bound to the socket, we have chosen port port number to be bound to the socket, we have chosen port

number number 42424242 in the lab. session in the lab. session

Page 64: NP Sockets

64Netprog: Sockets API

Basic Socket API in C – cont.Basic Socket API in C – cont.

Create a queue for client request –server codeCreate a queue for client request –server code– The listen call creates a queue for holding The listen call creates a queue for holding

pending clinet requests.pending clinet requests.listen(serv_sock_desc,1);listen(serv_sock_desc,1);

The two arguments to listen are The two arguments to listen are – The socket descriptor for the socket being The socket descriptor for the socket being

listened to (serv_sock_dec)listened to (serv_sock_dec)– The queue length desired – arbitrary, we’ll use 1 The queue length desired – arbitrary, we’ll use 1

for our example, but something like 5 would be for our example, but something like 5 would be more typicalmore typical

Page 65: NP Sockets

65Netprog: Sockets API

Basic Socket API in C – cont.Basic Socket API in C – cont.Accept a connection – server codeAccept a connection – server code

The default behavior of accept is to block until a The default behavior of accept is to block until a client connects.client connects.

int cli_sock_desc, cli_len;int cli_sock_desc, cli_len;struct sockaddr_in cli_addr;struct sockaddr_in cli_addr;cli_len = sizeof(cli_addr);cli_len = sizeof(cli_addr);cli_sock_desc = accept(serv_sock_addr,(stuct sockaddr *) cli_sock_desc = accept(serv_sock_addr,(stuct sockaddr *) &cli_addr, &cli_len);&cli_addr, &cli_len);

Note: accept return a new socket descriptor by using the Note: accept return a new socket descriptor by using the existing socket (identified by existing socket (identified by serv_sock_addrserv_sock_addr) as a ) as a template template for the type. This is reasonable since a server can for the type. This is reasonable since a server can connect to connect to multiple clients.multiple clients.

Page 66: NP Sockets

66Netprog: Sockets API

Basic Socket API in C – cont.Basic Socket API in C – cont.

The accept function has three The accept function has three arguments:arguments:– original socket, original socket, serv_sock_addrserv_sock_addr, to use , to use

a template for the typea template for the type– reference to the reference to the sockaddrsockaddr for the new for the new

socket (it receives the address of the socket (it receives the address of the calling client)calling client)

– The expected address The expected address lengthlength (gets reset (gets reset to the actual length)to the actual length)

Page 67: NP Sockets

67Netprog: Sockets API

Basic Socket API in C – cont.Basic Socket API in C – cont.

Communicate with the client – server codeCommunicate with the client – server code

Communication can be carried out with read and write calls. For Communication can be carried out with read and write calls. For example, to read a character from the client and write it back, we example, to read a character from the client and write it back, we might have:might have:

char ch;char ch;read(cli_sock_desc, &ch, 1);read(cli_sock_desc, &ch, 1);write(cli_sock_desc, &ch, 1);write(cli_sock_desc, &ch, 1);

Note: we use the socket descriptor returned by an earlier accept Note: we use the socket descriptor returned by an earlier accept call.call.

Page 68: NP Sockets

68Netprog: Sockets API

Basic Socket API in C – cont.Basic Socket API in C – cont.

Close the socket – server code Close the socket – server code

This is simply:This is simply:

close(cli_sock_desc);close(cli_sock_desc);

close(serv_sock_desc);close(serv_sock_desc);

Note: Note: If we now look at the client we note that it has If we now look at the client we note that it has very very similar pseudo code except that it has no listen similar pseudo code except that it has no listen or or accept calls, but does have a need to make a accept calls, but does have a need to make a

connection request. connection request.

Page 69: NP Sockets

69Netprog: Sockets API

Basic Socket API in C – cont.Basic Socket API in C – cont.

Create an unnamed socket – Create an unnamed socket – client codeclient codeThis is basically the same as for the This is basically the same as for the server, with a trivial name change for server, with a trivial name change for the socket descriptor:the socket descriptor:int client_sock_desc;int client_sock_desc;

client_sock_desc=socket(AF_INET,SOCK_STREAM,0);client_sock_desc=socket(AF_INET,SOCK_STREAM,0);

…………… …………… and so on.and so on.

Page 70: NP Sockets

70Netprog: Sockets API

Thanks