72
1 Sockets Chapter 10 from the book: Inter-process Communications in Linux : The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date: January 13, 2003

Sockets

Embed Size (px)

DESCRIPTION

Sockets. Chapter 10 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date: January 13, 2003. COMMUNICATION BASICS. Topics. COMMUNICATION BASICS. Network Addresses. COMMUNICATION BASICS. - PowerPoint PPT Presentation

Citation preview

1

SocketsChapter 10 from the book: Inter-process Communications in Linux :

The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall

Pub Date: January 13, 2003

2

Topics Network Addresses Domains Protocol Families Socket Types IPC Using Socketpair The Connection-Oriented Paradigm The Connectionless Paradigm

COMMUNICATION BASICS

3

Network Addresses Every host on a network has two unique

addresses: The first one is a 48-bit media access control

(MAC) address that is assigned to its network interface card (NIC).

(Figure 10.1)

COMMUNICATION BASICS

4

COMMUNICATION BASICS

linux$ /sbin/ifconfig -a

eth0 Link encap:Ethernet HWaddr 00:B0:D0:AB:7C:96

<-- 1

BROADCAST MULTICAST MTU:1500 Metric:1 |

RX packets:0 errors:0 dropped:0 overruns:0 frame:0 |

TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 |

collisions:0 txqueuelen:100 |

Interrupt:16 Base address:0xecc0 Memory:e08fc000-e08fcc40|

|

eth1 Link encap:Ethernet HWaddr 00:02:B3:35:9E:21

<-- 1

inet addr:137.49.6.1 Bcast:137.49.255.255 Mask:255.255.0.0

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:471693034 errors:2 dropped:0 overruns:27398 frame:2

Figure 10.1. Displaying the MAC addresses on a Linux host.

5

COMMUNICATION BASICS

TX packets:2147483647 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:100

Interrupt:26 Base address:0xd4c0 Memory:e08fe000-e08fec40

lo ink encap:Local Loopback

inet addr:127.0.0.1 Mask:255.0.0.0

UP LOOPBACK RUNNING MTU:16436 Metric:1

RX packets:95939986 errors:0 dropped:0 overruns:0 frame:0

TX packets:95939986 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:0

(1)This host has two network cards. As shown, only eth1 is active

Figure 10.1. Displaying the MAC addresses on a Linux host.

6

Network Addresses The second one is a 32-bit Internet (IP) address

subdivided into » Network portion (netid)» Local portion (hostid)

Using the leading bits of the netid value, networks can be divided into five classes, A through E.

First three classes are: A-C» In a Class A network bit 0 is 0» In a Class B the first two bits are 10 » In a Class C the first three bits are 110

COMMUNICATION BASICS

7

Network Addresses Figure 10.2 shows that the range of hostids is

directly related to the class of the network.

COMMUNICATION BASICS

Figure 10.2. Network class numbering scheme.

8

Domains A dotted IP address can be mapped into a more

easily understood symbolic notation using the Domain Name System (DNS).

All Internet addresses are divided into a set of high-level

Organizational domains Geographical domains

COMMUNICATION BASICS

9

Domains When we create the socket, we specify its

communication domain. The two types of socket communication domains

are: UNIX domain

» In this domain, when sockets are created, they have actual file (path) names. These sockets can be used only with processes that reside on the same host. UNIX domain sockets are sometimes used as the first step in the development of socket-based communications because, due to their locality, they are somewhat easier to debug.

COMMUNICATION BASICS

10

Domains Internet domain

» These sockets allow unrelated processes on different hosts to communicate.

COMMUNICATION BASICS

11

Protocol Families A set of rules and conventions is called a

protocol. Protocols are designed in layers. The layering of protocols facilitates a certain

degree of isolation. Figure 10.3 shows the standard seven layer

OSI model.

COMMUNICATION BASICS

12

LayerFunctionality

ApplicationPresentation

Session

Transport

Network

Data LinkPhysical

Provides processes access to interprocess facilities.Responsible for data conversion—text compression and reformatting,encryption.Addresses the synchronization of process dialog—establishes,manages, and terminates connections.Responsible for maintaining an agreed-upon level of data exchange. Determines type of service, flow control, error recovery, and so on.Concerned with the routing of data from one network to another—establishing, maintaining, and terminating connections.Insures error-free transmission of data.Addresses physical connections and transmission of raw data stream.

