Netprog 2001 - Advanced Sockets Programming1 Advanced Sockets Programming Ref: Chapter 7,11,21,22.

46
Netprog 2001 - Advanced Sockets Programming 1 Advanced Sockets Advanced Sockets Programming Programming Ref: Chapter 7,11,21,22 Ref: Chapter 7,11,21,22

Transcript of Netprog 2001 - Advanced Sockets Programming1 Advanced Sockets Programming Ref: Chapter 7,11,21,22.

Netprog 2001 - Advanced Sockets Programming 1

Advanced Sockets Advanced Sockets ProgrammingProgramming

Ref: Chapter 7,11,21,22Ref: Chapter 7,11,21,22

Netprog 2001 - Advanced Sockets Programming 2

• It's important to know about some of It's important to know about some of these topics, although it might not be these topics, although it might not be apparent how and when to use them.apparent how and when to use them.

• Details are in the book - we are just Details are in the book - we are just trying to get some idea of what can be trying to get some idea of what can be done.done.

Socket OptionsSocket Options Posix name/address conversion Posix name/address conversion Out-of-Band Data Out-of-Band Data Signal Driven I/O Signal Driven I/O

Netprog 2001 - Advanced Sockets Programming 3

Socket OptionsSocket Options• Various attributes that are used to Various attributes that are used to

determine the behavior of sockets.determine the behavior of sockets.

• Setting options tells the OS/Protocol Setting options tells the OS/Protocol Stack the behavior we want.Stack the behavior we want.

• Support for generic options (apply to all Support for generic options (apply to all sockets) and protocol specific options.sockets) and protocol specific options.

Netprog 2001 - Advanced Sockets Programming 4

Option typesOption types

• Many socket options are Boolean flags Many socket options are Boolean flags indicating whether some feature is indicating whether some feature is enabled (1) or disabled (0).enabled (1) or disabled (0).

• Other options are associated with more Other options are associated with more complex types including complex types including int, timeval, int, timeval,

in_addr, sockaddrin_addr, sockaddr, etc., etc.

Netprog 2001 - Advanced Sockets Programming 5

Read-Only Socket OptionsRead-Only Socket Options

• Some options are readable only (we Some options are readable only (we can’t set the value).can’t set the value).

Netprog 2001 - Advanced Sockets Programming 6

Setting and Getting option Setting and Getting option valuesvalues

getsockopt()getsockopt() gets the current value of gets the current value of a socket option.a socket option.

setsockopt()setsockopt() is used to set the value is used to set the value of a socket option.of a socket option.

#include <sys/socket.h>#include <sys/socket.h>

Netprog 2001 - Advanced Sockets Programming 7

int getsockopt( int sockfd,int getsockopt( int sockfd,

int level,int level,

int optname,int optname,

void *opval,void *opval,

socklen_t *optlen);socklen_t *optlen);

levellevel specifies whether the option is a specifies whether the option is a general option or a protocol specific general option or a protocol specific option (what level of code should option (what level of code should interpret the option).interpret the option).

getsockopt()getsockopt()

Netprog 2001 - Advanced Sockets Programming 8

int setsockopt( int sockfd,int setsockopt( int sockfd,

int level,int level,

int optname,int optname,

const void *opval,const void *opval,

socklen_t optlen);socklen_t optlen);

setsockopt()setsockopt()

Netprog 2001 - Advanced Sockets Programming 9

General Options General Options

• Protocol independent options.Protocol independent options.

• Handled by the generic socket system Handled by the generic socket system code.code.

• Some general options are supported Some general options are supported only by specific types of sockets only by specific types of sockets (SOCK_DGRAM, SOCK_STREAM).(SOCK_DGRAM, SOCK_STREAM).

Netprog 2001 - Advanced Sockets Programming 10

Some Generic OptionsSome Generic Options

SO_BROADCASTSO_BROADCAST

SO_DONTROUTESO_DONTROUTE

SO_ERRORSO_ERROR

SO_KEEPALIVESO_KEEPALIVE

SO_LINGERSO_LINGER

SO_RCVBUF,SO_SNDBUFSO_RCVBUF,SO_SNDBUF

SO_REUSEADDRSO_REUSEADDR

