bsd sockets programming

Upload: alisssa

Post on 10-Apr-2018

232 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Bsd Sockets Programming

    1/196

    BSD So cke ts Inte rface P rogramm ersGuide

    Edit ion 6

    B2355-90136

    HP 9000 Netw orking

    E0497

    Printed in: United States

    Copyright 1997 Hewlett-Packard Company.

  • 8/8/2019 Bsd Sockets Programming

    2/196

    2

    Lega l Notices

    The informa tion in t his docum ent is subject t o cha nge without notice.

    Hewlett-Packard m akes no warranty of any k ind with regard to this

    m anu al, includ ing, but not limited to, the im plied warranties of

    merchantability and fitness for a particular purpose. Hewlett-Packard

    sha ll not be held liable for errors contained h erein or direct, indirect,

    special, incidental or consequen tial da ma ges in conn ection with t he

    fur nishing, performa nce, or u se of th is mat erial.

    Warranty. A copy of the specific war ra nt y term s ap plicable to yourHewlett- Packar d product and r eplacement par ts can be obtained from

    your local Sales an d Ser vice Office.

    Restr icted Rights Legend. Use, du plicat ion or disclosur e by the U.S.

    Governmen t is su bject t o restrictions a s set forth in subpar agra ph (c) (1)

    (ii) of the Rights in Techn ical Dat a an d Computer Softwar e clau se at

    DFARS 252.227-7013 for DOD a gencies, an d su bpar agr aph s (c) (1) and

    (c) (2) of the Commer cial Compu ter Softwa re Rest ricted Right s clau se at

    FAR 52.227-19 for other agen cies.

    HE WLETT-PACKARD COMPANY 3000 Han over S tr eet P alo Alto,

    California 94304 U.S.A.

    Use of this manual and flexible disk(s) or tape cartridge(s) supplied forth is pack is rest ricted t o this pr oduct only. Additiona l copies of the

    programs may be ma de for secur ity an d back-up pur poses only. Resale of

    the pr ogra ms in th eir present form or with a lterat ions, is expressly

    prohibited.

    Copyright Notices. copyright 1983-97 Hewlet t-Packa rd Compa ny, all

    rights reserved.

    Reproduction, ad apt ation, or t ra nslat ion of this documen t with out prior

    written permission is pr ohibited, except a s a llowed u nder the copyright

    laws.

    copyright 1979, 1980, 1983, 1985-93 Regent s of th e Un iversity of

    California

    This softwar e is based in part on the Fourt h Berk eley Softwar e

    Distribution un der license from th e Regents of the Un iversity of

    California.

  • 8/8/2019 Bsd Sockets Programming

    3/196

    3

    copyright 1980, 1984, 1986 Novell, In c. copyright 1986-1992 Sun

    Microsystems, Inc. copyright 1985-86, 1988 Massachusetts Institute of

    Techn ology. copyright 1989-93 The Op en Softwa re Founda tion, In c.

    copyright 1986 Digital Equipment Corporation. copyright 1990

    Motorola, In c. copyright 1990, 1991, 1992 Cornell U niversit y

    copyright 1989-1991 The Un iversity of Mar yland copyright 1988

    Carn egie Mellon University

    Tradema rk Notices UNIX is a registered tradema rk in t he United

    States and other countries, licensed exclusively through X/Open

    Compan y Limited.

    X Window System is a tra demar k of th e Massachusett s Inst itute of

    Technology.

    MS-DOS an d Microsoft a re U.S. register ed tr adem ar ks of Microsoft

    Corporation.

    OSF/Motif is a tra demar k of th e Open Softwar e Foun dat ion, Inc. in the

    U.S. and other coun tr ies.

  • 8/8/2019 Bsd Sockets Programming

    4/196

  • 8/8/2019 Bsd Sockets Programming

    5/196

    Contents

    5

    1 . B SD Sockets Concept s

    In tr oduct ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17

    Key Terms and Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17

    How You Ca n U se BSD Socket s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20

    The Clien t-Ser ver Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21

    Crea tin g a Conn ection: th e Client-Server Model . . . . . . . . . . . . . . . . .21

    BSD Sockets Libra ry Rout ines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .25

    2 . Us ing Internet S tream Sockets

    Over view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29

    Pr epa rin g Address Var iables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31

    Declaring Socket Address Variables . . . . . . . . . . . . . . . . . . . . . . . . . . .31

    Gett ing th e Remote H ost's Int ern et Addr ess . . . . . . . . . . . . . . . . . . . .32

    Gett ing th e Port Addr ess for t he Desir ed Service . . . . . . . . . . . . . . . .33

    Using a Wildcard Local Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34

    Writin g th e Server Pr ocess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35

    Crea tin g a S ocket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35

    Bindin g a Socket Address t o the Ser ver P rocess's Socket . . . . . . . . . .36

    Sett ing Up th e Server t o Wait for Conn ection Requ ests . . . . . . . . . . .37

    Acceptin g a Conn ection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .38

    Writin g th e Client Pr ocess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40

    Crea tin g a S ocket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40

    Requesting a Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41

    Send ing an d Receiving Dat a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .43

    Sen din g Dat a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .43

    Receiving Da ta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .44

    Fla g Opt ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45

    Closing a Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .47

  • 8/8/2019 Bsd Sockets Programming

    6/196

    6

    Contents

    Exam ple Using Intern et Str eam S ockets . . . . . . . . . . . . . . . . . . . . . . . . 48

    3. Advanced Topics for Stream Sockets

    Socket Op tions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

    Gett ing an d Set tin g Socket Options. . . . . . . . . . . . . . . . . . . . . . . . . . . 62

    SO_REUS EADDR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

    SO_KEE PALIVE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

    SO_DONTROUTE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

    SO_SNDBU F . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

    SO_RCVBUF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

    SO_LINGE R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

    SO_USE LOOPBACK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

    SO_OOBINLIN E . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

    SO_SNDLOWAT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

    SO_RCVLOWAT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

    SO_SNDTIME O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

    SO_RCVTIMEO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

    SO_TYPE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

    SO_ERROR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

    SO_BROADCAST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

    SO_REUS EP ORT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

    Synchr onous I/O Multiplexing with Select . . . . . . . . . . . . . . . . . . . . . . . 72

    Sending an d Receiving Data Asynchronously . . . . . . . . . . . . . . . . . . . . 75

    Nonblockin g I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

    Usin g Shu tdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

    When to Shu t Down a Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

    Using Read and Write to Make Stream Sockets Transpar ent . . . . . . . 80

    Send ing an d Receiving Out -of-ban d Dat a . . . . . . . . . . . . . . . . . . . . . . . . 81

  • 8/8/2019 Bsd Sockets Programming

    7/196

    Contents

    7

    4 . Us ing Internet Datagram Socket s

    Over view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .86

    Pr epa rin g Address Var iables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .88

    Declaring Socket Address Variables . . . . . . . . . . . . . . . . . . . . . . . . . . .88

    Gett ing th e Remote H ost's Netw ork Address . . . . . . . . . . . . . . . . . . . .89

    Gett ing th e Port Addr ess for t he Desir ed Service . . . . . . . . . . . . . . . .90

    Using a Wildcard Local Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91Writin g th e Server a nd Clien t P rocesses . . . . . . . . . . . . . . . . . . . . . . . . .92

    Cr ea tin g Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .92

    Bindin g Socket Addresses t o Data gra m Sockets . . . . . . . . . . . . . . . . .93

    Send ing an d Receiving Messa ges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95

    Send ing Messa ges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95

    Receiving Mes sa ges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .96

    Fla g Opt ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .98

    Closing a Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .100

    Exa mple U sing Da ta gra m S ocket s . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101

    5. Advanced Topics for Internet Datagram Sockets

    SO_BROADCAST Socket Opt ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .111

    Specifying a Default Socket Address . . . . . . . . . . . . . . . . . . . . . . . . . . .112

    When to Specify a Defau lt Socket Address . . . . . . . . . . . . . . . . . . . . .113

    Synchr onous I/O Mult iplexing wit h Select. . . . . . . . . . . . . . . . . . . . . . .114

    Send ing an d Receiving Dat a Asynchr onously . . . . . . . . . . . . . . . . . . . .115

    Send ing an d Receiving IP Mu lticast Da ta gra ms . . . . . . . . . . . . . . . . . .116

    Send ing IP Mult icast Dat agr am s . . . . . . . . . . . . . . . . . . . . . . . . . . . .116

    Receiving IP Mu lticast Da ta gra ms . . . . . . . . . . . . . . . . . . . . . . . . . . .118

    Nonblockin g I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121

  • 8/8/2019 Bsd Sockets Programming

    8/196

    8

    Contents

    Usin g Broadcast Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

    6 . Us ing UNIX Domain Stream Sockets

    Over view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

    Pr epar ing Address Var iables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

    Declar ing Socket Address Var iables . . . . . . . . . . . . . . . . . . . . . . . . . 126

    Writin g th e Server Pr ocess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128Crea tin g a Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128

    Binding a Socket Address to th e Server Pr ocess's Socket . . . . . . . . 129

    Setting t he Server U p to Wait for Connection Requests . . . . . . . . . . 130

    Accepting a Connection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131

    Writin g th e Client P rocess. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

    Crea tin g a Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

    Request ing a Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134

    Send ing a nd R eceiving Dat a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136

    Send ing Dat a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136

    Receiving Dat a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137Fla g Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

    Closing a Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

    Exam ple Using UNIX Domain Str eam Sockets . . . . . . . . . . . . . . . . . . 140

    7 . Us ing UNIX Domain Datagram Socket s

    Over view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

    Pr epar ing Address Var iables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150

    Declar ing Socket Address Var iables . . . . . . . . . . . . . . . . . . . . . . . . . 150

    Writing the Ser ver an d Client Pr ocesses . . . . . . . . . . . . . . . . . . . . . . . 152

    Crea tin g Socket s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

    Binding Socket Addresses to UNIX Doma in Data gram Sockets . . . 153

  • 8/8/2019 Bsd Sockets Programming

    9/196

    Contents

    9

    Send ing an d Receiving Messa ges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .155

    Send ing Messa ges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .155

    Receiving Mes sa ges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .156

    Closing a Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .159

    Exam ple Using UNIX Domain Data gram Sockets . . . . . . . . . . . . . . . .160

    8 . P r og ra m m in g H i n tsTrou blesh ootin g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .167

    Usin g Diagnost ic Utilities as Troublesh ootin g Tools. . . . . . . . . . . . . . . 168

    Adding a Server P rocess to th e Int ernet Daemon . . . . . . . . . . . . . . . . .169

    Sum ma ry Tables for Syst em a nd Libr ar y Calls. . . . . . . . . . . . . . . . . . .173

    Port ab ility Is su es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177

    Porting Issues for IP C Fu nctions a nd Libra ry Calls . . . . . . . . . . . . .177

    Porting Issues for Ot her Fu nctions a nd Libra ry Calls Typically Used by

    IPC178

    A. BSD Sockets Quick Reference Table

    Quick Referen ce Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .182

    Glossary

  • 8/8/2019 Bsd Sockets Programming

    10/196

    10

    Contents

  • 8/8/2019 Bsd Sockets Programming

    11/196

    11

    Printin g History

    The manu al printing date and par t nu mber indicate i ts current edition.

    The print ing date will cha nge when a new edition is print ed. Minor

    chan ges may be ma de at reprint without changing the printing date. the

    manu al part num ber will chan ge when extensive chan ges are ma de.

    Manu al upda tes ma y be issued between editions to correct err ors or

    docum ent product cha nges. To ensure t ha t you receive the u pdat ed or

    new editions, you sh ould subscribe to the a ppropriate pr oduct su pport

    service. See your HP sales repr esenta tive for details.

    First E dition: Februar y 1991

    Second E dition: Ju ly 1992 (HP -UX Release 9.0)

    Third E dition: Ja nu ar y 1995 (HP -UX Release 10.0)

    Fourth Edition: December 1995 (HP-UX Release 10.10)

    Fifth Edition: J un e 1996

    Sixth E dition: April 1997 (HP-UX Release 10.30)

  • 8/8/2019 Bsd Sockets Programming

    12/196

    12

  • 8/8/2019 Bsd Sockets Programming

    13/196

    13

    Preface

    This guide describes HP's BSD Sockets. BSD Sockets is a set of

    programm ing development tools for interpr ocess commun ication. H P's

    implemen ta tion of BSD Socket s is a full set of socket s from th e

    net working ser vices originally developed by th e Un iversity of Californ ia

    at Berkeley (UCB).

    Th eBSD Sockets Interface Programmer's Guide is the prima ry reference

    for progra mmer s who write or ma intain BSD Sockets a pplications on HP

    9000 comput ers. This guide also provides inform at ion a bout BSD Socket s

    featu res for n ode mana gers who design HP 9000 networks.

    This guide is written for intermediat e to advanced program mers a nd

    assumes that :

    Your HP 9000 networking is installed and runn ing on your local host.

    You have all the login nam es you may be associated with (these may

    be obta ined from your node man ager).

    You have a l ist of other h osts or nodes your H P 9000 product can

    commu nicate with (this list may a lso be obtained from your node

    manager).

    This gu ide is organ ized as follows:

    Chapter 1 BSD Sockets Concepts provides an overview of the

    Client-Server Model.

    Chapter 2 Using Internet Stream Sockets describes the st eps

    involved in creat ing an int ernet strea m socket u sing

    the AF_INET address family.

    Chapter 3 Advan ced Topics for Stream Sock ets explains

    socket options, synchronous I/O multiplexing with

    select, sending a nd receiving da ta asynchronously,

    nonblocking I/O, us ing shutdown, using read and

    write to make stream sockets tran sparent, and

    sending a nd receiving out -of- band dat a.

    Chapter 4 Using Internet Datagram Sockets describes th e

    steps involved in creat ing an inter net da tagr am socket

    connection.

  • 8/8/2019 Bsd Sockets Programming

    14/196

    14

    Chapter 5 Advanced Topics for Internet Datagram So ckets

    includes informa tion about default socket addr ess,

    synchronous I/O multiplexing with select, sending

    an d receiving IP multicast dat agra ms, and broadcast

    addresses.

    Chapter 6 Using UNIX Domain Strea m Socke ts describes th e

    steps involved in creat ing a UN IX Doma in str eam

    socket conn ection bet ween t wo processes executin g on

    the sa me node.

    Chapter 7 Using UNIX Domain Data gram Socke ts describes

    the st eps required to excha nge data between AF_UNIX

    dat agra m sockets on the sam e node withoutestablishing a connection.

    Chapter 8 Programming Hints contains informat ion about

    troubleshooting, port addresses, diagnostic utilities,

    internet daemon, inetd, port ability issues, an d system

    an d library calls.

    Appendix A BSD Socke ts Quick Reference Table summarizes

    th e differen ces in calls for th e two sets of socket s

    beha vior: HP -UX BSD Socket s an d X/Open S ocket s.

  • 8/8/2019 Bsd Sockets Programming

    15/196

    15

    1 BSD Socke ts Con cepts

    The BSD Sockets facility allows you to create distributed applications

    tha t pass data between programs (on t he same computer or on separat e

    comput ers on the network) with out requiring an u nderst an ding of th e

  • 8/8/2019 Bsd Sockets Programming

    16/196

    16 Chapter 1

    BSD Sockets Concepts

    ma ny layer s of net working pr otocols. This is accomplished by usin g a set

    of system calls. These s ystem calls allow you t o crea te commu nication

    endpoints called sockets and tr ansfer data between them.

    NOTE BSD Sockets is a pr ogra m development tool. Before you at tempt to useBSD Sockets, you may need to familiarize yourself with the C

    programm ing langua ge and the HP -UX opera ting system. You could

    implement a BSD Sockets a pplicat ion u sing FORTRAN or Pascal, but a ll

    librar y calls and include files ar e implemented in C.

  • 8/8/2019 Bsd Sockets Programming

    17/196

    Chapter 1 17

    BSD Sockets Concepts

    Introduction

    Introduction

    This guide describes the s teps involved in establishing an d using BSD

    Socket s conn ections. It also describes th e protocols you mu st us e and

    how the BSD Sockets system calls intera ct. The details of each system

    call are d escribed in th e corr esponding ma n pa ges.

    Key Terms a nd Conce pts

    For a basic underst an ding of BSD Sockets an d its gener al model, you

    should review the following term s a nd definitions.

    address family The address format used to interpret addresses

    specified in socket operat ions. The int ernet addr ess

    family (AF_INET) and the Berkeley UNIX Domain

    addr ess family (AF_UNIX) are su pported.

    address ing A means of labeling a socket so that it is

    distinguishable from other sockets on a h ost.

    associat ion A BSD Socket s conn ection is d efined by a n

    association. An AF_INET association contains the

    (protocol, local addr ess, local port, rem ote add ress,rem ote port)-tu ple. An AF_UN IX associat ion

    cont ain s t he (protocol, local addr ess, peer

    address)-tuple. Associations must be unique;

    duplicate associations on the sa me h ost can not

    exist. The tu ple is creat ed when t he local and

    remote socket a ddresses ar e boun d an d conn ected.

    This means t ha t th e association is creat ed in two

    steps, and th ere is a chance tha t two potent ial

    associations could be alike between steps. The host

    prevents duplicate associations by checking for

    un iqueness of th e tuple at conn ection time, and

    reporting an er ror if th e tuple is not unique.

  • 8/8/2019 Bsd Sockets Programming

    18/196

    18 Chapter 1

    BSD Sockets Concepts

    Introduction

    binding Before a socket can be accessed across the network,

    it must be boun d to an a ddress. Binding associates a

    socket a ddress with a socket a nd m akes t he socket

    accessible to other sockets on the network. Once a

    socket address is bound, other sockets can connect

    to the socket a nd sen d dat a t o or r eceive data from

    it .

    channe l Commu nication pa th creat ed by establishing a

    conn ection bet ween sockets.

    communicat ion

    domain

    A set of properties th at describes the char acteristics

    of processes communicating through sockets. Theintern et (AF_INET) addr ess family doma in is

    supported. Th e UN IX Doma in (AF_UNIX) addr ess

    family domain is a lso sup ported, for local

    comm un icat ion only.

    internet

    address

    A four-byte address t ha t identifies a n ode on t he

    network.

    message The data sent in one UDP packet.

    packet A message or dat a u nit tha t is tra nsmitted between

    communicating processes.

    peer The r emote process with which a pr ocesscommunicates.

    port An a ddress within a host that is used to

    different iate between m ultiple sockets with t he

    sam e internet addr ess. You can u se port a ddress

    values 1024 thr ough 65535. (Port ad dresses 1

    th rough 1023 are reserved for t he su per-user.)

    protocols Two int ernet tr an sport layer protocols can be u sed

    with BSD Sockets. They ar e TCP, which implements

    strea m sockets, an d UDP, which implement s

    datagram sockets.

    socket Sockets ar e commu nication endpoints. A pair ofconn ected s ockets provides a n interface similar to

    th at of HP -UX pipes. A socket is ident ified by a

    socket descriptor.

  • 8/8/2019 Bsd Sockets Programming

    19/196

    Chapter 1 19

    BSD Sockets Concepts

    Introduction

    socket address For t he inter net a ddress family (AF_INET), the

    socket a ddress consists of the intern et a ddress, port

    addr ess an d addr ess family of a socket. The intern et

    an d port a ddress combinat ion allows the n etwork to

    locate a socket . For UN IX Doma in (AF_UN IX), th e

    socket addr ess is th e directory pathn ame bound to

    th e socket.

    socket

    descriptor

    A socket descriptor is a n HP -UX file descriptor t ha t

    references a socket instead of an ordinary file.

    Therefore, it can be used for reading, writing, or

    most sta nda rd file system calls after a BSD Sockets

    conn ection is established. System calls tha t use filedescriptors (e.g. read, write, select) can be used

    with socket descriptors. All BSD Socket s fun ctions

    use socket descriptors as a rgum ents.

    TCP Pr ovides the un derlying commu nication s upport for

    strea m sockets. The Tran smission Cont rol Protocol

    (TCP) is used to implement reliable, sequenced,

    flow-cont rolled two-way commu nication based on

    byte strea ms similar t o pipes. Refer t o the tcp(7p)

    man page for more informa tion on TCP.

    UDP Pr ovides the un derlying commu nication s upport for

    dat agra m sockets. The User Data gram P rotocol(UDP) is an un reliable pr otocol. A process r eceiving

    messages on a dat agra m socket could find m essages

    ar e dup licat ed, out-of-sequen ce, or m issing.

    Messages retain their record boundaries and are

    sent a s individua lly addr essed packets. There is no

    concept of a conn ection bet ween th e commu nicat ing

    socket s. Refer t o the udp(7p) ma n pa ge for more

    information on UDP.

    UNIX Dom ain

    Protocol

    In a ddition, t he U NIX Domain protocol may be used

    with AF_UNIX sockets for interprocess

    commu nication on t he sa me n ode. Refer t o the

    unix(7p) ma n pa ge for more informa tion on t he

    UN IX Doma in pr otocol.

  • 8/8/2019 Bsd Sockets Programming

    20/196

    20 Chapter 1

    BSD Sockets Concepts

    How You Can Use BSD Sockets

    How You Can Use BSD Soc kets

    The best exam ple of how BSD Sockets can be used is th e Int ernet

    Services. These services use BSD Sockets to communicate between

    rem ote hosts. Usin g th e BSD Socket s facility, you can writ e your own

    distributed a pplicat ion pr ogram s to do a variety of ta sks.

    For exam ple, you can wr ite distribut ed applicat ion programs to:

    Access a remote da tabase.

    Access mult iple computers at one t ime.

    Spread tasks across severa l hos t s.

  • 8/8/2019 Bsd Sockets Programming

    21/196

    Chapter 1 21

    BSD Sockets Concepts

    The Client-Server Model

    The Clien t-Se rver Mode l

    Typical BSD Sockets applications consist of two separate application

    level processes; one pr ocess (th e cl ient) requests a conn ection and t he

    oth er p rocess (the server) accepts it.

    The server process creat es a socket, binds an addr ess to it, an d sets up a

    mechanism (called a listen queue) for receiving connection requests. The

    client process creates a socket an d r equests a conn ection to th e server

    process. Once the server pr ocess accepts a client process's request an d

    esta blishes a conn ection, full-duplex (two-way) commu nicat ion can occur

    between th e two sockets.

    This set of conventions must be implemented by both processes.

    Depending upon t he n eeds of your applicat ion, your implement ation of

    the model can be symmetr ic or a symmetr ic. In a symmetr ical ap plication

    of the m odel, eith er pr ocess can be a server or a client . In an

    asymmet rical a pplicat ion of the m odel, there is a clearly defined server

    process and client pr ocess. An exam ple of an asym met rical application is

    the ftp service.

    Creatin g a Conn ection : the Clien t-Serve r

    Model

    The following figur es illustr at e conceptu al views of th e client -server

    model at t hree different stages of establishing a conn ection. The

    completed st eps ar e included in each figure.

  • 8/8/2019 Bsd Sockets Programming

    22/196

    22 Chapter 1

    BSD Sockets Concepts

    The Client-Server Model

    Figu re 1-1 Clie nt-S erve r in a P re -Con ne ction State

  • 8/8/2019 Bsd Sockets Programming

    23/196

    Chapter 1 23

    BSD Sockets Concepts

    The Client-Server Model

    Figu re 1-2 Clie nt-Se rve r at Tim e of Con ne ction Re qu est

  • 8/8/2019 Bsd Sockets Programming

    24/196

    24 Chapter 1

    BSD Sockets Concepts

    The Client-Server Model

    Figu re 1-3 Clie nt-Se rve r Wh en Con ne ction is Establish ed

  • 8/8/2019 Bsd Sockets Programming

    25/196

    Chapter 1 25

    BSD Sockets Concepts

    BSD Sockets Library Routines

    BSD Sock ets Library Routin es

    The librar y rout ines and system calls that you need to implement a BSD

    Sockets a pplication ar e described thr oughout th e guide. In addition, a

    complete list of all these routines an d system calls is provided in t he

    Summary Tables for Library and System Calls section of chapter 8,

    Pr ogram ming H ints.

    The library r outines ar e in th e common c librar y nam ed libc.sl.

    Therefore, you do not need to specify any library name on the cc

    comman d line to use th ese librar y calls, libc.sl is used automatically.

  • 8/8/2019 Bsd Sockets Programming

    26/196

    26 Chapter 1

    BSD Sockets Concepts

    BSD Sockets Library Routines

  • 8/8/2019 Bsd Sockets Programming

    27/196

    27

    2 Usin g In te rn e t Stream Socke ts

  • 8/8/2019 Bsd Sockets Programming

    28/196

    28 Chapter 2

    Using Internet Stream Sockets

    NOTE Release 10.10 an d lat er r eleases su pport t wo var iations of sockets

    beha vior: classic HP -UX socket s an d X/Open s ocket s. By defau lt, user s

    receive classic HP -UX socket s. To use X/Open s ocket s, user s mu st m ak e

    an addition to their m ake files by including the -l xnet ar gument with

    the c89 or cc utilities.

    User s ma y also use t he lint ut ility to check for possible violations t o the

    X/Open socket s specificat ion by includin g -l xnet to th e ar gum ent list of

    the lint ut ility.

    User s mu st a lso define th e following for X/Open s ocket s beha vior:

    _XOP E N_S OU RCE ;

    _XOPEN_SOURCE_EXTENDED = 1

    See Appendix A for a ta ble which sum ma rizes th e differences in calls for

    th e two varia tions of socket s beha vior. A quick r eference car d listing

    these call differences is also available. For detailed information about

    HP -UX sockets, see the rema inder of this ma nu al as well as th e man

    pages. For det ailed informa tion a bout X/Open socket s, see CAE

    Specification, Networking Services, Issue 4, X/Open and the man pages.

    This cha pter describes creat ing an int ernet strea m socket conn ection

    using the AF_INE T addr ess fam ily.

  • 8/8/2019 Bsd Sockets Programming

    29/196

    Chapter 2 29

    Using Internet Stream Sockets

    Overview

    Overview

    Inter net TCP st ream sockets provide bidirectional, reliable, sequenced

    an d u ndu plicat ed flow of data without record boun dar ies. The following

    table lists the steps involved in creating an d term inat ing a BSD Sockets

    connection using s trea m sockets.

    Ta ble 2-1 Cre atin g/Te rm in atin g BS D S oc ke ts Co nn ec tio ns Us in g In te rn et

    Stream Sockets

    Client

    ProcessActivity

    SystemCall Used Server ProcessActivity System CallUsed

    create a socket socket() create a socket socket()

    bind a socket

    address

    (optional)

    bind() bind a socket

    address

    bind()

    listen for incomin g

    connection

    requests

    listen()

    request a

    connection

    connect()

    accept conn ection accept()

    send data write() or

    send()

    receive dat a read() or

    recv()

    send data write() or

    send()

    receive dat a read() or

    recv()

    disconnect

    socket

    (optional)

    shutdown()

    or close()

    disconn ect s ocket

    (optional)

    shutdown()

    or close()

  • 8/8/2019 Bsd Sockets Programming

    30/196

    30 Chapter 2

    Using Internet Stream Sockets

    Overview

    Ea ch of these st eps or activities is described in more deta il in the

    following sections. The d escription of each a ctivity specifies a system call

    an d includes:

    What happens when the sys tem ca ll is used .

    Wh en t o m a ke th e ca ll.

    Wh a t t h e p ar a met er s d o.

    How the call interacts with other BSD Sockets system calls.

    Where to find details on the system cal l.

    The str eam socket program examples are at the en d of th ese descriptive

    sections. You can refer to the example code as you work through thedescriptions.

  • 8/8/2019 Bsd Sockets Programming

    31/196

    Chapter 2 31

    Using Internet Stream Sockets

    Preparing Address Variables

    Pre paring Address Variables

    Before you creat e a conn ection, est ablish t he corr ect varia bles an d collect

    the inform ation th at you n eed to request a conn ection.

    Your ser ver pr ocess n eeds to:

    Declare socket address var iables.

    Ass ign a wildcard address.

    Get the port address of the service that you want to provide.

    Your client process needs to:

    Declare socket address var iables.

    Get the remote hos t 's in te rnet address.

    Get the port address for the service that you want to use.

    These activities ar e described next. Refer to th e program exam ple at t he

    end of this chapter to see how th ese activities work together.

    Declaring Sock et Address Variables

    You need t o declar e a va riable of type st ru ct sockaddr_in to use for

    socket addr esses. For exam ple, the following declara tions ar e used in t heexample client pr ogra m:

    struct sockaddr_in myaddr; /* for local socket address */struct sockaddr_in peeraddr; /* for peer socket address */

    sockaddr_in is a s pecial case ofsockaddr and is used with t he

    AF_INET a ddressing domain. Both types ar e shown in th is cha pter, but

    sockaddr_in makes it easier to manipulate the internet an d port

    addr esses. Some of the BSD Sockets system calls are declared u sing a

    point er to sockaddr, but you can also use a pointer to sockaddr_in.

    Th e sockaddr_in address structure consists of the following fields:

  • 8/8/2019 Bsd Sockets Programming

    32/196

    32 Chapter 2

    Using Internet Stream Sockets

    Preparing Address Variables

    The ser ver pr ocess only needs a n a ddr ess for its own socket . Your client

    process may not need an address for its local socket. Refer to the

    inet(7f) man page for m ore informat ion on sockaddr_in.

    Getting the Re mote Ho st's Interne t Addres s

    gethostbyname obtains the internet address of the host and the length

    of tha t a ddress (as t he size of struct in_addr) from /etc/hosts or

    from NIS na me server. gethostbyname and its parameters are

    described in t he following ta ble.

    Include files: #include System call: struct hostent *gethostbyname(name)

    char *name;

    Funct ion resul t : pointer to s t ruct hostent containing internet address

    NU LL pointer (0) if failur e occurs.

    Example:

    Fie ld De scription

    short sin_family Specifies the ad dress family and sh ould

    always be set to AF_INET.

    u_short sin_port Specifies the port addr ess. Assign th is field

    when you bind t he port addr ess for th e

    socket or wh en you get a port addr ess for a

    specific service.

    struct inaddr

    sin_addr

    Specifies the intern et add ress. Assign this

    field when you get th e intern et add ress for

    the remote host.

    Parameter Description of Conten ts INP UT Value

    name pointer to a va lid host name

    (null-terminated string)

    host name string

  • 8/8/2019 Bsd Sockets Programming

    33/196

  • 8/8/2019 Bsd Sockets Programming

    34/196

    34 Chapter 2

    Using Internet Stream Sockets

    Preparing Address Variables

    #include struct servent *sp; /* pointer to service info */...sp = getservbyname (example, tcp);peeraddr.sin_port = sp->s_port;

    Whe n to Get the S erver's Sock et Address

    The server pr ocess needs t o get t he socket a ddress before binding th e

    listen socket. The client process needs to get the socket address before

    the client execut es a conn ection request . Refer t o the getservent(3n)

    man page for more informa tion on getservbyname.

    Using a Wildcard Local AddressWildcar d a ddressing simplifies local address binding. When an addr ess

    is assigned th e value of INADDR_ANY, the h ost interpr ets th e addr ess

    as a ny valid addr ess. This is useful for your ser ver process when you a re

    setting up t he listen socket. It mea ns th at t he server process does not

    have t o look u p its own int ernet addr ess. When INADDR_ANY is used a s

    a h ost addr ess, it a lso allows th e server to listen to all network

    connections on t he h ost. When a specific addr ess is used in t he bind, th e

    server can only listen to th at specific conn ection. Th us, IN ADDR_ANY is

    useful on a system in which mu ltiple LAN cards a re available, an d

    messa ges for a given socket can come in on an y of them .

    For exam ple, to bind a specific port a ddress t o a socket, but leave the

    local inter net add ress un specified, the following source code could beused:

    #include #include #include ...struct sockaddr_in sin;...s = socket(AF_INET, SOCK_STREAM, 0);sin.sin_family = AF_INET;sin.sin_addr.s_addr = INADDR_ANY;sin.sin_port = MYPORT;bind (s, &sin, sizeof(sin));

  • 8/8/2019 Bsd Sockets Programming

    35/196

    Chapter 2 35

    Using Internet Stream Sockets

    Writing the Server Process

    Writing th e Se rver Proce ss

    This section explains th e calls your ser ver process mu st m ake to conn ect

    with a nd ser ve a client pr ocess.

    Creating a Socke t

    The server pr ocess mu st call socket to create a commun icat ion

    endpoint. socket an d its par amet ers ar e described in the following

    table.

    Include files: #include #include

    System call: s = socket(af, type, protocol)int af, type, protocol;

    Fu nction resu lt: socket number (HP-UX file descriptor), 1 if failur e

    occurs.

    Example:

    s = socket (AF_INET, SOCK_STREAM, 0);

    The socket n um ber retu rn ed is the socket descriptor for the n ewly

    creat ed socket. This nu mber is an HP -UX file descriptor an d can be used

    for reading, writing or an y stan dar d file system calls after a BSD Sockets

    connection is established. A socket descriptor is treated like a file

    descriptor for an open file.

    Parame ter Description of Conten ts INP UT Value

    af address family AF_INET

    type socket type SOCK_STREAM

    pr otocol u nderlyin g prot ocol t o be

    used

    0 (defau lt) or valu e

    return ed bygetprotobyname

  • 8/8/2019 Bsd Sockets Programming

    36/196

    36 Chapter 2

    Using Internet Stream Sockets

    Writing the Server Process

    When to Create Sockets

    The server process should create a s ocket before any other BSD Sockets

    system calls. Refer to the socket(2) man page for more inform ation on

    socket.

    Binding a Socke t Address to the Se rver

    Process 's Socket

    After your ser ver process ha s created a socket, it m ust call bind to bind a

    socket a ddress. Unt il an addr ess is boun d to the server socket, other

    processes have no way to reference it.

    The server process mu st bind a specific port ad dress t o this socket, which

    is used for listening. Otherwise, a client process would not know what

    port t o connect t o for th e desired s ervice.

    Set up t he addr ess stru cture with a local address before you make a

    bind call. Use a wildcar d ad dress so your server pr ocess does not ha ve to

    look up its own intern et ad dress. bind and its param eters are described

    in t he following ta ble.

    Include files: #include #include #include

    System call: bind (s, addr, addrlen)int s;

    struct sockaddr *addr;int addrlen;

    Fu nction r esult: 0 if bind is successful, 1 if failure occurs.

    ParameterDescript ion of

    ContentsINPUT Value

    s socket descr iptor of loca l

    socket

    socket descriptor of socket

    to be bound

    addr socket address poin ter to address to be

    boun d to s

    addrlen length of socket address size of st ruct

    sockaddr_in

  • 8/8/2019 Bsd Sockets Programming

    37/196

    Chapter 2 37

    Using Internet Stream Sockets

    Writing the Server Process

    Example:

    struct sockaddr_in myaddr;...bind (ls, &myaddr, sizeof(struct sockaddr_in));

    When to Bind Sock et Addresses

    The server pr ocess should bind th e socket a ddress a fter th e socket is

    creat ed an d before a ny other BSD Sockets system calls. Refer t o the

    bind(2) man page for m ore inform ation on bind.

    Settin g Up th e Se rver to Wait for Conne ction

    RequestsOnce your server process has an addr ess boun d to it, it m ust call listen

    to set up a queue t ha t accepts incoming conn ection requests. The server

    process then monitors the queu e for requests (using select(2) or

    accept ). The ser ver process cann ot respond to a connection r equest

    un til it h as execut ed listen. listen and its param eters are described

    in t he following ta ble.

    Include files: none

    System call: listen(s, backlog)int s, backlog;

    Fu nction r esult: 0 if listen is successful, 1 if failure occurs.

    Example:

    listen (ls, 5);

    Parame ter De scription of Conte nts INP UT Value

    s socket descr iptor of loca l

    socket

    server socket s descriptor

    backlog preferred maximum

    nu mber of conn ection

    requests in the queue at

    any time

    size of queue (between 0

    an d SOMAXCONN)

  • 8/8/2019 Bsd Sockets Programming

    38/196

    38 Chapter 2

    Using Internet Stream Sockets

    Writing the Server Process

    backlog is th e pr eferred nu mber of una ccepted incoming conn ections

    allowed at a given time. The actual num ber may be greater th an the

    specified backlog. When th e request is full, furth er connection request s

    are rejected.

    A backlog of 0 specifies only 1 pen ding conn ection can exist a t a ny given

    time. SOMAXCONN is defin ed in . The defau lt setting

    is 20.

    When to Set Up Server to Listen

    The server pr ocess should be set u p to listen after socket is created an d

    boun d an d before t he ser ver can r espond to connection r equests. Refer t o

    the listen(2) ma n p age for m ore informat ion on listen.

    Accepting a Connect ion

    The server pr ocess can accept a ny conn ection requests t ha t ent er its

    queue a fter it executes listen. accept creat es a n ew socket for the

    connection a nd r etur ns t he socket descriptor for t he n ew socket. The new

    socket:

    Is created with the same propert ies as the old socket .

    Has the same bound port address as the old socket .

    Is connected to the client process's socket.

    accept blocks un til th ere is a conn ection r equest from a client p rocess in

    the queue, un less you ar e using n onblocking I/O. accept and its

    par amet ers a re described in t he following table.

    Include files: #include #include #include

    System call: s = accept(ls,addr,addrlen)int s;int ls;struct sockaddr *addr;int *addrlen;

  • 8/8/2019 Bsd Sockets Programming

    39/196

    Chapter 2 39

    Using Internet Stream Sockets

    Writing the Server Process

    Fu nction r esult: socket descriptor of new socket if accept is su ccessful,

    1 if failure occurs.

    Example:

    struct sockaddr_in peeraddr;...addrlen = sizeof(sockaddr_in);s = accept (ls, &peeraddr, &addrlen);

    There is n o way for the server pr ocess to indicate which requests it can

    accept. It mu st a ccept a ll requests or n one. Your server process can k eep

    tra ck of which process a conn ection request is from by examining t he

    address returned by accept. Once you have t his addr ess, you can use

    gethostbyaddr to get th e hostn am e. You can close down t he connection

    if you do not wan t t he server process to commun icate with t ha t

    par ticular client h ost or port.

    When to Accept a Connect ion

    The ser ver process sh ould accept a conn ection after execut ing th e

    listen call. Refer to th e accept(2) man page for m ore inform ation on

    accept.

    Parameter Conten ts INP UT ValueOUTPUT

    Value

    ls socket

    descriptor of

    local socket

    socket descriptor of

    server socket

    unchanged

    addr socket address poin ter to address

    structure where

    addr ess will be put

    pointer to

    socket

    addr ess of

    client socket

    th at servers

    new socket isconnected to

    addr len length of

    address

    point er to th e size

    of str uct

    sockaddr_in

    point er to the

    actual length

    of addr ess

    return ed in

    addr

  • 8/8/2019 Bsd Sockets Programming

    40/196

    40 Chapter 2

    Using Internet Stream Sockets

    Writing the Client Process

    Writing the Clien t Proce ss

    This section explains the calls your client process must make to connect

    with a nd be ser ved by a server pr ocess.

    Creating a Socke t

    The client process mu st call socket to creat e a commun icat ion en dpoint.

    socket an d its par amet ers ar e described in the following table.

    Include files: #include #include

    System call: s = socket(af, type, protocol)int af, type, protocol;

    Fu nction resu lt: socket nu mber (HP-UX file descriptor), 1 if failur e

    occurs.

    Example:

    s = socket (AF_INET, SOCK_STREAM, 0);

    The socket n um ber retu rn ed is the socket descriptor for t he n ewly

    creat ed socket. This number is a n H P-UX file descriptor an d can be used

    for reading, writing or a ny sta nda rd file system calls after a BSD Sockets

    connection is established. A socket descriptor is treated like a file

    descriptor for an open file.

    When to Create Sockets

    The client process should create sockets before requesting a connection.

    Refer t o the socket(2) man page for more informa tion on socket.

    Parame ter Description of Conten ts INP UT Valu e

    af address family AF_INET

    type socket type SOCK_STREAM

    pr ot ocol u nder lyin g pr ot ocol t o be

    used

    0 (defau lt) or valu e

    return ed by

    getprotobyname

  • 8/8/2019 Bsd Sockets Programming

    41/196

    Chapter 2 41

    Using Internet Stream Sockets

    Writing the Client Process

    Request ing a Connect ion

    Once the server process is listening for connection requests, the client

    process can r equest a conn ection with t he connect call. connect and its

    par amet ers a re described in t he following table.

    Include files: #include #include #include

    System call: connect(s, addr, addrlen)int s;struct sockaddr *addr;int addrlen;

    Fu nction r esult: 0 if conn ect is su ccessful, 1 if failur e occurs.

    Example:

    struct sockaddr_in peeraddr;...connect (s, &peeraddr, sizeof(struct sockaddr_in));

    connect initia tes a conn ection a nd blocks if the connection is not r eady,

    un less you ar e using nonblocking I/O. When t he conn ection is read y, the

    client process complet es its connect call an d th e server process can

    complet e its accept call.

    ParameterDescription of

    ContentsINPUT Value

    s socket descr iptor of loca l

    socket

    socket descriptor of socket

    requesting connection

    addr poin ter to the socket

    address

    point er t o the socket

    addr ess of the socket t o

    which client wa nt s to

    connect

    addr len length of address size of address st ructure

    point ed to by addr

  • 8/8/2019 Bsd Sockets Programming

    42/196

    42 Chapter 2

    Using Internet Stream Sockets

    Writing the Client Process

    NOTE The client pr ocess does not get feedback t ha t t he server p rocess ha s

    completed th e accept call. As soon as t he connect call returns, th e

    client pr ocess can send da ta. Local intern et an d port addr esses are bound

    when connect is executed if you have not already bound them yourself.

    These addr ess values ar e chosen by th e local host.

    When to Request a Conn ect ion

    The client process should requ est a conn ection after socket is creat ed an d

    after server socket h as a listening socket. Refer t o the connect(2) man

    page for m ore inform at ion on connect.

  • 8/8/2019 Bsd Sockets Programming

    43/196

    Chapter 2 43

    Using Internet Stream Sockets

    Sending and Receiving Data

    Sen ding and Receiv ing Data

    After t he connect and accept calls are successfully executed, the

    connection is established and dat a can be sent an d received between the

    two socket endpoint s. Becau se th e str eam socket descriptors corr espond

    to HP -UX file descriptors, you can use t he read and write calls (in

    addition to recv and send) to pass data t hrough a socket-termina ted

    channel.

    If you are considering the use of the read and write system calls

    instead of the send and recv calls described below, you should consider

    the following:

    If you use read and write instead ofsend and recv, you can use a

    socket for stdin or stdout.

    If you use read and write instead ofsend and recv, you can not use

    th e options specified with t he send or recv flags parameter.

    See the t able tha t lists other system calls in chapter 8, for more

    information on which of these system calls are best for your application.

    Sending Data

    send an d its par amet ers ar e described in th e following table.

    Include files: #include #include

    System call: count = send(s,msg,len,flags)int s;char *msg;int len, flags;

    ParameterDescription of

    ContentsINPUT Value

    s socket descr iptor of loca l

    socket

    socket descriptor of socket

    sending data

  • 8/8/2019 Bsd Sockets Programming

    44/196

    44 Chapter 2

    Using Internet Stream Sockets

    Sending and Receiving Data

    Fu nction resu lt: nu mber of bytes actu ally sent, 1 if failure occur s.

    Example:

    count = send (s, buf, 10, 0);

    send blocks u ntil th e specified nu mber of bytes ha ve been queued to be

    sent, u nless you ar e usin g nonblocking I/O.

    When to Send Da ta

    The server or client process should send da ta after t he conn ection is

    established. Refer t o the send(2) man page for m ore information on

    send.

    Receiv ing Data

    recv an d its para meter s ar e described in th e following table.

    Include files: #include #include

    System call: count = recv(s,buf,len,flags)int s;char *buf;int len, flags;

    msg pointer to da ta buffer poin ter to da ta to be sent

    len size of da ta buffer size of msg

    flags set t ings for opt iona l flags 0 or MSG_OOB

    ParameterDescript ion of

    ContentsINPUT Value

  • 8/8/2019 Bsd Sockets Programming

    45/196

    Chapter 2 45

    Using Internet Stream Sockets

    Sending and Receiving Data

    Fu nction r esult: nu mber of bytes actually received, 1 if failur e occurs.

    Example:

    count = recv(s, buf, 10, 0);

    recv blocks u ntil th ere is at least 1 byte of dat a t o be received, unless

    you a re u sing nonblocking I/O. The h ost does not wait for len bytes t o be

    available; if less than len bytes are available, tha t n umber of bytes are

    received.

    No more th an len bytes of data a re received. If there ar e more tha n len

    bytes of data on t he socket, th e rema ining bytes are r eceived on the n ext

    recv.

    Flag Option s

    The flag options a re:

    0 for no op t ions.

    MSG_OOB for out of band da ta .

    MSG_PEEK for a nondest ruct ive read .

    Use t he MSG_OOB option if you want to receive out of ban d da ta . Refer

    to the Sending and Receiving Out of Band Data section of chapter 3,Advanced Topics for St rea m Socket s, for more inform at ion.

    ParameterDescription of

    ContentsINPUT Value

    s socket descr iptor of loca l

    socket

    socket descriptor of socket

    receiving da ta

    buf poin ter to da ta buffer poin ter to buffer tha t is to

    receive da ta

    len maximum number of

    bytes that should be

    received

    size of dat a bu ffer

    flags set t ings for opt iona l flags 0, MSG_OOB or

    MSG_PEEK

  • 8/8/2019 Bsd Sockets Programming

    46/196

    46 Chapter 2

    Using Internet Stream Sockets

    Sending and Receiving Data

    Use th e MSG_PE EK option t o preview incoming dat a. If this option is

    set on a recv, any data r etur ned rema ins in the socket buffer as th ough

    it had n ot been rea d yet. The next recv returns the same data.

    When to Receive Da ta

    The server or client process should receive data after connection is

    established. Refer t o the recv(2) man page for m ore information on

    recv.

  • 8/8/2019 Bsd Sockets Programming

    47/196

  • 8/8/2019 Bsd Sockets Programming

    48/196

    48 Chapter 2

    Using Internet Stream Sockets

    Example Using Internet Stream Sockets

    Example Us ing Interne t Stream Sockets

    NOTE These programs ar e provided as examples only of strea m socket u sage

    and are not Hewlett-Packard supported products.

    These program examples demonstrate how to set up and use internet

    strea m sockets. These sample progra ms ar e in th e

    /usr/lib/demos/networking/socket directory. The client progra m

    is intended to ru n in conjunction with th e server program. The client

    program requests a ser vice called example from th e server progra m.

    The server process receives requests from the remote client process,

    ha ndles the request a nd ret ur ns th e results to the client pr ocess. Note

    that the server:

    Uses the wildcard address for the l is ten socket .

    Uses the ntohs addr ess conversion call to show port ing to a h ost t ha t

    requires it.

    Uses the SO_LINGER option for a graceful disconnect.

    The client process creates a conn ection, sends requ ests t o the ser ver

    process an d receives the resu lts from t he server pr ocess. Note th at th e

    client:

    Uses shutdown to indicate tha t it is done sending request s.

    Uses getsockname to see what socket ad dress was assigned to the

    local socket by th e host.

    Uses the ntohs addr ess conversion call to show port ing to a h ost t ha t

    requires it.

    Before you r un th e example programs, ma ke th e following ent ry in t he

    two host's /etc/services files:

    example 22375/tcp

    The s ource code for t hese two pr ogram s follows

    /** S E R V . T C P** This is an example program that demonstrates the use of stream* sockets as a BSD Sockets mechanism. This contains the server,* and is intended to operate in conjunction with the client* program found in client.tcp. Together, these two programs

  • 8/8/2019 Bsd Sockets Programming

    49/196

    Chapter 2 49

    Using Internet Stream Sockets

    Example Using Internet Stream Sockets

    * demonstrate many of the features of sockets, as well as good* conventions for using these features.** This program provides a service called example. In order for* it to function, an entry for it needs to exist in the* /etc/services file. The port address for this service can be* any port number that is likely to be unused, such as 22375,* for example. The host on which the client will be running* must also have the same entry (same port number) in its* /etc/services file.**/

    #include #include #include #include

    #include #include

    int s; /* connected socket descriptor */int ls; /* listen socket descriptor */

    struct hostent *hp; /* pointer to host info for remote host */struct servent *sp; /* pointer to service information */

    long timevar; /* contains time returned by time() */char *ctime(); /* declare time formatting routine */

    struct linger linger = {1,1};/* allow lingering, graceful close; *//* used when setting SO_LINGER */

    struct sockaddr_in myaddr_in; /* for local socket address */struct sockaddr_in peeraddr_in;/* for peer socket address */

    /*

    * M A I N** This routine starts the server. It forks, leaving the child* to do all the work, so it does not have to be run in the* background.It sets up the listen socket, and for each incoming* connection, it forks a child process to process the data.* It will loop forever, until killed by a signal.*/main(argc, argv)int argc;char *argv[];{

    int addrlen;/* clear out address structures */

    memset ((char *)&myaddr_in, 0, sizeof(struct sockaddr_in));

    memset ((char *)&peeraddr_in, 0, sizeof(struct sockaddr_in));/* Set up address structure for the listen socket. */

    myaddr_in.sin_family = AF_INET;/* The server should listen on the wildcard address,* rather than its own internet address. This is* generally good practice for servers, because on* systems which are connected to more than one

  • 8/8/2019 Bsd Sockets Programming

    50/196

    50 Chapter 2

    Using Internet Stream Sockets

    Example Using Internet Stream Sockets

    * network at once will be able to have one server* listening on all networks at once. Even when the* host is connected to only one network, this is good* practice, because it makes the server program more* portable.*/

    myaddr_in.sin_addr.s_addr = INADDR_ANY;/* Find the information for the example server* in order to get the needed port number.*/

    sp = getservbyname (example, tcp);if (sp == NULL) {

    fprintf(stderr, %s: host not found ,argv[0]);

    exit(1);}

    myaddr_in.sin_port = sp->s_port;

    /* Create the listen socket. */ls = socket (AF_INET, SOCK_STREAM, 0);if (ls == -1) {

    perror(argv[0]);fprintf(stderr, %s: unable to create socket\n , argv[0]);exit(1);

    }/* Bind the listen address to the socket. */

    if (bind(ls, &myaddr_in, sizeof(struct sockaddr_in)) == -1) {perror(argv[0]);fprintf(stderr, %s: unable to bind address\n, argv[0]);exit(1);

    }/* Initiate the listen on the socket so remote users* can connect. The listen backlog is set to 5. 20*/

    if (listen(ls, 5) == -1) {perror(argv[0]);fprintf(stderr, %s: unable to listen on socket\n,argv[0]);exit(1);

    }

    /* Now, all the initialization of the server is* complete, and any user errors will have already* been detected. Now we can fork the daemon and* return to the user. We need to do a setpgrp* so that the daemon will no longer be associated* with the user's control terminal. This is done* before the fork, so that the child will not be* a process group leader. Otherwise, if the child* were to open a terminal, it would become associated* with that terminal as its control terminal. It is* always best for the parent to do the setpgrp.*/

    setpgrp();

    switch (fork()) {case -1:

    /* Unable to fork, for some reason. */perror(argv[0]);

  • 8/8/2019 Bsd Sockets Programming

    51/196

    Chapter 2 51

    Using Internet Stream Sockets

    Example Using Internet Stream Sockets

    fprintf(stderr, %s: unable to fork daemon\n, argv[0]);exit(1);

    case 0:/* The child process (daemon) comes here. *//* Close stdin and stderr so that they will not* be kept open. Stdout is assumed to have been* redirected to some logging file, or /dev/null.* From now on, the daemon will not report any* error messages. This daemon will loop forever,* waiting for connections and forking a child* server to handle each one.*/fclose(stdin);fclose(stderr);

    /* Set SIGCLD to SIG_IGN, in order to prevent* the accumulation of zombies as each child

    * terminates. This means the daemon does not* have to make wait calls to clean them up.*/

    signal(SIGCLD, SIG_IGN);for(;;) {

    /* Note that addrlen is passed as a pointer* so that the accept call can return the* size of the returned address.*/

    addrlen = sizeof(struct sockaddr_in);/* This call will block until a new* connection arrives. Then, it will* return the address of the connecting* peer, and a new socket descriptor,* s, for that connection.*/

    s = accept(ls, &peeraddr_in, &addrlen);if ( s == -1) exit(1);

    switch (fork()) {case -1: /* Can't fork, just continue. */exit(1);

    case 0: /* Child process comes here. */server();exit(0);

    default: /* Daemon process comes here. *//* The daemon needs to close the* the new accept socket after* forking the child. This* prevents daemon from running* out of file descriptors.* It also means that when the* server closes the socket,* that it will allow socket* to be destroyed since it* will be the last close.*/

    close(s);}

    }

    default: /* Parent process comes here. */exit(0);

    }

  • 8/8/2019 Bsd Sockets Programming

    52/196

    52 Chapter 2

    Using Internet Stream Sockets

    Example Using Internet Stream Sockets

    }/** S E R V E R** This is the actual server routine that the daemon forks* to handle each individual connection. Its purpose is* to receive the request packets from the remote client,* process them, and return the results to the client.* It will also write some logging information to stdout.**/server(){

    int reqcnt = 0; /* keeps count of number of requests */char buf[10]; /* This example uses 10 byte messages. */char *inet_ntoa();char *hostname; /* points to remote host's name string */

    int len, len1;/* Close the listen socket inherited from the daemon. */close(ls);

    /* Look up the host information for the remote host* we have connected with. Its internet address* was returned by the accept call, in the main* daemon loop above.*/

    hp = gethostbyaddr ((char *) &peeraddr_in.sin_addr,sizeof (struct in_addr),peeraddr_in.sin_family);

    if (hp == NULL) {/* The info is unavailable for the remote host.* Just format its internet address to be* printed in the logging information. The* address will be shown in internet dot format.

    */hostname = inet_ntoa(peeraddr_in.sin_addr);} else {

    hostname = hp->h_name; /* point to host's name */}

    /* Log a startup message. */time (&timevar);

    /* The port number must be converted first to* host byte order before printing. On most hosts,* this is not necessary, but the ntohs() call is* included here so that this program could easily* be ported to a host that does require it.*/

    printf(Startup from %s port %u at %s,hostname, ntohs(peeraddr_in.sin_port), ctime(&timevar));

    /* Set the socket for a lingering, graceful close.* Since linger was set to 1 above, this will

    * cause a final close of this socket to wait* until all of the data sent on it has been* received by the remote host.

    */if (setsockopt(s, SOL_SOCKET, SO_LINGER, &linger,

    sizeof(linger)) == -1) {errout: printf(Connectionwith%saborterror\n,hostname);

  • 8/8/2019 Bsd Sockets Programming

    53/196

    Chapter 2 53

    Using Internet Stream Sockets

    Example Using Internet Stream Sockets

    exit(1);}

    /* Go into a loop, receiving requests from the* remote client. After the client has sent the* last request, it will do a shutdown for sending,* which causes an end-of-file condition to appear* on this end of the connection. After all of the* clients requests have been received, the next* recv call will return zero bytes, signalling an* end-of-file condition. This is is how the server* will know that no more requests will follow* and the loop will be exited.*/

    while (len = recv(s, buf, 10, 0)) {if (len == -1) goto errout; /* error from recv */

    /* The reason this while loop exists is that* there is a remote possibility of the above

    * recv returning less than 10 bytes. This is* because a recv returns as soon as there is* some data, and will not wait for all of the* requested data to arrive. Since 10 bytes is* relatively small compared to the allowed TCP* packet sizes, a partial receive is unlikely.* If this example had used 2048 bytes requests* instead, a partial receive would be far more* likely. This loop will keep receiving until* all 10 bytes have been received, thus* guaranteeing that the next recv at the top* of the loop will start at the beginning* of the next request.*/

    while (len < 10) {len1 = recv(s, &buf[len], 10-len, 0);if (len1 == -1) goto errout;len += len1;

    } /* Increment the request count. */reqcnt++;

    /* This sleep simulates the processing of* the request that a real server might do.*/

    sleep(1);/* Send a response back to the client. */

    if (send(s, buf, 10, 0) != 10) goto errout;}

    /* The loop has terminated, because there are no* more requests to be serviced. As above, this* close will block until all of the sent replies* have been received by the remote host. Lingering* on the close is so the server will have a better* idea when the remote has picked up all the data.* This allows the start and finish times printed

    * in the log file to more accurately reflect* the length of time this connection was used.*/

    close(s);

    /* Log a finishing message. */time (&timevar);

  • 8/8/2019 Bsd Sockets Programming

    54/196

    54 Chapter 2

    Using Internet Stream Sockets

    Example Using Internet Stream Sockets

    /* The port number must be converted first to* host byte order before printing. On most hosts,* this is not necessary, but the ntohs() call is* included here so this program could easily* be ported to a host that does require it.*/

    printf(Completed %s port %u, %d requests, at %s\n,hostname, ntohs(peeraddr_in.sin_port), reqcnt,ctime(&timevar));

    }

    /** C L I E N T . T C P** This example program demonstrates the use of stream* sockets as a BSD Sockets mechanism. This contains the client,* and is intended to operate in conjunction with the server

    * program found in serv.tcp. Together, these two programs* demonstrate many of the features of sockets, as well as* good conventions for using these features.** This program requests a service called example. For it* to function, an entry needs to exist in the /etc/services* file. The port address for this service can be any port* number that is not used, such as 22375, for example. The* host on which the server will be running must also have the* same entry (same port number) in its /etc/services file.**/

    #include #include #include #include #include

    int s; /* connected socket descriptor */

    struct hostent *hp; /* pointer to host info for remote host */struct servent *sp; /* pointer to service information */

    long timevar; /* contains time returned by time() */char *ctime(); /* declare time formatting routine */

    struct sockaddr_in myaddr_in; /* for local socket address */struct sockaddr_in peeraddr_in; /* for peer socket address */

    /** M A I N** This routine is the client that requests service from the* remote example server. It creates a connection, sends a few* of requests, shuts down the connection in one direction to

    * signal the server about the end of data, and then receives* all of the responses. Status will be written to stdout.** The name of the system to which the requests will be sent* is given as a parameter to the command.*/main(argc, argv)

  • 8/8/2019 Bsd Sockets Programming

    55/196

    Chapter 2 55

    Using Internet Stream Sockets

    Example Using Internet Stream Sockets

    int argc;char *argv[];{

    int addrlen, i, j;

    /* This example uses 10 byte messages. */char buf[10];

    if (argc != 2) {fprintf(stderr, Usage:%s \n argv[0];exit(1);

    }/* clear out address structures */

    memset ((char *)&myaddr_in, 0, sizeof(struct sockaddr_in));memset ((char *)&peeraddr_in, 0, sizeof(struct sockaddr_in));

    /* Set up the peer address to which we will connect. */

    peeraddr_in.sin_family = AF_INET;/* Get the host information for the hostname that the* user passed in.*/

    hp = gethostbyname (argv[1]);/* argv[1] is the host name. */

    if (hp == NULL) {fprintf(stderr, %s: %s not found in /etc/hosts\n,

    argv[0], argv[1]);exit(1);

    }peeraddr_in.sin_addr.s_addr=((struct in_addr*)(hp->h_addr)->s_addr;

    /* Find the information for the example server* in order to get the needed port number.*/

    sp = getservbyname (example, tcp);if (sp == NULL) {

    fprintf(stderr, %s: example not found in/etc/services\n, argv[0]);exit(1);

    }peeraddr_in.sin_port = sp->s_port;

    /* Create the socket. */s = socket (AF_INET, SOCK_STREAM, 0);if (s == -1) {

    perror(argv[0]);fprintf(stderr,%s: unable to create socket\n, argv[0])exit(1);

    }/* Try to connect to the remote server at the* address which was just built into peeraddr.*/

    if (connect(s, &peeraddr_in, sizeof(struct sockaddr_in)) ==-1) {perror(argv[0]);

    fprintf(stderr, %s: unable to connect to remote\n,argv[0]);

    exit(1);}

    /* Since the connect call assigns a random address* to the local end of this connection, let's use* getsockname to see what it assigned. Note that

  • 8/8/2019 Bsd Sockets Programming

    56/196

    56 Chapter 2

    Using Internet Stream Sockets

    Example Using Internet Stream Sockets

    * addrlen needs to be passed in as a pointer,* because getsockname returns the actual length* of the address.*/

    addrlen = sizeof(struct sockaddr_in);if (getsockname(s, &myaddr_in, &addrlen) == -1) {

    perror(argv[0]);fprintf(stderr, %s: unable to read socket address\n,

    argv[0]);exit(1);

    }

    /* Print out a startup message for the user. */time(&timevar);

    /* The port number must be converted first to* host byte order before printing. On most hosts,* this is not necessary, but the ntohs() call is

    * included here so this program could easily be* ported to a host that does require it.*/

    printf(Connected to %s on port %u at %s,argv[1], ntohs(myaddr_in.sin_port),

    ctime(&timevar));

    /* This sleep simulates any preliminary processing* that a real client might do here.*/

    sleep(5);

    /* Send out all the requests to the remote server.* In this case five are sent but any random number* could be used. The first four bytes of buf are* set up to contain the request number. This* number will be returned in the servers reply.

    */

    /* CAUTION: If you increase the number of requests* sent or the size of the requests, you should be* aware that you could encounter a deadlock* situation. Both the client's and server's* sockets can only queue a limited amount of* data on their receive queues.*/

    for (i=1; i

  • 8/8/2019 Bsd Sockets Programming

    57/196

    Chapter 2 57

    Using Internet Stream Sockets

    Example Using Internet Stream Sockets

    if (shutdown(s, 1) == -1) {perror(argv[0]);

    fprintf(stderr, %s: unable to shutdown socket\n,argv[0]);exit(1);

    }

    /* Start receiving all the replys from the server.* This loop will terminate when the recv returns* zero, which is an end-of-file condition. This* will happen after the server has sent all of its* replies, and closed its end of the connection.*/while (i = recv(s, buf, 10, 0)) {

    if (i == -1) {errout: perror(argv[0]);

    fprintf(stderr, %s: error reading result\n,argv[0]);exit(1);

    }

    /* The reason this while loop exists is that there* is a remote possibility of the above recv returning* less than 10 bytes. This is because a recv returns* as soon as there is some data, and will not wait for* all of the requested data to arrive. Since 10 bytes* is relatively small compared to the allowed TCP* packet sizes, a partial receive is unlikely. If* this example had used 2048 bytes requests instead,* a partial receive would be far more likely.* This loop will keep receiving until all 10 bytes* have been received, thus guaranteeing that the* next recv at the top of the loop will* start at the begining of the next reply.*/

    while (i < 10) {j = recv(s, &buf[i], 10-i, 0);

    if (j == -1) goto errout;i += j;}

    /* Print out message indicating the* identity of this reply.*/

    printf(Received result number %d\n, *(int *)buf);}

    /* Print message indicating completion of task. */

    time(&timevar);printf(All done at %s, ctime(&timevar));

    }

  • 8/8/2019 Bsd Sockets Programming

    58/196

    58 Chapter 2

    Using Internet Stream Sockets

    Example Using Internet Stream Sockets

  • 8/8/2019 Bsd Sockets Programming

    59/196

  • 8/8/2019 Bsd Sockets Programming

    60/196

    60 Chapter 3

    Advanced Topics for Stream Sockets

    This chapter explains the following:

    S ock et op tion s.

    Synchronous I /O mult iplexing with select.

    Sending and receiving data asynchronously.

    Nonblock ing I/O.

    U sin g sh ut down .

    Using read and write to make stream sockets tra nsparent.

    Sending and receiving out of band data.

  • 8/8/2019 Bsd Sockets Programming

    61/196

    Chapter 3 61

    Advanced Topics for Stream Sockets

    Socket Options

    Socket Opt ions

    The oper at ion of socket s is contr olled by socket level options. Th e

    following options ar e su pported for intern et st ream sockets:

    S O_RE US EADDR

    S O_KE E PALIVE

    S O_DON TROU TE

    SO_SNDBUF

    SO_RCVBUF

    SO_LINGE R

    S O_U SE LOOP BACK

    S O_OOBIN LIN E

    S O_SN DLOWAT

    S O_RCVL OWAT

    SO_SN DTIME O

    S O_RCVTIME O

    SO_TYPE SO_ERROR

    S O_BRO ADCAS T

    SO_RE USE PORT

    All of these options may be used on either AF_INET or AF_UNIX

    socket s; the following, however, ar e rea lly INET specific in t heir function

    and will not change UNIX socket behavior.

    S O_KE E PALIVE

    S O_RE US EADDR

    S O_DON TROU TE

    S O_U SE LOOP BACK

    S O_OOBIN LIN E

  • 8/8/2019 Bsd Sockets Programming

    62/196

    62 Chapter 3

    Advanced Topics for Stream Sockets

    Socket Options

    SO_SN DTIME O

    S O_RCVTIME O

    S O_BRO ADCAS T

    SO_RE USE PORT

    In a ddition, th e SO_DEBUG option is supp orted for compat ibility only; it

    has no functionality.

    Options for protocol levels ar e described in t he in dividual pr otocol

    manu al pages, such a s tcp(7p), udp(7p), and ip(7p).

    The n ext section describes how to get th e cur ren t valu e of a socket option

    an d to set socket options, followed by a description of each a vailableoption. Refer t o cha pter 6 for a description of the SO_BROADCAST

    option.

    Gett ing an d Sett ing Sock et Options

    The socket options are defined in th e sys/socket.h file. You can get

    the current statu s of an option with the getsockopt call, an d you can

    set th e value of an option with th e setsockopt call.

    getsockopt an d its par amet ers ar e described in the following table:

    Include files: #include #include

    System call: getsockopt(s, level, optname, optval, optlen)int s, level, optname;char *optval;int *optlen;

  • 8/8/2019 Bsd Sockets Programming

    63/196

    Chapter 3 63

    Advanced Topics for Stream Sockets

    Socket Options

    Fu nction r esult: 0 if th e option is set. If getsockopt fails for any reason,

    the function retu rn s -1, and th e option is not retur ned.

    An error code is stored in errno.

    Example:

    len = sizeof (optval))getsockopt(s, SOL_SOCKET, SO_REUSEADDR, &optval, &len;)

    optval may never be zero. It mu st always point to data sen t with th e

    socket option a nd m ust always be at least th e size of an int eger.

    The following socket options set socket parameter values. optval is an

    integer conta ining the new value:

    SO_SNDBUF

    SO_RCVBUF

    S O_SN DLOWAT

    S O_RCVL OWAT

    SO_SN DTIME O

    Parame ter Con ten ts INP UT ValueOUTPUT

    Value

    s socket

    descriptor

    socket descriptor

    for which option

    values ar e to be

    returned

    unchanged

    level protocol

    level

    SOL_SOCKET unchanged

    optname name of

    option

    supported option

    name

    unchanged

    optva l poin ter to

    current

    value of

    option

    pointer to buffer

    wher e options

    current value is to

    be returned

    pointer to buffer

    that conta ins

    cur rent option

    value

    opt len poin ter to

    length of

    optval

    pointer to

    maximum number

    of bytes to be

    returned by optval

    point er to

    actual size of

    optval retur ned

  • 8/8/2019 Bsd Sockets Programming

    64/196

    64 Chapter 3

    Advanced Topics for Stream Sockets

    Socket Options

    S O_RCVTIME O

    The following socket options toggle socket behavior. optval is an integer

    cont ain ing a boolean flag for th e beha vior (1 = on, 0 = off):

    S O_KE E PALIVE

    SO_DEBUG

    S O_DON TROU TE

    S O_U SE LOOP BACK

    S O_RE US EADDR

    S O_OOBIN LIN E

    SO_RE USE PORT

    The SO_LINGER option is a combinat ion. It set s a linger value, an d also

    toggles linger beh avior on an d off. In pr evious r eleases

    SO_DONTLINGER wa s su pported. For SO_LINGER, optval points to a

    struct linger, defined in /usr/include/sys/socket.h. The

    structure contains an integer boolean flag to toggle behavior on/off, and

    an integer linger value. Refer t o the getsockopt(2) ma n pa ge for more

    information on getsockopt.

    setsockopt an d its par amet ers ar e described in the following table:

    Include files: #include #include

    System call: setsockopt(s, level, optname, optval, optlen)int s, level, optname;char *optval;int optlen;

    ParameterDescript ion of

    ContentsINPUT Value

    s socket descr iptor socket descr iptor for

    which options ar e to be set

    level protocol level SOL_SOCKET

  • 8/8/2019 Bsd Sockets Programming

    65/196

    Chapter 3 65

    Advanced Topics for Stream Sockets

    Socket Options

    Fu nction r esult: 0 if setsockopt is successful, 1 if failure occur s.

    E xa m ple: S ee th e d es cr ip tion of t h e S O_RE U SE AD DR op tion for

    an example.

    Refer t o the setsockopt(2) man page for m ore inform ation on

    setsockopt.

    SO_REUSEADDR

    This option is AF_INE T socket-specific.

    SO_REUSE ADDR ena bles you to resta rt a da emon which was killed or

    terminated.

    This option modifies th e ru les used by bind t o validat e local addresses,

    but it does not violate th e un iqueness requiremen ts of an association.

    SO_REUSE ADDR modifies the bind r ules only when a wildcard Int ernet

    Protocol (IP) address is used in combinat ion with a par ticular protocol

    port. The h ost st ill checks at conn ection t ime to be sur e an y other sockets

    with th e same local addr ess an d local port do not h ave the sa me rem ote

    addr ess and r emote port . Conn ect fails if th e uniqueness r equirement is

    violated.

    Exam ple of the SO_REUSEADDR Option

    A network d aem on server is listen ing on a sp ecific port : port 2000. If you

    executed netstat an, part of th e out put would resemble:

    Active connections (including servers)Proto Recv-Q Send-Q Local Address Foreign Address (state)tcp 0 0 *.2000 *.* LISTEN

    optname name of opt ion supported opt ion name

    optva l poin ter to opt ion input

    value

    Must be a t least size of

    (int ). Holds either value to

    be set or boolean flag

    opt len length of optva l size of optva l

    ParameterDescription of

    ContentsINPUT Value

  • 8/8/2019 Bsd Sockets Programming

    66/196

    66 Chapter 3

    Advanced Topics for Stream Sockets

    Socket Options

    Netw ork Daemo n Serve r Listenin g at Port 2000. When thenetwork daemon accepts a connection request, th e accepted socket will

    bind to port 2000 an d to the addr ess where th e daemon is run ning (e.g.

    192.6.250.100). If you executed netstat an, the output would

    resemble:

    Active connections (including servers)Proto Recv-Q Send-Q Local Address Foreign Address (state)tcp 0 0 192.6.250.100.2000 192.6.250.101.4000 ESTABLISHEDtcp 0 0 *.2000 *.* LISTEN

    New Connect ion Establi shed, Daemon Server St i llListening. Here th e network daemon ha s established a connection tothe client (192.6.250.101.4000) with a n ew server socket. The

    original network daemon server continues to listen for more connectionrequests.

    If th e listening n etwork daemon process is killed, att empts t o restart the

    daemon fail if SO_REUSE ADDR is not set. The r estar t fails becau se th e

    daemon a ttem pts t o bind to port 2000 and a wildcard IP addr ess (e.g.

    *.2000). The wildcar d addr ess mat ches the add ress of the est ablished

    conn ection (192.6.250.100), so th e bind aborts to avoid du plicate

    socket na ming.

    When SO_REUSE ADDR is set, bind ignores th e wildcard ma tch, so the

    network da emon can be restar ted. An example usage of th is option is:

    int optval = 1;setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval,sizeof(optval));bind (s, &sin, sizeof(sin));

    SO_KEEPALIVE

    This option is AF_INE T socket-specific.

    This option enables th e periodic tra nsmission of messages on a connected

    socket. This occurs at t he tr an sport level and does not require an y work

    in your a pplication pr ogram s.

    If the peer socket does not r espond to th ese messages, the conn ection is

    considered broken. The next time one of your processes at tempt s to u se a

    connection th at is considered br oken, the process is n otified (with a

    SIGP IPE signa l if you a re t rying t o send, or an en d-of-file condition if youare trying t o receive) that the connection is br oken.

  • 8/8/2019 Bsd Sockets Programming

    67/196

    Chapter 3 67

    Advanced Topics for Stream Sockets

    Socket Options

    SO_DONTROUTE

    This option is AF_INE T socket-specific.

    SO_DONTROUTE indicat es tha t outgoing messages should bypass th e

    stan dar d routing facilities. Instea d, messages are directed to th e

    appr opriate net work interface according to th e network portion of th e

    destination address.

    SO_SNDBUF

    SO_SNDBUF cha nges th e send socket bu ffer size. Increasing t he send

    socket bu ffer size allows a user to send m ore data before t he u ser's

    app licat ion will block, wa iting for more bu ffer s pa ce.

    NOTE Increasing buffer size to send la rger portions of dat a before t he

    app licat ion blocks m ay increase th roughput, but the best m ethod of

    tun ing performa nce is to experiment with var ious buffer sizes.

    You can increase a str eam socket's buffer size at an y time, but decrease it

    only prior to establishing a connection. The maximum buffer size for

    strea m sockets is 262144 bytes. Here is an example:

    int result;int buffsize = 10,000;result = setsockopt(s, SOL_SOCKET, SO_SNDBUF, &buffsize,sizeof(buffsize));

    SO_RCVBUF

    SO_RCVBUF chan ges th e receive socket buffer size.

    You can increase a str eam socket's buffer size at an y time, but decrease it

    only prior to establishing a connection. The maximum buffer size for

    strea m sockets is 262144 bytes. Here is an example:

    int result;int buffsize = 10,000;result=setsockopt(s,SOL_SOCKET,SO_RCVBUF,&buffsize,sizeof(buffsize));

  • 8/8/2019 Bsd Sockets Programming

    68/196

    68 Chapter 3

    Advanced Topics for Stream Sockets

    Socket Options

    Table 3-1 Su mm ary In form ation for Ch an gin g Socke t Bu ffe r Size

    SO_LINGERSO_LINGER cont rols the actions t aken when a close is execut ed on a

    socket t ha t h as u nsent dat a. This option can be cleared by toggling. The

    default is off.

    The linger t imeout interval is set with a param eter in th e setsockopt

    call. The only useful values a re zero an d n onzero:

    If l_onoff is zero, close return s immediately, but an y unsent data is

    tra nsmitted (after close returns).

    If l_onoff is nonzero and l_linger is zero, close retu rn s immediately,

    and a ny unsent da ta is discarded.

    If l_onoff is nonzero and l_linger is nonzero, close does not retur nun til all unsent dat a is tr an smitted (or t he conn ection is closed by the

    remote system).

    In t he defau lt case (SO_LINGE R is off), close is n ot blocked. Th e socket

    itself, however, goes th rough gra ceful disconn ect, and no dat a is lost.

    Here is an example:

    int result;struct linger linger;linger.l_onoff = 1;

    /*0 = off (l_linger ignored), nonzero = on */linger.l_linger =1;

    /*0 = discard data, nonzero = wait for data sent */result = setsockopt(s, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));

    S ock et T yp e (P r ot ocol) s tr ea m (T CP )

    When Buffer Size

    Increa se Allowed

    at an y time

    When Buffer Size

    Decrease Allowed

    only prior to establishing a

    connection

    Ma xim um Bu ffer Size 262144 byt es

  • 8/8/2019 Bsd Sockets Programming

    69/196

    Chapter 3 69

    Advanced Topics for Stream Sockets

    Socket Options

    Table 3-2 Summary of Linge r Option s on Close

    SO_USELOOPBACKThis option is not a pplicable to UNIX Doma in socket s.

    SO_USELOOPBACK directs the network layer (IP) of networking code

    to use th e local loopback addr ess when sending dat a from th is socket.

    Use t his option only when a ll data sent will also be received locally.

    SO_OOBINLINE

    This option is not a pplicable to UNIX Doma in socket s.

    This option ena bles receipt of out-of-band da ta inline. Norm ally, OOB

    data is extracted from the data st ream an d must be read with the

    MSG_OOB flag specified in the recv() call. When SO_OOBINLINE isspecified, OOB data arr iving at t ha t socket r emains inline an d can be

    read without MSG_OOB specified.

    In both cases, a n orm al read() or recv(