Figure 10.3. The ISO/OSI layer cake.

COMMUNICATION BASICS

13

Protocol Families A grouping of layers, usually equal to transport

and network layers of the OSI model that deals with data format , addressing, flow control and error handling is called a protocol family.

There are a number of protocol families: SNA— IBM's Systems Network Architecture UUCP— UNIX-to-UNIX copy XNS— Xerox Network System NETBIOS— IBM's Network Basic Input/Output

System TCP/IP— DARPA (Defense Advanced Research

Projects Agency) Internet

COMMUNICATION BASICS

14

Protocol Families Our discussion centers on TCP and UDP of the

TCP/IP protocol family, Internet domain (PF_INET) and UNIX domain (PF_UNIX) that is used in creation of sockets

In general TCP/IP composed of: TCP— Transmission Control Protocol. TCP is reliable, full duplex

and connection-oriented. Data is transmitted as a byte stream. IP— Internet Protocol. Provides delivery of packets. TCP, UDP and

ICMP usually call IP. ARP/RARP— Address/Reverse Address Resolution Protocol.

These protocols are used to resolve Internet/hardware addressing. UDP— User Datagram Protocol. UDP is non-reliable, full duplex,

and connectionless. Data is transmitted as a series of packets. ICMP— Internet Control Message Protocol. Used for error handling

and flow control.

COMMUNICATION BASICS

15

Socket Types Communicated data can be in a

Stream format Data is transmitted as a sequence of bytes

Datagram format» Datagrams are small, discrete packets that, contain

header information, data, and trailer information (error correction, etc.).

Socket type will determine how communications will be carried on between the processes using the socket.

Sockets must be of the same type to communicate.

COMMUNICATION BASICS

16

Socket Types There are two basic socket types:

Stream sockets» These sockets are reliable. When these sockets are used,

data is delivered in order, in the same sequence in which it was sent. There is no duplication of data, and some form of error checking and flow control is usually present. Stream sockets allow bidirectional (full duplex) communication. Stream sockets are connection-oriented. That is, the two processes using the socket create a logical connection (a virtual circuit). Information concerning the connection is established prior to the transmission of data and is maintained by each end of the connection during the communication. Data is transmitted as a stream of bytes. In a very limited fashion, these sockets also permit the user to place a higher priority urgent message ahead of the data in the current stream.

COMMUNICATION BASICS

17

Socket Types Datagram sockets

» Datagram sockets are potentially unreliable. Thus, with these sockets, received data may be out of order. Datagram sockets support bidirectional communications but are considered connectionless. There is no logical connection between the sending and receiving processes. Each datagram is sent and processed independently. Individual datagrams may take different routes to the same destination. With connectionless service, there is no flow control. Error control, when specified, is minimal. Datagram packets are normally small and fixed in size.

COMMUNICATION BASICS

18

IPC Using Socketpair The socketpair call is used to create the pair of

sockets and is only implemented for the PF_UNIX (PF_LOCAL) family and is used for the same host communications.

Pipes also are used for the same host but they are limited because the file descriptors permit unidirectional communication.

The socketpair function creates two file descriptors for two connected sockets on the same computer. These file descriptors permit two-way communication between related processes.

19

IPC Using Socketpair

Return

Summaryint socketpair( int d, int type,

int protocol, int sv[2] );

Include File(s)

<sys/socket.h>

Manual Section2

SuccessFailureSets errno

0 and two open socket descriptors-1Yes

Table 10.1. Summary of the socketpair System Call

Return

Summaryint socketpair( int d, int type,

int protocol, int sv[2] );

Include File(s)

<sys/socket.h>

Manual Section2

SuccessFailureSets errno

0 and two open socket descriptors.-1Yes

20

IPC Using Socketpair socketpair takes four arguments:

The first argument is an integer value that specifies the domain.

» In general, the domains for socket-based calls should be specified as one of the protocol family-defined constants found in the header file <bits/socket.h>.

(Table 10.2)

21

IPC Using Socketpair

ConstantValueReference

PF_UNSPEC0Unspecified

PF_LOCAL1Local to host (pipes and file-domain).