Netprog 2001 - Advanced Sockets Programming 11

SO_BROADCASTSO_BROADCAST• Boolean option: enables/disables sending Boolean option: enables/disables sending

of broadcast messages.of broadcast messages.• Underlying DL layer must support Underlying DL layer must support

broadcasting!broadcasting!• Applies only to SOCK_DGRAM sockets.Applies only to SOCK_DGRAM sockets.• Prevents applications from inadvertently Prevents applications from inadvertently

sending broadcasts (OS looks for this flag sending broadcasts (OS looks for this flag when broadcast address is specified).when broadcast address is specified).

Netprog 2001 - Advanced Sockets Programming 12

SO_DONTROUTESO_DONTROUTE

• Boolean option: enables bypassing of Boolean option: enables bypassing of normal routing.normal routing.

• Used by routing daemons.Used by routing daemons.

Netprog 2001 - Advanced Sockets Programming 13

SO_ERRORSO_ERROR

• Integer value option. Integer value option.

• The value is an error indicator value The value is an error indicator value

(similar to (similar to errno)errno)..

• Readable (get’able) only!Readable (get’able) only!

• Reading (by calling Reading (by calling getsockopt()getsockopt()) )

clears any pending error.clears any pending error.

Netprog 2001 - Advanced Sockets Programming 14

SO_KEEPALIVESO_KEEPALIVE• Boolean option: enabled means that Boolean option: enabled means that

STREAM sockets should send a STREAM sockets should send a probeprobe to peer if no data flow for a “long time”.to peer if no data flow for a “long time”.

• Used by TCP - allows a process to Used by TCP - allows a process to determine whether peer process/host determine whether peer process/host has crashed. has crashed.

• Consider what would happen to an Consider what would happen to an open telnet connection without open telnet connection without keepalive.keepalive.

Netprog 2001 - Advanced Sockets Programming 15

SO_LINGERSO_LINGER

Value is of type:Value is of type:struct linger {struct linger {

int l_onoff;int l_onoff; /* 0 = off */ /* 0 = off */

int l_linger; /* time in seconds */int l_linger; /* time in seconds */

};};

• Used to control whether and how long a Used to control whether and how long a call to close will wait for pending ACKS. call to close will wait for pending ACKS.

• connection-oriented sockets only. connection-oriented sockets only.

Netprog 2001 - Advanced Sockets Programming 16

SO_LINGER SO_LINGER usageusage• By default, calling By default, calling close()close() on a TCP on a TCP

socket will return immediately.socket will return immediately.

• The closing process has no way of The closing process has no way of knowing whether or not the peer knowing whether or not the peer received all data.received all data.

• Setting SO_LINGER means the closing Setting SO_LINGER means the closing process can determine that the peer process can determine that the peer machine has received the data (but not machine has received the data (but not that the data has been that the data has been read()read() !). !).

Netprog 2001 - Advanced Sockets Programming 17

shutdown() shutdown() vsvs SO_LINGERSO_LINGER

• The book shows how you can use The book shows how you can use shutdown()shutdown() to find out when the peer to find out when the peer process has read all the sent data.process has read all the sent data.

Netprog 2001 - Advanced Sockets Programming 18

SO_RCVBUFSO_RCVBUFSO_SNDBUFSO_SNDBUF

• Integer values options - change the Integer values options - change the receive and send buffer sizes.receive and send buffer sizes.

• Can be used with STREAM and Can be used with STREAM and DGRAM sockets.DGRAM sockets.

• With TCP, this option effects the With TCP, this option effects the window size used for flow control - must window size used for flow control - must be established before connection is be established before connection is made.made.

Netprog 2001 - Advanced Sockets Programming 19

SO_REUSEADDRSO_REUSEADDR

• Boolean option: enables binding to an Boolean option: enables binding to an address (port) that is already in use.address (port) that is already in use.

• Used by servers that are transient - Used by servers that are transient - allows binding a passive socket to a allows binding a passive socket to a port currently in use (with active port currently in use (with active sockets) by other processes.sockets) by other processes.

Netprog 2001 - Advanced Sockets Programming 20

SO_REUSEADDRSO_REUSEADDR

• Can be used to establish separate Can be used to establish separate servers for the same service on servers for the same service on different interfaces (or different IP different interfaces (or different IP addresses on the same interface).addresses on the same interface).

• Virtual Web Servers can work this way.Virtual Web Servers can work this way.

Netprog 2001 - Advanced Sockets Programming 21

IP Options (IPv4)IP Options (IPv4)

• IP_HDRINCL: used on raw IP sockets IP_HDRINCL: used on raw IP sockets when we want to build the IP header when we want to build the IP header ourselves.ourselves.

• IP_TOS: allows us to set the “Type-of-IP_TOS: allows us to set the “Type-of-service” field in an IP header.service” field in an IP header.

• IP_TTL: allows us to set the “Time-to-IP_TTL: allows us to set the “Time-to-live” field in an IP header.live” field in an IP header.

Netprog 2001 - Advanced Sockets Programming 22

TCP socket optionsTCP socket options

• TCP_KEEPALIVE: set the idle time TCP_KEEPALIVE: set the idle time used when SO_KEEPALIVE is enabled.used when SO_KEEPALIVE is enabled.

• TCP_MAXSEG: set the maximum TCP_MAXSEG: set the maximum segment size sent by a TCP socket.segment size sent by a TCP socket.

Netprog 2001 - Advanced Sockets Programming 23

another TCP socket optionanother TCP socket option

• TCP_NODELAY: can disable TCP’s TCP_NODELAY: can disable TCP’s Nagle algorithm that delays sending Nagle algorithm that delays sending small packets if there is unACK’d data small packets if there is unACK’d data pending.pending.

• TCP_NODELAY also disables delayed TCP_NODELAY also disables delayed ACKS (TCP ACKs are cumulative).ACKS (TCP ACKs are cumulative).

Netprog 2001 - Advanced Sockets Programming 24

• This was just an overviewThis was just an overview– there are many details associated with the there are many details associated with the

options described.options described.– There are many options that haven’t been There are many options that haven’t been

described.described.– Our text is one of the best sources of Our text is one of the best sources of

information about socket options.information about socket options.

Socket Options SummarySocket Options Summary

Netprog 2001 - Advanced Sockets Programming 25

Posix Name/Adress ConversionPosix Name/Adress Conversion

• We've seen We've seen gethostbynamegethostbyname and and gethostbyaddrgethostbyaddr - these are protocol - these are protocol dependent.dependent.– Not part of sockets library.Not part of sockets library.

• Posix includes protocol Posix includes protocol independentindependent functions:functions:

getaddrinfo()getaddrinfo() getnameinfo()getnameinfo()

Netprog 2001 - Advanced Sockets Programming 26

getaddrinfogetaddrinfo, , getnameinfogetnameinfo

• These functions provide name/address These functions provide name/address conversions as part of the sockets conversions as part of the sockets library.library.

• In the future it will be important to write In the future it will be important to write code that can run on many protocols code that can run on many protocols (IPV4, IPV6), but for now these (IPV4, IPV6), but for now these functions are not widely available.functions are not widely available.– It's worth seeing how they work even It's worth seeing how they work even

though we probably can't use them yet!though we probably can't use them yet!

Netprog 2001 - Advanced Sockets Programming 27

WhyWhy getaddrinfo() getaddrinfo()??

• Puts protocol dependence in library Puts protocol dependence in library (where it belongs).(where it belongs).– Same code can be used for many Same code can be used for many

protocols (IPV4, IPV6)protocols (IPV4, IPV6)– re-entrant function - re-entrant function - gethostbynamegethostbyname is is

not!not!• Important to threaded applications.Important to threaded applications.

Netprog 2001 - Advanced Sockets Programming 28

getaddrinfo()getaddrinfo()

int getaddrinfo( int getaddrinfo(

const char *hostname,const char *hostname,

const char *service,const char *service,

const struct addrinfo* hints,const struct addrinfo* hints,

struct addrinfo **result);struct addrinfo **result);

getaddrinfo() getaddrinfo() replaces both replaces both gethostbyname()gethostbyname() and and getservbyname()getservbyname()

Netprog 2001 - Advanced Sockets Programming 29

getaddrinfo() getaddrinfo() parametersparameters