PF_UNIXPF_LOCALOld BSD name for PF_LOCAL.

PF_FILEPF_LOCALAnother nonstandard name for PF_LOCAL.

PF_INET2IP protocol family.

PF_AX253Amateur Radio AX.25.

PF_IPX4Novell Internet Protocol.

PF_APPLETALK5Appletalk DDP.

PF_NETROM6Amateur radio NetROM.

PF_BRIDGE7Multiprotocol bridge.

PF_ATMPVC8ATM PVCs.

Table 10.2. Protocol Family Constants.

22

IPC Using Socketpair

ConstantValueReference

PF_X259Reserved for X.25 project.

PF_INET610IP version 6.

PF_ROSE11Amateur Radio X.25 PLP..

PF_DECnet12Reserved for DECnet project..

PF_NETBEUI13Reserved for 802.2LLC project..

PF_SECURITY14Security callback pseudo AF..

PF_KEY15PF_KEY key management API.

PF_NETLINK16

PF_ROUTEPF_NETLINKAlias to emulate 4.4BSD..

PF_PACKET17Packet family..

PF_ASH18Ash..

Table 10.2. Protocol Family Constants.

23

IPC Using Socketpair

ConstantValueReference

PF_ECONET19Acorn Econet.

PF_ATMSVC20ATM SVCs.

PF_SNA22Linux SNA Project

PF_IRDA23IRDA sockets.

PF_PPPOX24PPPoX sockets.

PF_MAX32For now.

Table 10.2. Protocol Family Constants.

24

IPC Using Socketpair The second argument for the socketpair call is

type that indicates the socket type:» The defined constant SOCK_STREAM to indicate a

stream socket.» The defined constant SOCK_DGRAM to indicate a

datagram-based socket.

25

IPC Using Socketpair The third argument is protocol that is used to

indicate the protocol within the specified family.» In most cases, this argument is set to 0, which

indicates to the system that it should select the protocol.

UDP for connectionless sockets TCP for connection-oriented

26

IPC Using Socketpair The fourth argument is sv that is the base address

of an integer array that references the two socket descriptors.

» Descriptors are created if the call is successful.» Each descriptor is bidirectional and is available for

both reading and writing. » If the socketpair call fails, it returns a −1 and sets

errno.

(Table 10.3.)

27

IPC Using Socketpair

Table 10.3. socketpair Error Messages..

#Constantperror MessageExplanation

14EFAULTBad addresssv references an illegal address.

24EMFILEToo many open filesThis process has reached the limit for open file descriptors.

93EPROTONOSUPPORTProtocol not supportedRequested protocol not supported on this system.

95EOPNOTSUPPORTOperation not supportedSpecified protocol does not support socket pairs.

97EAFNOSUPPORTAddress family not supported by protocol

Cannot use the indicated address family with specified protocol family.

28

IPC Using Socketpair Figure 10.5 shows in the socketpair.c program

example, how the created sockets communicate and exchange information between the parent and child processes.

To see how socketpair.c example program works, compile socketpair.c with –lsocket optin on jupiter and see the result. Can you modify it to be able to run on elara?

Instead of socketpair, the more general system call (i.e., socket) is uses for interprocess communications.

29

IPC Using Socketpair

Figure 10.5. The socketpair before and after the process forks.

30

The Connection-Oriented Paradigm Socket types are:

connection-oriented (type SOCK_STREAM) Figure10.6.

connectionless (type SOCK_DGRAM)

31

The Connection-Oriented Paradigm

Figure 10.6. A connection-oriented client–server communication sequence.

32

The Connection-Oriented Paradigm Figure 10.6 shows

The process initiating the connection is the client process and the process receiving the connection is the server.

Both the client and server processes use the socket call to create a new instance of a socket.

The socket will act as a queuing point for data exchange.

(Table 10.4)

33

The Connection-Oriented Paradigm

Return

SummaryInt socket( int domaint, int type, int protocol) ;

Include File(s)

>sys/types.h<<sys/socket.h>

Manual Section2

SuccessFailureSets errno

0 and an open socket descriptor.-1Yes

Table 10.4. Summary of the socket System Call.

Return

34

The Connection-Oriented Paradigm The socket system call takes three arguments:

The first argument is an integer value that specifies the protocol family.