hostnamehostname is a hostname or an address string is a hostname or an address string (dotted decimal string for IP).(dotted decimal string for IP).

serviceservice is a service name or a decimal port is a service name or a decimal port number string.number string.

Netprog 2001 - Advanced Sockets Programming 30

struct addrinfostruct addrinfostruct addrinfo {struct addrinfo {

intint ai_flags;ai_flags;

intint ai_family;ai_family;

intint ai_socktype;ai_socktype;

intint ai_protocol;ai_protocol;

size_tsize_t ai_addrlen;ai_addrlen;

char char *canonname;*canonname;

structstruct sockaddr *ai_addr;sockaddr *ai_addr;

structstruct addrinfo *ai_next;addrinfo *ai_next;};};

Linked list!

Netprog 2001 - Advanced Sockets Programming 31

getaddrinfo() hintsgetaddrinfo() hints

hintshints is an is an addrinfo *addrinfo * (can be (can be NULLNULL) that can ) that can contain:contain:– ai_flagsai_flags ((AI_PASSIVEAI_PASSIVE , , AI_CANONNAME AI_CANONNAME ) )

– ai_familyai_family ((AF_AF_XXX XXX ))

– ai_socktypeai_socktype ((SOCK_SOCK_XXX XXX ))– ai_protocol ai_protocol (IPPROTO_TCP, etc.)(IPPROTO_TCP, etc.)

Netprog 2001 - Advanced Sockets Programming 32

getaddrinfo() resultgetaddrinfo() result

resultresult is returned with the address of a is returned with the address of a pointer to an pointer to an addrinfo addrinfo structure that is the structure that is the head of a linked list.head of a linked list.

It is possible to get multiple structures:It is possible to get multiple structures:– multiple addresses associated with the multiple addresses associated with the

hostnamehostname..

– The The serviceservice is provided for multiple socket is provided for multiple socket types.types.

Netprog 2001 - Advanced Sockets Programming 33

addrinfoaddrinfo usage usage

ai_flagsai_familyai_socktypeai_protocolai_addrlenai_canonnameai_addrai_next

Used in call to socket()socket()

Used in call to bind(), connect()bind(), connect()oror sendto() sendto()

ai_flagsai_familyai_socktypeai_protocolai_addrlenai_canonnameai_addrai_next

Netprog 2001 - Advanced Sockets Programming 34

getnameinfo()getnameinfo()int getnameinfo( int getnameinfo(

const struct sockaddr *sockaddr,const struct sockaddr *sockaddr,

socklen_t addrlensocklen_t addrlen

char *host,char *host,

size_t hostlen,size_t hostlen,

char *serv,char *serv,

size_t servlen,size_t servlen,

int flags);int flags);

getnameinfo()getnameinfo() looks up a hostname and a looks up a hostname and a service name given a service name given a sockaddrsockaddr

Netprog 2001 - Advanced Sockets Programming 35

Out-of-Band DateOut-of-Band Date• Ever been on a date, gone to a dance Ever been on a date, gone to a dance

club and the band doesn't show up?club and the band doesn't show up?– This is becoming a serious problem: This is becoming a serious problem:

• The number of Internet dating services is The number of Internet dating services is growing exponentially.growing exponentially.

• The number of bands is not growing.The number of bands is not growing.

– RFC 90210 proposes some short term RFC 90210 proposes some short term solutions (until the number of bands can be solutions (until the number of bands can be increased).increased).

Netprog 2001 - Advanced Sockets Programming 36

Out-of-Band Out-of-Band DataData

• TCP (and other transport layers) provide TCP (and other transport layers) provide a mechanism for delivery of "high priority" a mechanism for delivery of "high priority" data ahead of "normal data".data ahead of "normal data".

• We can almost think of this as 2 streams:We can almost think of this as 2 streams:

TCP PORTA

TCP PORTB

normal data

special data

Netprog 2001 - Advanced Sockets Programming 37

TCP OOB DataTCP OOB Data• TCP supports something like OOB data TCP supports something like OOB data

using URGENT MODE (a bit is set in a using URGENT MODE (a bit is set in a TCP segment header). TCP segment header).

• A TCP segment header field contains A TCP segment header field contains an indication of the location of the an indication of the location of the urgent data in the stream (the byte urgent data in the stream (the byte number).number).

Netprog 2001 - Advanced Sockets Programming 38

Sending OOB DataSending OOB Datasend(sd,buff,1,MSG_OOB);send(sd,buff,1,MSG_OOB);

Use Use send()send() to put a single byte of urgent to put a single byte of urgent data in a TCP stream.data in a TCP stream.

The TCP layer adds some segment header The TCP layer adds some segment header info to let the other end know there is info to let the other end know there is some OOB data.some OOB data.

Netprog 2001 - Advanced Sockets Programming 39

Receiving OOB DataReceiving OOB Data

• The TCP layer generates a The TCP layer generates a SIGURGSIGURG signal in the receiving process.signal in the receiving process.

• select()select() will tell you an exception will tell you an exception condition is present.condition is present.

Netprog 2001 - Advanced Sockets Programming 40

Reading URG dataReading URG data(a.k.a. (a.k.a. re-urg-e-dating)re-urg-e-dating)

• Depending on how things are set up:Depending on how things are set up:– the data can be read using the data can be read using recv()recv() with a with a MSG_OOBMSG_OOB flag set. flag set.

– The data can be read The data can be read inlineinline and the and the receiving process can moniter the receiving process can moniter the out-of-out-of-band-markband-mark for the connection (using for the connection (using sockatmark()sockatmark()))

Netprog 2001 - Advanced Sockets Programming 41

So what?So what?

• OOB Data might be used:OOB Data might be used:– a heartbeat between the client and server a heartbeat between the client and server

to detect early failure (example in the to detect early failure (example in the book).book).

– A way to communicate an exceptional A way to communicate an exceptional condition to a peer even when flow control condition to a peer even when flow control has stopped the sender.has stopped the sender.

Netprog 2001 - Advanced Sockets Programming 42

Singles Driven IOUSingles Driven IOU

• Another problem with Internet Dating Another problem with Internet Dating services is the lack of single drivers in services is the lack of single drivers in many metropolitan areas.many metropolitan areas.– Neither participant can pick up the other.Neither participant can pick up the other.– Dating protocols degrade to involve online Dating protocols degrade to involve online

communication only.communication only.– Proxy drivers (running TAXI protocol) get Proxy drivers (running TAXI protocol) get

overloaded and refuse IOU packets.overloaded and refuse IOU packets.

Netprog 2001 - Advanced Sockets Programming 43

Signal Driven I/OSignal Driven I/O

• We can tell the kernel to send us a We can tell the kernel to send us a SIGIOSIGIO signal whenever something signal whenever something happens to a socket descriptor.happens to a socket descriptor.

• The signal handler must determine what The signal handler must determine what conditions caused the signal and take conditions caused the signal and take appropriate action.appropriate action.

Netprog 2001 - Advanced Sockets Programming 44

Signal Driven UDPSignal Driven UDP

• SIGIO occurs whenever:SIGIO occurs whenever:– an incoming datagram arrives.an incoming datagram arrives.– An asynchronous error occurs.An asynchronous error occurs.

• Could be ICMP error (unreachable, invalid Could be ICMP error (unreachable, invalid address, etc).address, etc).

• Could allow process to handle other Could allow process to handle other tasks and still watch for incoming UDP tasks and still watch for incoming UDP messages.messages.

Netprog 2001 - Advanced Sockets Programming 45

Signal-Driven ExampleSignal-Driven Example

• Real life signal-driven UDP example Real life signal-driven UDP example described in the book:described in the book:– NTP Network Time Protocol.NTP Network Time Protocol.– Used to record timestamp of arrival of UDP Used to record timestamp of arrival of UDP

datagram. datagram.

Netprog 2001 - Advanced Sockets Programming 46

Signal Driven TCP (very rare)Signal Driven TCP (very rare)• SIGIOSIGIO occurs whenever: occurs whenever:

– an incoming connection has completed.an incoming connection has completed.– Disconnect request initiated.Disconnect request initiated.– Disconnect request completed.Disconnect request completed.– Half a connection shutdown.Half a connection shutdown.– Data has arrived.Data has arrived.– Data has been sent (indicating there is buffer Data has been sent (indicating there is buffer

space)space)– asynchronous errorasynchronous error