(Table 10.5)

35

The Connection-Oriented Paradigm

Table 10.5. Supported Protocol Families.

ConstantProtocol FamilyPF_APPLETALKAppletalk

PF_ATMPVCAccess to raw ATM PVCs

PF_AX25Amateur radio AX.25 protocol

PF_INETIPv4 Internet protocols

PF_INET6IPv6 Internet protocols

PF_IPXIPX - Novell protocols

PF_NETLINKKernel user interface device

PF_PACKETLow-level packet interface

PF_UNIX, PF_LOCALLocal communication

PF_X25ITU-T X.25 / ISO-8208 protocol x25(7)

36

The Connection-Oriented Paradigm The second argument for the socket system call is

type that indicates the socket type:» The defined constant SOCK_STREAM to indicate a

stream socket.» The defined constant SOCK_DGRAM to indicate a

datagram-based socket.

37

The Connection-Oriented Paradigm The third argument is protocol that is used

to indicate the protocol within the specified family.

» In most cases, this argument is set to 0, which indicates to the system that it should select the protocol.

» If the socket call is successful, it will return an integer value that can be used to reference the socket descriptor.

» If the call fails, it returns a −1 and sets errno.

(Table 10.6.)

38

The Connection-Oriented Paradigm#ConstantPerror MessageExplanation

12ENOMEMCannot allocate memory

When creating a socket, insufficient memory available.

13EACCESPermission deniedCannot create a socket of the specified type/protocol.

22EINVALInvalid argumentUnknown protocol or protocol family is not available.

23ENFILEToo many open files in system

Insufficient kernel (system) memory for socket allocation.

24EMFILEToo many open filesThis process has reached the limit for open file descriptors.

93EPROTONOSUPPORTProtocol not supportedRequested protocol not supported on this system or within this domain.

105ENOBUFSNo buffer space available

Socket cannot be created until resources are freed.

Table 10.6. socket Error Messages.

39

The Connection-Oriented Paradigm Initially, when the socket is created, it is

unbound (i.e., there is no name or address/port number pair associated with the socket).

If the process creating the socket is to act as a server, the socket must be bound.

(Table 10.7)

40

The Connection-Oriented Paradigm

Return

Summaryint bind(int sockfd, struct sockaddr *my_addr,

socklen_t addrlen);

Include File(s)

>sys/types.h<<sys/socket.h>

Manual Section2

SuccessFailureSets errno

0-1Yes

Table 10.7. Summary of the bind System Call

Return

41

The Connection-Oriented Paradigm The bind system call takes two arguments:

The first argument is an integer value that has been returned from a previous successful socket call.

The second argument is a real gem. The short explanation is the argument references a generic address structure of the type:

/* Structure describing a generic socket address. */

struct sockaddr {

__SOCKADDR_COMMON (sa_); /* Common data: adr family and length. */

char sa_data[14]; /* Address data. */

};

42

The Connection-Oriented Paradigm If bind is successful, it returns a 0; otherwise, it

returns a −1 and sets the value of errno.

(Table 10.8)

43

The Connection-Oriented Paradigm#ConstantPerror MessageExplanation

2ENOENTNo such file or directoryComponent of the path for the file name

entry does not exist.

9EBADFBad file descriptorsockfd reference is invalid.

12ENOMEMCannot allocate memoryInsufficient memory.

13EACCESPermission denied• Cannot create a socket of the specified type/

protocol.

• Search access denied for part of the path

specified by name.

14EFAULTBad addressmy_addr references address outside user's

space.

20ENOTDIRNot a directoryPart of the path of my_addr is not a

directory.

22EINVALInvalid argument• addrlen is invalid.

• sockfd already bound to an address.

Table 10.8. bind Error Messages.

44

The Connection-Oriented Paradigm#ConstantPerror MessageExplanation

30EROFSRead-only file systemFile would reside on a read-only file

system.

36ENAMETOOLONGFile name too longmy_addr name is too long.

40ELOOPToo many levels of symbolic links

Too many symbolic links in my_addr.

63ENOSROut of streams resourcesInsufficient STREAMS resources for

specified operation.

88ENOTSOCKSocket operation on non-socket

sockfd is a file descriptor, not a socket

descriptor

98EADDRINUSEAddress already in useSpecified address already in use.

99EADDRNOTAVAILCan't assign request address

The specified address is not available on the

local system.

Table 10.8. bind Error Messages.

45

The Connection-Oriented Paradigm The listen system call creates a queue for incoming

connection requests. If the queue is full and the protocol does not support

retransmission, the client process generating the request will receive the error ECONNREFUSED from the server.

If the protocol does support retransmission, the request is ignored, so a subsequent retry can succeed.

This call only applies to sockets of type SOCK_STREAM or SOCK_SEQPACKET.

(Table 10.9)

46

The Connection-Oriented Paradigm

Return

Summaryint listen(int s, int backlog);

Include File(s)

>sys/types.h<<sys/socket.h>

Manual Section2

SuccessFailureSets errno

0-1Yes

Table 10.9. Summary of the listen System Call.

Return

47

The Connection-Oriented Paradigm The listen system call takes two arguments:

The first argument is a valid integer socket descriptor.

The second argument, backlog, denotes the maximum size of the queue.

Should the listen call fail, it sets errno. (Table 10.10)

48

The Connection-Oriented Paradigm#ConstantPerror MessageExplanation

9EBADFBad file descriptors reference is invalid.

88ENOTSOCKSocket operation on non-sockets is a file descriptor, not a socket descriptor.

95EOPNOTSUPPOperation not supportedSocket type (such as SOCK_DGRAM) does not support listen operation.

Table 10.10. listen Error Messages.

49

The Connection-Oriented Paradigm When the server process is ready to accept a

connection from a client process, accept system call is called.

(Table 10.11.)

50

The Connection-Oriented Paradigm

Return

Summaryint accept( int s, struct sockaddr *addr,

socklen_t *addrlen );

Include File(s)

>sys/types.h<<sys/socket.h>

Manual Section2

SuccessFailureSets errno

Positive integer new socket descriptor value-1Yes

Table 10.11. Summary of the accept System Call.

Return

51

The Connection-Oriented Paradigm The accept system call takes three arguments:

The first argument is a valid integer socket descriptor.

The second argument, *addr, is a pointer to a generic sockaddr structure.

The third argument,*addrlen, initially contains a reference to the length, in bytes, of the previous sockaddr structure.

Should the accept call fail, it sets errno. (Table 10.12)

52

The Connection-Oriented Paradigm#ConstantPerror MessageExplanation

1EPERMOperation not permitted

Firewall software prohibits connection.

4EINTRInterrupted system call

A signal was received during the accept process.

9EBADFBad file descriptorThe socket reference is invalid.

11EWOULDBLOCK,EAGAIN

Resource temporarily

unavailable

The socket is set to non-blocking, and no connections are pending

12ENOMEMCannot allocate memory

Insufficient memory to perform operation.

14EFAULTBad addressReference for addr is not writeable.

19ENODEVNo such deviceSpecified protocol family/type not found in the netconfig file.

Table 10.12. accept Error Messages.

53

The Connection-Oriented Paradigm#ConstantPerror MessageExplanation

22EINVALInvalid argumentInvalid argument passed to accept call

24EMFILEToo many files openProcess has exceeded the maximum

number of files open.

63ENOSROut of streams resources

Insufficient STREAMS resources for

specified operation.

71EPROTOProtocol errorAn error in protocol has occurred.

85ERESTARTInterrupted system call should be restarted

accept call must be restarted.

88ENOTSOCKSocket operation on non-socket

The socket is a file descriptor, not a socket descriptor.

93EPROTONOSUPPORTProtocol not supportedInvalid protocol specified.

Table 10.12. accept Error Messages.

54

The Connection-Oriented Paradigm#ConstantPerror MessageExplanation

94ESOCKTNOSUPPORTSocket type not supportedInvalid socket type specified.

95EOPNOTSUPPOperation not supportedis not of type SOCK_STREAM.

103ECONNABORTEDSoftware caused connection

abort

Connection aborted.

105ENOBUFSNo buffer space availableInsufficient memory to perform

operation.

110ETIMEDOUTConnection timed outUnable to establish connection within specified time limit.

Table 10.12. accept Error Messages.

55

The Connection-Oriented Paradigm In the connection-oriented setting, the client

process initiates the connection with the server process with the connect system call.

(Table 10.13.)

56

The Connection-Oriented Paradigm

Return

Summaryint connect(int sockfd,

const struct sockaddr *serv_addr,

socklen_t addrlen);

Include File(s)

>sys/types.h<<sys/socket.h>

Manual Section2

SuccessFailureSets errno

0-1Yes

Table 10.13. Summary of the connect System Call.

Return

57

The Connection-Oriented Paradigm The connect system call takes three arguments:

The first argument is a valid integer socket descriptor.

The second argument, *serv_addr, is handled differently depending upon whether the referenced socket is connection-oriented or connectionless.

» In the connection-oriented setting, *serv_addr references the address of the socket with which the client wants to communicate (i.e., the serving process's address).

» For a connectionless socket, *serv_addr references the address to which the datagrams are to be sent.

58

The Connection-Oriented Paradigm The third argument, addrlen, conveys the size of

the *serv_addr reference. Should the connect call fail, it sets errno.

(Table 10.14)

59

The Connection-Oriented Paradigm#ConstantPerror MessageExplanation

1EPERMOperation not permitted• Attempt to broadcast without having

broadcast flag set.

• Request failed due to firewall.

4EINTRInterrupted system callA signal was received during the connect process.

9EBADFBad file descriptorThe socket reference is invalid.

11EAGAINResource temporarily

unavailable

No more free local ports.

13EACCESPermission deniedPermission denied

14EFAULTBad addressAddress referenced by *serv_addr is

outside the user's address space.

22EINVALInvalid argumentnamelength is not correct for address

referenced by *serv_addr.

Table 10.14. connect Error Messages.

60

The Connection-Oriented Paradigm#ConstantPerror MessageExplanation

63ENOSROut of streams resourcesInsufficient STREAMS resources for

specified operation.

88ENOTSOCKSocket operation on non-socket

The socket is a file descriptor, not a socket descriptor.

91EPROTOTYPEProtocol wrong type for socket

Conflicting protocols, socketfd

versus the *serv_addr reference.

97EAFNOSUPPORTAddress family not supported by protocol family

Address referenced by *serv_addr

cannot be used with this socket.

98EADDRINUSEAddress already in useLocal address referenced by

*serv_addr already in use.

99EADDRNOTAVAILCannot assign requested address

Address referenced by *serv_addr

not available on remote system.

101ENETUNREACHNetwork is unreachableCannot reach specified system.

Table 10.14. connect Error Messages.

61

The Connection-Oriented Paradigm#ConstantPerror MessageExplanation

106EISCONNTransport endpoint is already connected

sockfd already connected.

110ETIMEDOUTConnection timed outCould not establish a connection within

time limits.

111ECONNREFUSEDConnection refusedConnect attempt rejected; socket already

connected.

114EALREADYOperation already in progress

Socket is non-blocking, and no previous

connection completed.

115EINPROGRESSOperation now in progressSocket set as non-blocking, and

connection cannot be established

immediately.

Table 10.14. connect Error Messages.

62

The Connectionless Paradigm The sequence of events for connectionless client–server

communication has some common elements with connection-oriented communication.

Both the client and server still generate sockets using the socket call. The server and, most often, the client, bind their sockets to an address.

Both the server and client send and receive datagram packets to and from a specified address.

The server process sends its packets to the client address, and the client sends its packets to the server address.

(Figure 10.14)

63

The Connectionless Paradigm

Figure 10.14. A connectionless client–server communication sequence.

64

The Connectionless Paradigm The sendto call is one of several alternate ways

to write data to a socket.

(Table 10.19)

65

The Connectionless Paradigm

Return

Summaryint send (int s, const void *msg,size_t len,

int flags);

int sendto (int s,const void *msg,

size_t len, int flags,

const struct sockaddr *to, socklen_t

tolen);

int sendmsg(int s, const struct msghdr *msg,

int flags);

Include File(s)

<netinet/in.h>Manual Section2

SuccessFailureSets errno

Number of bytes sent.-1Yes

Table 10.19. Summary of the send, sendto, and sendmsg System Calls.

66

The Connectionless Paradigm

FlagMeaningMSG_OOBMessage out of band. At present this flag is valid only for Internet stream-

based sockets. Specifying MSG_OOB allows the process to send urgent data. The receiving process can choose to ignore the message.

MSG_DONTROUTEBypass routing tables and attempt to send message in one hop. This is often used for diagnostics purposes.

MSG_DONTWAITAdopt non-blocking operation for operations that block return EAGAIN.

MSG_NOSIGNALOn stream-based socket do not send a SIGPIPE error when one end of connection is broken.

MSG_CONFIRMWith SOCK_DGRAM and SOCK_RAW sockets, in Linux 2.3+, notify the link layer of successful reply from the other side.

Table 10.20. Flags for the send, sendto, and sendmsg Calls.

67

The Connectionless Paradigm#ConstantPerror MessageExplanation

4EINTRInterrupted system call

A signal was received by the process

before data was sent.

9EBADFBad file descriptorThe socket reference is invalid.

11EWOULDBLOCK,EAGAIN

Resource temporarily

unavailable

The socket is set to non-blocking,

and no connections are pending.

12ENOMEMCannot allocate memory

Insufficient memory to perform

operation.

14EFAULTBad addressAddress referenced by *serv_addr is

outside the user's address space.

Table 10.21. send, sendto, and sendmsg Error Messages.

68

The Connectionless Paradigm#ConstantPerror MessageExplanation

22EINVALInvalid argumenttolen argument contains an incorrect value.

32EPIPEBroken pipeLocal end of a connection-oriented

socket is closed.

88ENOTSOCKSocket operation on non-socket

The socket argument is a file descriptor, not a socket descriptor.

90EMSGSIZEMessage too longSocket type requires message to be sent to be atomic (all sent at once) and the message to send is too long.

105ENOBUFSNo buffer space availableOutput queue is full.

Table 10.21. send, sendto, and sendmsg Error Messages.

69

The Connectionless Paradigm Other than read, there are three system calls

comparable to send for receiving data from a socket descriptor. These calls are recv, recvfrom, and recvmsg. Unless otherwise specified (such as with fcntl), these calls will block if no message has arrived at the socket.

(Table 10.22)

70

The Connectionless Paradigm

Return

Summaryint recv(int s, void *buf, size_t len, int flags);

int recvfrom(int s, void *buf, size_t len,

int flags, struct sockaddr *from, socklen_t

*fromlen);

int recvmsg(int s, struct msghdr *msg, int flags);

Include File(s)

<netinet/in.h>Manual Section2

SuccessFailureSets errno

Number of bytes received-1Yes

Table 10.22. Summary of the recv, recvfrom, and recvmsg System Calls.

71

The Connectionless Paradigm

FlagMeaningMSG_ERRQUEUEReceive error messages from the error message queue. The details of

how to implement error message retrieval is beyond the scope of this text (see the manual page on recv for specifics).

MSG_NOSIGNALWith a stream socket, do not raise a SIGPIPE error when the other end of the socket disappears.

MSG_OOBMessage out of band. At present this flag is valid only for Internet stream-based sockets. Specifying MSG_OOB allows the process to read urgent out-of-band data.

MSG_PEEKLook at the current data but do not consume it. Subsequent read-receive type calls will retrieve the same peeked-at data.

MSG_TRUNCWith datagram socket, return the real length of the message even if it exceeds specified amount.

MSG_WAITALLWait until the full request for data has been satisfied.

Table 10.23. Flags for the recv, recvfrom, and recvmsg Calls.

72

The Connectionless Paradigm#ConstantPerror MessageExplanation

4EINTRInterrupted system call

A signal was received by process before data

was received.

9EBADFBad file descriptorThe socket reference is invalid.

11EAGAINResource temporarily unavailable

• The socket is set to non-blocking, and no

connections are pending.

• Timer expired before data was received.

14EFAULTBad addressArgument references a location outside user

address space.

22EINVALInvalid argumentAn argument contains incorrect value.

88ENOTSOCKSocket operation on non-socket

The socket argument is a file descriptor, not

a socket descriptor.

107ENOTCONNTransport endpoint is not connected

A connection-oriented socket has not been

connected.

111ECONNREFUSEDConnection refusedRemote host has refused the connection

request.

Table 10.24. recv, recvfrom, and recvmsg Error Messages