12.07.2015 Views

z/VM: TCP/IP Programmer's Reference - z/VM - IBM

z/VM: TCP/IP Programmer's Reference - z/VM - IBM

z/VM: TCP/IP Programmer's Reference - z/VM - IBM

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

z/<strong>VM</strong><strong>TCP</strong>/<strong>IP</strong> Level 3A0Programmer’s <strong>Reference</strong>Version3Release1.0SC24-5983-00


z/<strong>VM</strong><strong>TCP</strong>/<strong>IP</strong> Level 3A0Programmer’s <strong>Reference</strong>Version3Release1.0SC24-5983-00


Note!Before using this information and the product it supports, read the information under “Notices” on page 425.||||First Edition (February 2001)This edition applies to the <strong>IBM</strong> ® Transmission Control Protocol/Internet Protocol Feature for z/<strong>VM</strong> (<strong>TCP</strong>/<strong>IP</strong> Level3A0), program number 5654-A17 and to all subsequent releases and modifications until otherwise indicated in neweditions.This edition replaces SC24-5849-01.© Copyright International Business Machines Corporation 1987, 2001. All rights reserved.US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contractwith <strong>IBM</strong> Corp.


|||ContentsPreface . . . . . . . . . . . . . . . ixWho Should Read This Book. . . . . . . . . ixWhat You Should Know before Reading This Book ixWhat This Book Contains . . . . . . . . . . ixHow to Use This Book . . . . . . . . . . . xiHow the Term “internet” Is Used in This Book. . xiWhere to Find More Information . . . . . . . xiService Information . . . . . . . . . . . . xiUnderstanding Syntax Diagrams . . . . . . . xiHow Numbers Are Used in This Book . . . . . xivHow to Send Your Comments to <strong>IBM</strong> . . . . . xivSummary of Changes . . . . . . . . xvFirst Edition for z/<strong>VM</strong> (February 2001) . . . . . xv<strong>IP</strong> Multicast . . . . . . . . . . . . . xvOther Changes . . . . . . . . . . . . xvSecond Edition for <strong>VM</strong>/ESA ® (July 1999) . . . . xvFirst Edition for <strong>VM</strong>/ESA . . . . . . . . . xvChapter 1. General ProgrammingInformation . . . . . . . . . . . . . 1Porting Considerations . . . . . . . . . . . 1Accessing System Return Messages . . . . . . 1Printing System Return Messages . . . . . . 1Compiling and Linking C Applications . . . . . 1Textlib (TXTLIB) Files . . . . . . . . . . 2<strong>TCP</strong>LOAD EXEC . . . . . . . . . . . . . 2Using <strong>TCP</strong>LOAD . . . . . . . . . . . . 3SET LDRTBLS Command . . . . . . . . . . 4Chapter 2. C Sockets ApplicationProgram Interface . . . . . . . . . . 5Programming with C Sockets . . . . . . . . . 5Socket Programming Concepts . . . . . . . 5Guidelines for Using Socket Types . . . . . . 6Addressing within Sockets. . . . . . . . . 6Main Socket Calls. . . . . . . . . . . . 8C Socket Library. . . . . . . . . . . . . 16Porting . . . . . . . . . . . . . . . . 17Environment Variables Used by the Sockets Library 17C Socket <strong>Reference</strong> . . . . . . . . . . . . 19C Socket Calls . . . . . . . . . . . . . 21accept(). . . . . . . . . . . . . . . 22bind() . . . . . . . . . . . . . . . 23close() . . . . . . . . . . . . . . . 27connect() . . . . . . . . . . . . . . 27endhostent() . . . . . . . . . . . . . 30endnetent() . . . . . . . . . . . . . 31endprotoent() . . . . . . . . . . . . . 31endservent() . . . . . . . . . . . . . 31fcntl() . . . . . . . . . . . . . . . 31getclientid() . . . . . . . . . . . . . 32getdtablesize() . . . . . . . . . . . . 33gethostbyaddr() . . . . . . . . . . . . 33gethostbyname() . . . . . . . . . . . . 34gethostent() . . . . . . . . . . . . . 35gethostid(). . . . . . . . . . . . . . 36gethostname() . . . . . . . . . . . . 36getibmsockopt() . . . . . . . . . . . . 36getnetbyaddr() . . . . . . . . . . . . 38getnetbyname() . . . . . . . . . . . . 39getnetent(). . . . . . . . . . . . . . 40getpeername() . . . . . . . . . . . . 40getprotobyname() . . . . . . . . . . . 41getprotobynumber() . . . . . . . . . . 41getprotoent() . . . . . . . . . . . . . 42getservbyname() . . . . . . . . . . . . 43getservbyport() . . . . . . . . . . . . 43getservent() . . . . . . . . . . . . . 44getsockname() . . . . . . . . . . . . 44getsockopt() . . . . . . . . . . . . . 45givesocket() . . . . . . . . . . . . . 49htonl() . . . . . . . . . . . . . . . 51htons() . . . . . . . . . . . . . . . 51ibmsflush() . . . . . . . . . . . . . 51inet_addr() . . . . . . . . . . . . . 52inet_lnaof() . . . . . . . . . . . . . 52inet_makeaddr() . . . . . . . . . . . . 53inet_netof() . . . . . . . . . . . . . 53inet_network() . . . . . . . . . . . . 53inet_ntoa(). . . . . . . . . . . . . . 54ioctl() . . . . . . . . . . . . . . . 54listen() . . . . . . . . . . . . . . . 56maxdesc() . . . . . . . . . . . . . . 57ntohl() . . . . . . . . . . . . . . . 58ntohs() . . . . . . . . . . . . . . . 59read() . . . . . . . . . . . . . . . 59readv() . . . . . . . . . . . . . . . 60recv() . . . . . . . . . . . . . . . 61recvfrom() . . . . . . . . . . . . . . 62recvmsg() . . . . . . . . . . . . . . 63select() . . . . . . . . . . . . . . . 64selectex() . . . . . . . . . . . . . . 67send() . . . . . . . . . . . . . . . 68sendmsg() . . . . . . . . . . . . . . 69sendto() . . . . . . . . . . . . . . 70sethostent() . . . . . . . . . . . . . 72setibmsockopt() . . . . . . . . . . . . 72setnetent() . . . . . . . . . . . . . . 75setprotoent() . . . . . . . . . . . . . 75setservent() . . . . . . . . . . . . . 75setsockopt() . . . . . . . . . . . . . 76sockdb_sock_debug() . . . . . . . . . . 79sock_debug_bulk_perf0 (). . . . . . . . . 80sock_do_bulkmode() . . . . . . . . . . 80sock_do_teststor() . . . . . . . . . . . 81shutdown() . . . . . . . . . . . . . 81socket() . . . . . . . . . . . . . . . 82takesocket() . . . . . . . . . . . . . 85tcperror() . . . . . . . . . . . . . . 86© Copyright <strong>IBM</strong> Corp. 1987, 2001 iii


write() . . . . . . . . . . . . . . . 87writev(). . . . . . . . . . . . . . . 88Sample C Socket Programs . . . . . . . . . 89C Socket <strong>TCP</strong> Client . . . . . . . . . . . 89C Socket <strong>TCP</strong> Server . . . . . . . . . . . 90C Socket UDP Server . . . . . . . . . . . 92C Socket UDP Client . . . . . . . . . . . 93Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (PascalLanguage) . . . . . . . . . . . . . 95Software Requirements . . . . . . . . . . 95Data Structures . . . . . . . . . . . . . 96Connection State. . . . . . . . . . . . 96Connection Information Record. . . . . . . 97Socket Record . . . . . . . . . . . . 98Notification Record . . . . . . . . . . . 98File Specification Record. . . . . . . . . 105Using Procedure Calls . . . . . . . . . . 105Notifications. . . . . . . . . . . . . 105<strong>TCP</strong>/UDP Initialization Procedures . . . . . 106<strong>TCP</strong>/UDP Termination Procedure . . . . . 106Handling External Interrupts . . . . . . . 107<strong>TCP</strong> Communication Procedures . . . . . . 107Ping Interface . . . . . . . . . . . . 107Monitor Procedures . . . . . . . . . . 108UDP Communication Procedures . . . . . . 108Raw <strong>IP</strong> Interface . . . . . . . . . . . 108Timer Routines . . . . . . . . . . . . 109Host Lookup Routines . . . . . . . . . 109AddUserNote . . . . . . . . . . . . 110Other Routines . . . . . . . . . . . . 110Procedure Calls. . . . . . . . . . . . . 110BeginTcpIp . . . . . . . . . . . . . 110ClearTimer . . . . . . . . . . . . . 111CreateTimer . . . . . . . . . . . . . 111DestroyTimer . . . . . . . . . . . . 111EndTcpIp . . . . . . . . . . . . . . 111GetHostNumber . . . . . . . . . . . 112GetHostResol . . . . . . . . . . . . 112GetHostString . . . . . . . . . . . . 113GetIdentity . . . . . . . . . . . . . 113GetNextNote . . . . . . . . . . . . 113GetSmsg . . . . . . . . . . . . . . 114Handle . . . . . . . . . . . . . . 114LocalAddress . . . . . . . . . . . . 115IsLocalHost . . . . . . . . . . . . . 115MonCommand . . . . . . . . . . . . 116MonQuery . . . . . . . . . . . . . 117NotifyIo . . . . . . . . . . . . . . 118PingRequest . . . . . . . . . . . . . 119RawIpClose . . . . . . . . . . . . . 119RawIpOpen . . . . . . . . . . . . . 120RawIpReceive . . . . . . . . . . . . 120RawIpSend . . . . . . . . . . . . . 121ReadXlateTable . . . . . . . . . . . . 122RTcpExtRupt . . . . . . . . . . . . 123RTcpVmcfRupt . . . . . . . . . . . . 123SayCalRe . . . . . . . . . . . . . . 124SayConSt . . . . . . . . . . . . . . 124SayIntAd . . . . . . . . . . . . . . 124SayIntNum . . . . . . . . . . . . . 125SayNotEn . . . . . . . . . . . . . 125SayPorTy . . . . . . . . . . . . . . 125SayProTy . . . . . . . . . . . . . . 125SetTimer . . . . . . . . . . . . . . 126StartTcpNotice . . . . . . . . . . . . 126TcpAbort . . . . . . . . . . . . . . 127TcpClose . . . . . . . . . . . . . . 127TcpExtRupt . . . . . . . . . . . . . 128TcpFReceive, TcpReceive, and TcpWaitReceive 128TcpFSend, TcpSend, and TcpWaitSend . . . . 131TcpNameChange . . . . . . . . . . . 133TcpOpen and TcpWaitOpen. . . . . . . . 134TcpOption . . . . . . . . . . . . . 136TcpStatus . . . . . . . . . . . . . . 137TcpVmcfRupt . . . . . . . . . . . . 138UdpClose . . . . . . . . . . . . . 138UdpNReceive . . . . . . . . . . . . 139UdpOpen . . . . . . . . . . . . . 139UdpReceive . . . . . . . . . . . . . 140UdpSend . . . . . . . . . . . . . . 141Unhandle. . . . . . . . . . . . . . 142UnNotifyIo . . . . . . . . . . . . . 142Sample Pascal Program . . . . . . . . . . 143Chapter 4. Virtual MachineCommunication Facility Interface . . . 147General Information . . . . . . . . . . . 147Data Structures . . . . . . . . . . . . 147<strong>VM</strong>CF Functions . . . . . . . . . . . 149<strong>VM</strong>CF <strong>TCP</strong><strong>IP</strong> Communication CALLCODERequests . . . . . . . . . . . . . . 150<strong>VM</strong>CF <strong>TCP</strong><strong>IP</strong> Communication CALLCODENotifications. . . . . . . . . . . . . 151<strong>TCP</strong>/UDP/<strong>IP</strong> Initialization and TerminationProcedures . . . . . . . . . . . . . . 152BEGINtcp<strong>IP</strong>service . . . . . . . . . . 152HANDLEnotice . . . . . . . . . . . 153ENDtcp<strong>IP</strong>service . . . . . . . . . . . 153<strong>TCP</strong> CALLCODE Requests . . . . . . . . . 154OPENtcp . . . . . . . . . . . . . . 154SENDtcp and FSENDtcp . . . . . . . . 155FRECEIVEtcp . . . . . . . . . . . . 156RECEIVEtcp. . . . . . . . . . . . . 157CLOSEtcp . . . . . . . . . . . . . 157ABORTtcp . . . . . . . . . . . . . 158STATUStcp . . . . . . . . . . . . . 158OPTIONtcp . . . . . . . . . . . . . 158UDP CALLCODE Requests. . . . . . . . . 158OPENudp . . . . . . . . . . . . . 159SENDudp . . . . . . . . . . . . . 159NRECEIVEudp . . . . . . . . . . . . 159CLOSEudp . . . . . . . . . . . . . 160<strong>IP</strong> CALLCODE Requests . . . . . . . . . 160OPENrawip . . . . . . . . . . . . . 160SENDrawip . . . . . . . . . . . . . 160RECEIVErawip . . . . . . . . . . . . 161CLOSErawip . . . . . . . . . . . . 161CALLCODE System Queries . . . . . . . . 161IShostLOCAL . . . . . . . . . . . . 161MONITORcommand . . . . . . . . . . 162MONITORquery . . . . . . . . . . . 162ivz/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


PINGreq . . . . . . . . . . . . . . 163CALLCODE Notifications . . . . . . . . . 163BUFFERspaceAVAILABLE . . . . . . . . 164CONNECTIONstateCHANGED . . . . . . 164DATAdelivered. . . . . . . . . . . . 164URGENTpending . . . . . . . . . . . 165UDPdatagramDELIVERED . . . . . . . . 165UDPdatagramSPACEavailable . . . . . . . 166RAW<strong>IP</strong>packetsDELIVERED. . . . . . . . 166RAW<strong>IP</strong>spaceAVAILABLE . . . . . . . . 167RESOURCESavailable . . . . . . . . . 167UDPresourcesAVAILABLE . . . . . . . . 167PINGresponse . . . . . . . . . . . . 167DUMMYprobe . . . . . . . . . . . . 168ACTIVEprobe . . . . . . . . . . . . 168Chapter 5. Inter-User CommunicationVehicle Sockets . . . . . . . . . . 169Prerequisite Knowledge . . . . . . . . . . 169Available Functions . . . . . . . . . . . 169Socket Programming with IUCV . . . . . . . 170Preparing to use the IUCV Socket API . . . . . 171Establishing an IUCV connection to <strong>TCP</strong>/<strong>IP</strong> . . 171Initializing the IUCV Connection . . . . . . 171Severing the IUCV Connection . . . . . . . 173Sever by the Application . . . . . . . . 173Sever by <strong>TCP</strong>/<strong>IP</strong> . . . . . . . . . . . 173Issuing Socket Calls . . . . . . . . . . . 174Overlapping Socket Requests . . . . . . . 174<strong>TCP</strong>/<strong>IP</strong> Response to an IUCV Request . . . . 175Cancelling a Socket Request . . . . . . . 175IUCV Socket Call Syntax . . . . . . . . . 176IUCV Socket Calls. . . . . . . . . . . . 177ACCEPT . . . . . . . . . . . . . . 177BIND . . . . . . . . . . . . . . . 178CANCEL . . . . . . . . . . . . . . 178CLOSE . . . . . . . . . . . . . . 179CONNECT . . . . . . . . . . . . . 180FCNTL . . . . . . . . . . . . . . 180GETCLIENTID . . . . . . . . . . . . 181GETHOSTID . . . . . . . . . . . . 182GETHOSTNAME . . . . . . . . . . . 182GETPEERNAME . . . . . . . . . . . 183GETSOCKNAME . . . . . . . . . . . 183GETSOCKOPT . . . . . . . . . . . . 184GIVESOCKET . . . . . . . . . . . . 185IOCTL. . . . . . . . . . . . . . . 186LISTEN . . . . . . . . . . . . . . 188MAXDESC . . . . . . . . . . . . . 189READ, READV. . . . . . . . . . . . 189RECV, RECVFROM, REC<strong>VM</strong>SG . . . . . . 190SELECT, SELECTEX . . . . . . . . . . 191SEND . . . . . . . . . . . . . . . 193SENDMSG . . . . . . . . . . . . . 194SENDTO . . . . . . . . . . . . . . 194SETSOCKOPT . . . . . . . . . . . . 195SHUTDOWN . . . . . . . . . . . . 196SOCKET . . . . . . . . . . . . . . 197TAKESOCKET . . . . . . . . . . . . 198WRITE, WRITEV . . . . . . . . . . . 199LASTERRNO . . . . . . . . . . . . 200Chapter 6. Remote Procedure Calls 201The RPC Interface . . . . . . . . . . . . 201Portmapper . . . . . . . . . . . . . . 203Contacting Portmapper . . . . . . . . . 204Target Assistance . . . . . . . . . . . 204RPCGEN Command . . . . . . . . . . . 204enum clnt_stat Structure. . . . . . . . . . 205Remote Procedure Call Library . . . . . . . 206Porting . . . . . . . . . . . . . . . 206Remapping C Identifiers with RPC.H . . . . 206Accessing System Return Messages . . . . . 206Printing System Return Messages . . . . . 207Enumerations . . . . . . . . . . . . 207RPC Global Variables. . . . . . . . . . . 207rpc_createerr . . . . . . . . . . . . 207svc_fds . . . . . . . . . . . . . . 207Remote Procedure and eXternal DataRepresentation Calls . . . . . . . . . . . 207auth_destroy() . . . . . . . . . . . . 207authnone_create() . . . . . . . . . . . 208authunix_create() . . . . . . . . . . . 208authunix_create_default() . . . . . . . . 208callrpc() . . . . . . . . . . . . . . 209clnt_broadcast() . . . . . . . . . . . 209clnt_call() . . . . . . . . . . . . . . 211clnt_control() . . . . . . . . . . . . 211clnt_create() . . . . . . . . . . . . . 212clnt_destroy() . . . . . . . . . . . . 213clnt_freeres() . . . . . . . . . . . . 213clnt_geterr() . . . . . . . . . . . . . 213clnt_pcreateerror() . . . . . . . . . . . 214clnt_perrno() . . . . . . . . . . . . 214clnt_perror() . . . . . . . . . . . . . 214clnt_spcreateerror() . . . . . . . . . . 215clnt_sperrno() . . . . . . . . . . . . 215clnt_sperror() . . . . . . . . . . . . 216clntraw_create() . . . . . . . . . . . 216clnttcp_create() . . . . . . . . . . . . 217clntudp_create() . . . . . . . . . . . 217get_myaddress() . . . . . . . . . . . 218getrpcport() . . . . . . . . . . . . . 219pmap_getmaps() . . . . . . . . . . . 219pmap_getport(). . . . . . . . . . . . 219pmap_rmtcall() . . . . . . . . . . . . 220pmap_set() . . . . . . . . . . . . . 221pmap_unset() . . . . . . . . . . . . 221registerrpc() . . . . . . . . . . . . . 222svc_destroy() . . . . . . . . . . . . 222svc_freeargs() . . . . . . . . . . . . 223svc_getargs() . . . . . . . . . . . . 223svc_getcaller() . . . . . . . . . . . . 224svc_getreq() . . . . . . . . . . . . . 224svc_register() . . . . . . . . . . . . 224svc_run() . . . . . . . . . . . . . . 225svc_sendreply(). . . . . . . . . . . . 225svc_unregister() . . . . . . . . . . . 226svcerr_auth() . . . . . . . . . . . . 226svcerr_decode(). . . . . . . . . . . . 226svcerr_noproc(). . . . . . . . . . . . 226svcerr_noprog(). . . . . . . . . . . . 227svcerr_progvers() . . . . . . . . . . . 227Contentsv


svcerr_systemerr() . . . . . . . . . . . 227svcerr_weakauth() . . . . . . . . . . . 228svcraw_create() . . . . . . . . . . . . 228svctcp_create() . . . . . . . . . . . . 228svcudp_create(). . . . . . . . . . . . 229xdr_accepted_reply() . . . . . . . . . . 229xdr_array() . . . . . . . . . . . . . 230xdr_authunix_parms() . . . . . . . . . 230xdr_bool() . . . . . . . . . . . . . 231xdr_bytes() . . . . . . . . . . . . . 231xdr_callhdr() . . . . . . . . . . . . 232xdr_callmsg() . . . . . . . . . . . . 232xdr_double() . . . . . . . . . . . . 232xdr_enum() . . . . . . . . . . . . . 233xdr_float() . . . . . . . . . . . . . 234xdr_inline() . . . . . . . . . . . . . 234xdr_int() . . . . . . . . . . . . . . 235xdr_long() . . . . . . . . . . . . . 235xdr_opaque() . . . . . . . . . . . . 235xdr_opaque_auth() . . . . . . . . . . 236xdr_pmap() . . . . . . . . . . . . . 236xdr_pmaplist() . . . . . . . . . . . . 237xdr_pointer() . . . . . . . . . . . . 237xdr_reference() . . . . . . . . . . . . 237xdr_rejected_reply() . . . . . . . . . . 238xdr_replymsg() . . . . . . . . . . . . 238xdr_short() . . . . . . . . . . . . . 239xdr_string() . . . . . . . . . . . . . 239xdr_u_int() . . . . . . . . . . . . . 239xdr_u_long() . . . . . . . . . . . . 240xdr_u_short() . . . . . . . . . . . . 240xdr_union() . . . . . . . . . . . . . 241xdr_vector() . . . . . . . . . . . . . 241xdr_void() . . . . . . . . . . . . . 242xdr_wrapstring() . . . . . . . . . . . 242xdrmem_create() . . . . . . . . . . . 243xdrrec_create() . . . . . . . . . . . . 243xdrrec_endofrecord() . . . . . . . . . . 244xdrrec_eof() . . . . . . . . . . . . . 244xdrrec_skiprecord() . . . . . . . . . . 244xdrstdio_create() . . . . . . . . . . . 244xprt_register() . . . . . . . . . . . . 245xprt_unregister() . . . . . . . . . . . 245Sample RPC Programs . . . . . . . . . . 246RPC Client . . . . . . . . . . . . . . 246RPC Server . . . . . . . . . . . . . . 246RPC Raw Data Stream . . . . . . . . . . 248Chapter 7. X Window System Interface 251What Is Provided . . . . . . . . . . . . 251Software Requirements . . . . . . . . . . 251Using the X Window System Interface in the <strong>VM</strong>Environment . . . . . . . . . . . . . 251Application Resource File . . . . . . . . . 253Identifying the Target Display . . . . . . . . 254Creating an Application . . . . . . . . . . 254Generating X-Window System Applications . . . 254X Window System Subroutines . . . . . . . 256Opening and Closing a Display . . . . . . 256Creating and Destroying Windows . . . . . 256Manipulating Windows . . . . . . . . . 257Changing Window Attributes . . . . . . . 257Obtaining Window Information . . . . . . 258Obtaining Properties and Atoms . . . . . . 258Manipulating Window Properties. . . . . . 258Setting Window Selections . . . . . . . . 258Manipulating Colormaps . . . . . . . . 259Manipulating Color Cells . . . . . . . . 259Creating and Freeing Pixmaps. . . . . . . 259Manipulating Graphics Contexts . . . . . . 260Clearing and Copying Areas . . . . . . . 261Drawing Lines . . . . . . . . . . . . 261Filling Areas. . . . . . . . . . . . . 261Loading and Freeing Fonts . . . . . . . . 262Querying Character String Sizes . . . . . . 262Drawing Text . . . . . . . . . . . . 263Transferring Images . . . . . . . . . . 263Manipulating Cursors . . . . . . . . . 263Handling Window Manager Functions . . . . 264Manipulating Keyboard Settings . . . . . . 264Controlling the Screen Saver . . . . . . . 265Manipulating Hosts and Access Control . . . 265Handling Events . . . . . . . . . . . 266Enabling and Disabling Synchronization . . . 266Using Default Error Handling . . . . . . . 267Communicating with Window Managers . . . 267Manipulating Keyboard Event Functions . . . 268Manipulating Regions . . . . . . . . . 269Using Cut and Paste Buffers . . . . . . . 270Querying Visual Types . . . . . . . . . 270Manipulating Images . . . . . . . . . . 271Manipulating Bitmaps . . . . . . . . . 271Using the Resource Manager . . . . . . . 271Manipulating Display Functions . . . . . . 272Extension Routines . . . . . . . . . . . 275MIT Extensions to X . . . . . . . . . . . 275Associate Table Functions . . . . . . . . . 276Miscellaneous Utility Routines. . . . . . . . 277X Authorization Routines . . . . . . . . . 280X Intrinsics Routines . . . . . . . . . . . 280Athena Widget Support . . . . . . . . . . 290Extension Routines . . . . . . . . . . . 292MIT Extensions to X . . . . . . . . . . . 293Associate Table Functions . . . . . . . . . 293Miscellaneous Utility Routines. . . . . . . . 293X Authorization Routines . . . . . . . . . 293X Window System Toolkit . . . . . . . . . 293Application Resources . . . . . . . . . . 295Athena Widget Set . . . . . . . . . . . 296OSF/Motif-Based Widget Support . . . . . . 297Sample X Window System Applications . . . . 299Xlib Sample Program . . . . . . . . . . . 299Athena Widget Sample Program . . . . . . . 300OSF/Motif-Based Widget Sample Program . . . 302Chapter 8. Kerberos AuthenticationSystem . . . . . . . . . . . . . . 303Authentication Server . . . . . . . . . . 303Name Structures . . . . . . . . . . . 303Tickets and Authenticators . . . . . . . . 304Communicating with the Authentication Server 304Ticket-Granting Server . . . . . . . . . . 305viz/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Accessing a Service . . . . . . . . . . 305Kerberos Database. . . . . . . . . . . . 306Administration Server . . . . . . . . . . 306Kerberos C Language Applications Library . . . 307Kerberos Routines <strong>Reference</strong> . . . . . . . . 308Client Commands . . . . . . . . . . . 308Applications. . . . . . . . . . . . . . 309Kerberos Routines . . . . . . . . . . . . 309krb_get_cred() . . . . . . . . . . . . 309krb_kntoln() . . . . . . . . . . . . . 309krb_mk_err() . . . . . . . . . . . . 310krb_mk_priv() . . . . . . . . . . . . 310krb_mk_req() . . . . . . . . . . . . 311krb_mk_safe() . . . . . . . . . . . . 311krb_rd_err() . . . . . . . . . . . . . 312krb_rd_priv() . . . . . . . . . . . . 313krb_rd_req() . . . . . . . . . . . . . 314krb_rd_safe() . . . . . . . . . . . . 315krb_recvauth() . . . . . . . . . . . . 315krb_sendauth() . . . . . . . . . . . . 316Sample Kerberos Programs . . . . . . . . . 318Kerberos Client. . . . . . . . . . . . . 318Kerberos Server . . . . . . . . . . . . 320Chapter 9. SNMP Agent DistributedProgram Interface . . . . . . . . . 325SNMP Agents and Subagents . . . . . . . . 325Processing DPI Requests. . . . . . . . . . 326Processing a GET Request . . . . . . . . 327Processing a SET Request . . . . . . . . 327Processing a GET_NEXT Request. . . . . . 327Processing a REGISTER Request . . . . . . 328Processing a TRAP Request. . . . . . . . 328Compiling and Linking . . . . . . . . . . 328SNMP DPI <strong>Reference</strong> . . . . . . . . . . . 329DPI Library Routines . . . . . . . . . . . 329DPIdebug() . . . . . . . . . . . . . 329fDPIparse() . . . . . . . . . . . . . 330mkDPIlist() . . . . . . . . . . . . . 330mkDPIregister() . . . . . . . . . . . 331mkDPIresponse() . . . . . . . . . . . 331mkDPIset() . . . . . . . . . . . . . 332mkDPItrap(). . . . . . . . . . . . . 333mkDPItrape() . . . . . . . . . . . . 334Example of an Extended Trap . . . . . . . 334pDPIpacket() . . . . . . . . . . . . 335query_DPI_port() . . . . . . . . . . . 336Sample SNMP DPI Client Program . . . . . . 337The DPISAMPLE Program (Sample DPI Subagent) 337DPISAMPLE TABLE . . . . . . . . . . 339Client Sample Program . . . . . . . . . . 339Compiling and Linking the DPISAMPLE.CSource Code. . . . . . . . . . . . . 358Chapter 10. SMTP Virtual MachineInterfaces . . . . . . . . . . . . . 359SMTP Transactions . . . . . . . . . . . 359SMTP Commands . . . . . . . . . . . . 360HELO . . . . . . . . . . . . . . . 360EHLO . . . . . . . . . . . . . . . 361MAIL FROM . . . . . . . . . . . . 361RCPT TO . . . . . . . . . . . . . 362DATA . . . . . . . . . . . . . . . 363RSET . . . . . . . . . . . . . . . 364QUIT . . . . . . . . . . . . . . . 364NOOP. . . . . . . . . . . . . . . 364HELP . . . . . . . . . . . . . . . 364QUEU . . . . . . . . . . . . . . . 365VRFY . . . . . . . . . . . . . . . 367EXPN . . . . . . . . . . . . . . . 368VERB . . . . . . . . . . . . . . . 368TICK . . . . . . . . . . . . . . . 369SMTP Command Example . . . . . . . . . 369SMTP Command Responses . . . . . . . . 369Path Address Modifications . . . . . . . . 370Batch SMTP Command Files . . . . . . . . 371Batch SMTP Examples . . . . . . . . . . 371Sending Mail to a <strong>TCP</strong> Network Recipient. . . 371Querying SMTP Delivery Queues . . . . . 372SMTP Exit Routines . . . . . . . . . . . 373Client Verification Exit . . . . . . . . . . 373Built-in Client Verification Function . . . . . 373Client Verification Exit Parameter Lists . . . . 374Using the Mail Forwarding Exit . . . . . . . 378Mail Forwarding Exit Parameter Lists . . . . 379Using the SMTP Command Exit . . . . . . . 384SMTP Command Exit Parameter Lists . . . . 385Chapter 11. Telnet Exits . . . . . . . 391Telnet Session Connection Exit . . . . . . . 391Telnet Exit Parameter List . . . . . . . . 392Sample Exit . . . . . . . . . . . . . 392Telnet Printer Management Exit . . . . . . . 393Telnet Printer Management Exit Parameter List 393Sample Exit . . . . . . . . . . . . . 393Chapter 12. FTP Server Exit . . . . . 395The FTP Server Exit . . . . . . . . . . . 395Sample Exit . . . . . . . . . . . . . 395Audit Processing . . . . . . . . . . . . 395Audit Processing Parameter List . . . . . . 396Audit Processing Parameter Descriptions . . . 396Return Codes from Audit Processing . . . . 398General Command Processing . . . . . . . . 398General Command Processing Parameter List 398General Command Processing ParameterDescriptions . . . . . . . . . . . . . 399Return Codes from General CommandProcessing . . . . . . . . . . . . . 400Change Directory Processing . . . . . . . . 401Change Directory Processing Parameter List . . 401Appendix A. Pascal Return Codes . . 405Explanatory Notes. . . . . . . . . . . . 407Appendix B. C API System ReturnCodes . . . . . . . . . . . . . . 409Contentsvii


Preface||<strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong>: Programmer’s <strong>Reference</strong> describes the routines for applicationprogramming in <strong>IBM</strong>* Transmission Control Protocol/Internet Protocol Version 3Release 1.0 for <strong>VM</strong> (<strong>TCP</strong>/<strong>IP</strong> Level 3A0 for <strong>VM</strong>).Who Should Read This BookThis book contains reference information about the following applicationprogramming interfaces (API):v C socketsv Pascalv Virtual Machine Communication Facility (<strong>VM</strong>CF)v Remote Procedure Calls (RPCs)v X Window Systemv Kerberos Authentication SystemvvvSimple Network Management Protocol (SNMP) agent distributed programinterfaceConversational Monitor System (CMS) command interface to the name serverSimple Mail Transfer Protocol (SMTP)The descriptive information in the chapters is supplemented with appendixes thatcontain sample programs and quick references.For comments and suggestions about this book, use the Reader’s Comment Formlocated at the back of this book. This form gives instructions on submitting yourcomments by mail, by FAX, or by electronic mail.This book is intended for users and programmers who are familiar with <strong>VM</strong>/ESAand the Control Program (CP) and the Conversational Monitor System (CMS)components. You should also be familiar with the C or Pascal programminglanguage and the specific Application Programming Interface (API) that you areusing.What You Should Know before Reading This BookWhat This Book ContainsBefore using this book, you should be familiar with z/<strong>VM</strong>, CP, and CMS. Inaddition, <strong>TCP</strong>/<strong>IP</strong> Level 3A0 for <strong>VM</strong> should already be installed and customizedfor your network.You should read this book when you want to use the application programminginterfaces that are available in <strong>TCP</strong>/<strong>IP</strong> Level 3A0 for <strong>VM</strong>.“Chapter 1. General Programming Information” on page 1, provides informationfor programmers who use the application program interfaces described in thisbook.© Copyright <strong>IBM</strong> Corp. 1987, 2001 ix


“Chapter 2. C Sockets Application Program Interface” on page 5, describes the CSocket application program interface provided with <strong>TCP</strong>/<strong>IP</strong> Level 3A0 for <strong>VM</strong>.“Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language)” on page 95, describes how to usethe Pascal language application program interface to write application programsfor the <strong>TCP</strong>, UDP, and <strong>IP</strong> layers of the <strong>TCP</strong>/<strong>IP</strong> protocol suite.“Chapter 4. Virtual Machine Communication Facility Interface” on page 147,describes how to communicate directly with the <strong>TCP</strong><strong>IP</strong> virtual machine usingVirtual Machine Communication Facility calls.“Chapter 5. Inter-User Communication Vehicle Sockets” on page 169, describes howto use the (IUCV) socket. While not every C socket library function is provided, allof the basic operations necessary to communicate with other socket programs arepresent.“Chapter 6. Remote Procedure Calls” on page 201, describes the Remote ProcedureCall protocol, which permits remote execution of subroutines across a <strong>TCP</strong>/<strong>IP</strong>network.“Chapter 7. X Window System Interface” on page 251, describes the X WindowSystem and subroutines for <strong>TCP</strong>/<strong>IP</strong> Level 3A0 for <strong>VM</strong>.“Chapter 8. Kerberos Authentication System” on page 303, describes the KerberosAuthentication System and the routines for writing authentication programs.“Chapter 9. SNMP Agent Distributed Program Interface” on page 325, describes theSimple Network Management Protocol (SNMP) agent distributed programinterface (DPI).“Chapter 10. SMTP Virtual Machine Interfaces” on page 359, describes thecommunication interfaces to the SMTP virtual machine.“Chapter 11. Telnet Exits” on page 391, describes the Telnet server exits thatprovide CP command simulation, TN3270E printer management, and systemaccess control when Telnet connections are established with your host.“Chapter 12. FTP Server Exit” on page 395, describes the FTP Server Exit“Appendix A. Pascal Return Codes” on page 405, lists the system return codes asthey apply to Pascal calls and provides their numeric value and description.“Appendix B. C API System Return Codes” on page 409, lists the system returncodes and provides their numeric value and a description.“Appendix C. Well-Known Port Assignments” on page 413, This appendix lists thewell-known port assignments for transport protocols <strong>TCP</strong> and UDP, and includesport number, keyword, and a description of the reserved port assignment. You canalso find a list of these well-known port numbers in the ETC SERVICES file.“Appendix D. Related Protocol Specifications” on page 417, lists the relatedprotocol specifications concerning <strong>TCP</strong>/<strong>IP</strong> Level 3A0 for <strong>VM</strong>.“Appendix E. Abbreviations and Acronyms” on page 421, lists and defined theabbreviations and acronyms used in this book.xz/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Syntax Diagram DescriptionAbbreviations:Uppercase letters denote the shortest acceptable abbreviation.If an item appears entirely in uppercase letters, it cannot beabbreviated.Example►► KEYWOrd ►◄You can type the item in uppercase letters, lowercase letters,or any combination.In this example, you can enter KEYWO, KEYWOR, orKEYWORD in any combination of uppercase and lowercaseletters.Symbols:You must code these symbols exactly as they appear in thesyntax diagram.* Asterisk: Colon, Comma= Equal Sign- Hyphen() Parentheses. PeriodVariables:Highlighted lowercase items (like this) denote variables.►► KEYWOrd ►In this example, var_name represents a variable you mustspecify when you code the KEYWORD command.► var_name►◄Repetition:An arrow returning to the left means that the item can berepeated.A character within the arrow means you must separaterepeated items with that character.A footnote (1) by the arrow references a limit that tells howmany times the item can be repeated.►► ▼ repeat ►◄►► ▼ ,repeat ►◄►► ▼ (1) repeat ►◄Notes:1 Specify repeat up to 5times.xiiz/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Syntax Diagram DescriptionRequired Choices:When two or more items are in a stack and one of them is onthe line, you must specify one item.In this example, you must choose A, B, or C.Example►►ABC►◄Optional Choice:When an item is below the line, the item is optional. In thisexample, you can choose A or nothing at all.►►A►◄When two or more items are in a stack below the line, all ofthem are optional. In this example, you can choose A, B, C, ornothing at all.►►ABC►◄Defaults:Defaults are above the line. The system uses the defaultunless you override it. You can override the default by codingan option from the stack below the line.►►ABC►◄In this example, A is the default. You can override A bychoosing B or C.Repeatable Choices:A stack of items followed by an arrow returning to the leftmeans that you can select more than one item or, in somecases, repeat a single item.In this example, you can choose any combination of A, B, orC.Syntax Fragments:►► ▼ ABC►◄Some diagrams, because of their length, must fragment thesyntax. The fragment name appears between vertical bars inthe diagram. The expanded fragment appears in the diagramafter a heading with the same fragment name.In this example, the fragment is named “A Fragment.”►► A Fragment ►◄A Fragment:ABCPrefacexiii


How Numbers Are Used in This BookIn this book, numbers over four digits are represented in metric style. A space isused rather than a comma to separate groups of three digits. For example, thenumber sixteen thousand, one hundred forty-seven is written 16 147.How to Send Your Comments to <strong>IBM</strong>|Your feedback is important in helping us to provide the most accurate andhigh-quality information. If you have comments about this book or any other <strong>VM</strong>documentation, send your comments to us using one of the following methods. Besure to include the name of the book, the form number (including the suffix), andthe page, section title, or topic you are commenting on.v Visit the z/<strong>VM</strong> web site at:http://www.ibm.com/servers/eserver/zseries/zvmvvThere you will find the feedback page where you can enter and submit yourcomments.Send your comments by electronic mail to one of the following addresses:Internet: pubrcf@vnet.ibm.com<strong>IBM</strong>Link : GDL<strong>VM</strong>E(PUBRCF)Fill out the Readers’ Comments form at the back of this book and return it usingone of the following methods:– Mail it to the address printed on the form (no postage required in the USA).– Fax it to 1-607-752-2327.– Give it to an <strong>IBM</strong> representative.xivz/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Summary of ChangesThis section describes the technical changes made in this edition of the book and inprevious editions. For your convenience, the changes made in this edition areidentified in the text by a vertical bar (|) in the left margin. This edition may alsoinclude minor corrections and editorial changes that are not identified.|||||||||||First Edition for z/<strong>VM</strong> (February 2001)This edition contains updates for the General Availability of <strong>TCP</strong>/<strong>IP</strong> Level 3A0Programmer’s <strong>Reference</strong>.<strong>IP</strong> MulticastSupport for <strong>IP</strong> Multicast has been added for the C sockets application programinterfaces getsockopt and setsockopt.Other ChangesvvvMiscellaneous service updates were added since the previous release.XCLIENT sample programs were removed.The chapter on NCS was removed. The product is now unsupported.Second Edition for <strong>VM</strong>/ESA ® (July 1999)First Edition for <strong>VM</strong>/ESAThis edition contains updates for the General Availability of <strong>TCP</strong>/<strong>IP</strong> FunctionLevel 320 Programmer’s <strong>Reference</strong>.vvvThe chapter ’SMTP Virtual Machine Interfaces’, which discusses the interfaces tothe SMTP server, has been updated to include new support for ExtendedServices and the server exits.A new chapter with details of the telnet server session connection and printermanagement exits was added.A new chapter for the FTP Server Exit was added.This edition contains updates for the General Availability of <strong>TCP</strong>/<strong>IP</strong> FunctionLevel 310 Programmer’s <strong>Reference</strong>.vThe DUMMYprobe and ACTIVEprobe <strong>VM</strong>CF interrupt headers were added toChapter 4.© Copyright <strong>IBM</strong> Corp. 1987, 2001 xv


xviz/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Chapter 1. General Programming InformationPorting ConsiderationsThis chapter contains fundamental, technical information that programmers needto know before they attempt to work with the application program interfaces (API)provided with <strong>TCP</strong>/<strong>IP</strong>.Important NoteIn order to develop or port applications in the C programming language thatinterface directly to <strong>TCP</strong>, UDP, and <strong>IP</strong>, or which modify <strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong> Ccomponents, the following are required:v <strong>IBM</strong> C for <strong>VM</strong>/ESA Compiler, Version 3 Release 1 (5654-033)v Language Environment, which is included in the base release.Accessing System Return MessagesTo access system return values while running your C program, use only theerrno.h include statement supplied with the compiler. To access <strong>TCP</strong>/<strong>IP</strong> networkreturn values, add the following include statement to your C program:#include Printing System Return MessagesTo print only system errors, use perror(), a procedure available in the C compilerrun-time library. To print both system and network errors, use tcperror(), aprocedure provided by <strong>IBM</strong> and included with <strong>TCP</strong>/<strong>IP</strong> Level 320 for <strong>VM</strong>.Compiling and Linking C ApplicationsThis section describes how to compile and link-edit C applications that use the<strong>TCP</strong>/<strong>IP</strong> C sockets1. Access the <strong>TCP</strong>/<strong>IP</strong> client minidisk (<strong>TCP</strong>MAINT 592) ahead of the S-disk toavoid conflicts with OpenEdition ® for <strong>VM</strong>/ESA.Establish the C development environment:– Access the C compiler– SET LDRTBLS 25 (the number you need depends on your program)– GLOBAL LOADLIB SCEERUNNote: CMSLIB is required only when the program will run in a 370-modevirtual machine.2. Compile your programs, ensuring that the preprocessor symbol <strong>VM</strong> isdefined. For example:CC myprog (DEF(<strong>VM</strong>)With OpenEdition for <strong>VM</strong>/ESA you can also use the c89 command and themake shell utility.© Copyright <strong>IBM</strong> Corp. 1987, 2001 1


General Programming Information3. Select the link libraries your applications need and put them on a GLOBALTXTLIB command. SCEELKED and COMMTXT are the minimum required:GLOBAL TXTLIB SCEELKED COMMTXTAdditional libraries, listed in Table 1 may be required depending on the <strong>TCP</strong>/<strong>IP</strong>functions your application uses. For example, programs that use RPC mustissue:GLOBAL TXTLIB SCEELKED COMMTXT RPCLIBTextlib (TXTLIB) FilesTable 1. TXTLIB Files and ApplicationsTXTLIB FileCOMMTXTRPCLIBBPLDBMKDBKRBDESX11LIBOLDXLIBXTLIBXAWLIBXMLIBDPILIBApplicationC Sockets and Pascal APIRemote Procedure CallsKerberosKerberosKerberosKerberosXlib, Xmu, Xext and Xau RoutinesX Release 10 compatibility routinesX IntrinsicsAthena Widget SetOSF/Motif-based widget setSNMP DPI|4. Link-edit your programs into an executable module. The sample applicationsin this book are built using the <strong>TCP</strong>LOAD utility. Your own applications shouldbe built using the CMOD command. For example:<strong>TCP</strong>LOAD sample@c corCMOD myprog1 myprog2 (AUTOComplete information on compiling and link-editing C programs can be foundin the C <strong>VM</strong>/ESA User’s Guide, SC09-2151.<strong>TCP</strong>LOAD EXECThe <strong>TCP</strong>LOAD EXEC is provided to generate an executable module from yourcompiled program. When running <strong>TCP</strong>LOAD, all disks containing object files mustbe accessed as extensions of the A-disk. The <strong>TCP</strong>LOAD EXEC generates a modulewhen given a list of text file names and a control file.►► <strong>TCP</strong>LOAD load_list control_file type ►2 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


General Programming Information►(XA►◄TXTLIBfilename▼filenameParameterload_listcontrol_filetypeDescriptionSpecifies the file name of a file with the file type LOADLIST thatcontains file names to be included in the load module. The firstline in the load_list specifies the name of the main object module.Subsequent lines specify additional object modules to be includedin the load module.Specifies the control_file, which determines the file types of text filesaccording to the standard update identifier procedure.Specifies the type parameter as one of the following:C Includes SCEELKED, CMSLIB, RPCLIB, <strong>TCP</strong>ASCAL,<strong>TCP</strong>LANG, COMMTXT, and CLIB txtlibs.C-ONLYIncludes SCEELKED, RPCLIB, COMMTXT, CMSLIB, andCLIB txtlib.PASCALIncludes <strong>TCP</strong>ASCAL, <strong>TCP</strong>LANG, and COMMTXT txtlibs.PASCAL is the default for the type parameter.XASpecify this option if the application requires storage above the16Mb line. The application will be generated RMODE ANY andAMODE 31. Pascal applications will require the GLOBALLOADLIB <strong>TCP</strong>RTLIB command be issued before being run.TXTLIB Specifies the TXTLIB option, which allows you to specify up to 50filenames that will be added to the GLOBAL TXTLIB command.See Table 1 on page 2 for a list of the files necessary for eachapplication.If <strong>TCP</strong>LOAD is not used, you must global the appropriate TXTLIB files.Using <strong>TCP</strong>LOADThe following example describes how to use <strong>TCP</strong>LOAD to generate an executablemodule from object files.1. Create a file with file type LOADLIST, which contains all the object (TEXT) filesto be linked. For example, llistfn loadlist.2. Create a control file with file type CNTRL, which contains the list of TEXT filetypes. For example, ctrlfn cntrl.3. Invoke the <strong>TCP</strong>LOAD command, as shown in the following example.<strong>TCP</strong>LOAD llistfn ctrlfn C (TXTLIB mylib1 mylib2Where:v llistfn is the LOADLIST file namev ctrlfn is the control file namev C is the language of the main programv TXTLIB is the keyword that specifies the libraries to linkChapter 1. General Programming Information 3


General Programming Informationv mylib1 and mylib2 are the libraries to link.The following is an example of how to create an executable module from a list ofobject files. In the example, OBJ1, OBJ2, OBJ3, OBJ4, and OBJ5 are TEXT files createdby compiling C programs, and MYLIB1 and MYLIB2 are libraries.1. Create the file SAMPLE LOADLIST that lists the object files:OBJ1OBJ2OBJ3OBJ4OBJ52. Create the file TEST CNTRL with the following:TEXTSET LDRTBLS Command3. Invoke <strong>TCP</strong>LOAD with the following command:<strong>TCP</strong>LOAD SAMPLE TEST C (TXTLIB MYLIB1 MYLIB2This creates the executable file SAMPLE MODULE.The SET LDRTBLS command defines the number of pages of storage to be usedfor loader tables (LDRTBLS). By default, a virtual machine having up to 384 Kb ofaddressable storage has three pages of loader tables; a larger virtual machine hasfour pages. Each loader table page has a capacity of 169 external names. DuringLOAD and INCLUDE command processing, each unique, external nameencountered in a TEXT deck is entered in the loader table.►► SET LDRTBLS nn ►◄ParameternnDescriptionSpecifies the number of pages to be used for loader tables.For more information about the SET LDRTBLS command, see the CMS Command<strong>Reference</strong>.4 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Chapter 2. C Sockets Application Program InterfaceProgramming with C SocketsThis chapter describes the C socket application program interface (API) providedwith <strong>TCP</strong>/<strong>IP</strong>. Use the socket routines in your C program to interface with the <strong>TCP</strong>,UDP, and <strong>IP</strong> protocols. This allows you to communicate across networks withother programs. You can, for example, make use of socket routines when you writea client program that must communicate with a server program running onanother computer.To use the C socket API, you should know C language programming.For more information about C sockets, see the <strong>IBM</strong> AIX ® Operating System Technical<strong>Reference</strong>: System Calls and Subroutines.The <strong>VM</strong> C socket API provides a standard interface to the transport andinternetwork layer interfaces of <strong>TCP</strong>/<strong>IP</strong>. It supports three socket types: stream,datagram, and raw. Stream and datagram sockets interface to the transport layerprotocols, and raw sockets interface to the network layer protocols. Theprogrammer chooses the most appropriate interface for an application.Socket Programming ConceptsBefore programming with the C socket API, you should consider the followingimportant concepts.What is a Socket?A socket is an endpoint for communication that can be named and addressed in anetwork. From an application program perspective, it is a resource allocated by thevirtual machine. It is represented by an integer called a socket descriptor.The socket interface was designed to provide applications with a network interfacethat hides the details of the physical network. The interface is differentiated by thedifferent services that are provided. Stream, datagram, and raw sockets each definea different service available to applications.The stream socket interface defines a reliable connection-oriented service. Data issent without errors or duplication and is received in the same order as it is sent.Flow control is built in to avoid data overruns. No boundaries are imposed on thedata; it is considered to be a stream of bytes. An example of an application thatuses stream sockets is Telnet.The datagram socket interface defines a connectionless service. Datagrams are sentas independent packets. The service provides no guarantees; data can be lost orduplicated, and datagrams can arrive out of order. The size of a datagram islimited to the size that can be sent in a single transaction (currently the default is8192 and the maximum is 32,767). No disassembly and reassembly of packets isperformed. An example of an application that uses datagram sockets is theNetwork File System (NFS).© Copyright <strong>IBM</strong> Corp. 1987, 2001 5


C Sockets Application Program InterfaceThe raw socket interface allows direct access to lower layer protocols such as <strong>IP</strong>and Internet Control Message Protocol (ICMP). The interface is often used fortesting new protocol implementations.The socket interface can be extended; therefore, you can define new socket types toprovide additional services. Because socket interfaces isolate you from thecommunication functions of the different protocol layers, the interfaces are largelyindependent of the underlying network. In the <strong>VM</strong> implementation of sockets,stream sockets interface to <strong>TCP</strong>, datagram sockets interface to UDP, and rawsockets interface to ICMP and <strong>IP</strong>. In the future, the underlying protocols canchange; however, the socket interface remains the same. For example, streamsockets can eventually interface to the International Standards Organization (ISO)Open System Interconnection (OSI) transport class 4 protocol. This means thatapplications do not have to be rewritten as underlying protocols change. For moreinformation about open System Interconnection, see Open System Interconnection:<strong>Reference</strong> Summary.Guidelines for Using Socket TypesThe following considerations help you choose the appropriate socket type for anapplication.If you are communicating to an existing application, use the same protocols as theexisting application. For example, if you interface to an application that uses <strong>TCP</strong>,use stream sockets. For other applications you should consider the followingfactors:vvvReliability. Stream sockets provide the most reliable connection. Datagram, orraw sockets, are unreliable, because packets can be discarded, corrupted, orduplicated during transmission. This can be acceptable if the application doesnot require reliability, or if the application implements the reliability on top ofthe sockets interface. The trade-off is the increased performance available overstream sockets.Performance. The overhead associated with reliability, flow control, packetreassembly, and connection maintenance degrade the performance of streamsockets so that they do not perform as well as datagram sockets.The amount of data to be transferred. Datagram sockets impose a limit on theamount of data transferred in a single transaction. If you send less than 2048bytes at a time, use datagram sockets. As the amount of data in a singletransaction increases, it makes more sense to use stream sockets.If you are writing a new protocol on top of <strong>IP</strong>, or wish to use the ICMP protocol,then you must choose raw sockets.Addressing within SocketsThe following sections describe the different ways to address within the C socketAPI.Address FamiliesAddress families define different styles of addressing. All hosts in the sameaddressing family understand and use the same scheme for addressing socketendpoints. <strong>TCP</strong>/<strong>IP</strong> supports two addressing families: AF_INET and AF_IUCV. TheAF_INET domain defines addressing in the internet (INET) domain. The AF_IUCVdomain defines addressing in the Inter-User Communication Vehicle (IUCV)domain. In the IUCV domain, virtual machines can use the socket interface tocommunicate with other virtual machines on the same host.6 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Socket AddressA socket address is defined by the sockaddr structure in the SOCKETS.H headerfile. It has two fields as shown in the following example:struct sockaddr{unsigned short sa_family; /* address family */char sa_data[14]; /* up to 14 bytes of direct address */};The sa_family field contains the addressing family. It is AF_INET for the internetdomain and AF_IUCV for the IUCV domain. The sa_data field is different for eachaddress family. Each address family defines its own structure, which can beoverlaid on the sockaddr structure. For more information about the internet domain,see “Addressing within an Internet Domain” and for more information about theIUCV domain, see “Addressing within the IUCV Domain” on page 8.Internet AddressesInternet addresses are 32-bit quantities that represent a network interface. Everyinternet address within an administered AF_INET domain must be unique. Acommon misunderstanding is that every host must have a unique internet address.In fact, a host has as many internet addresses as it has network interfaces.PortsA port is used to differentiate between different applications using the samenetwork interface: it is an additional qualifier used by the system software to getdata to the correct application. Physically, a port is a 16-bit integer. Some ports arereserved for particular applications and are called well-known ports. For a listingof well-known ports, see “Appendix C. Well-Known Port Assignments” onpage 413.Network Byte OrderPorts and addresses are usually specified to calls using the network byte orderingconvention. Network byte order is also known as big endian byte ordering, wherethe high-order byte defines significance, (as compared with little endian byteordering, where the low-order byte defines significance). Using network byteordering for data exchanged between hosts allows hosts using differentarchitectures to exchange address information. For examples of using the htons()call to put ports into network byte order, see Figure 2 on page 9, Figure 5 onpage 10, and Figure 8 on page 12. For more information about network byte order,see “accept()” on page 22, “bind()” on page 23, “htonl()” on page 51, “htons()” onpage 51, “ntohl()” on page 58, and “ntohs()” on page 59.Note: The socket interface does not handle application data byte orderingdifferences. Application writers must handle byte order differencesthemselves or use higher-level interfaces, such as Remote Procedure Calls(RPC).Addressing within an Internet DomainA socket address in an internet addressing family comprises four fields: theaddress family (AF_INET), an internet address, a port, and a character array. Thestructure of an internet socket address is defined by the following sockaddr_instructure, which is found in the IN.H header file:struct in_addr{unsigned long s_addr;};struct sockaddr_in{C Sockets Application Program InterfaceChapter 2. C Sockets Application Program Interface 7


C Sockets Application Program Interface};short sin_family; /* addressing family */unsigned short sin_port; /* port number */struct in_addr sin_addr; /* internet address */char sin_zero[8]; /* zeros */The sin_family field is set to AF_INET. The sin_port field is the port used by theapplication, in network byte order. The sin_addr field is the internet address of thenetwork interface used by the application. It is also in network byte order. Thesin_zero field should be set to all zeroes.Addressing within the IUCV DomainA socket address in the IUCV addressing family is comprised of six fields: theaddress family (AF_INET), three reserved fields, a <strong>VM</strong> user ID, and an applicationname. The structure of an IUCV socket address is defined by the followingsockaddr_iucv structure, which is found in the SAIUCV.H header file.struct sockaddr_iucv{short siucv_family; /* addressing family */unsigned short siucv_port; /* port number */unsigned long siucv_addr; /* address */unsigned char siucv_nodeid[8]; /* nodeid to connect to */unsigned char siucv_user_id[8]; /* user_id to connect to */unsigned char siucv_name[8]; /* iucvname for connect */};The siucv_family field is set to AF_IUCV. The siucv_port, siucv_addr, and siucv_nodeidfields are reserved for future use. The siucv_userid field is the <strong>VM</strong> user ID and thesiucv_name field is the application name by which the socket is to be known for thebind() or connect() calls.Either IUCV ANY or IUCV ALLOW must be specified in the system directory forthe virtual machine. This specification shows the approval of the client or server todo socket communication with another virtual machine.Main Socket CallsYou can write a very powerful network application with less than a dozen socketcalls.1. First, an application must get a socket descriptor using the socket() call, as inthe example shown in Figure 1. For a complete description, see “socket()” onpage 82.int socket(int domain, int type, int protocol);.int s;.s = socket(AF_INET, SOCK_STREAM, 0);Figure 1. An Application Uses the socket() CallThe code fragment in Figure 1 allocates a socket descriptor s in the internetaddressing family (AF_INET). The domain parameter is a constant thatspecifies the domain where the communication is taking place. A domain isthe collection of applications using the same naming convention. <strong>VM</strong> supportstwo addressing families: AF_INET and AF_IUCV. The type parameter is aconstant that specifies the type of socket, which can be SOCK_STREAM forstream sockets, SOCK_DGRAM for datagram sockets, or SOCK_RAW for raw8 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


sockets. In the AF_IUCV domain, the type must be SOCK_STREAM. Theprotocol parameter is a constant that specifies the protocol to use, and isignored unless type is set to SOCK_RAW. Passing 0 chooses the defaultprotocol. If successful, socket() returns a positive integer socket descriptor.2. Once an application has a socket descriptor, it can explicitly bind() a uniquename to the socket, as in the example shown in Figure 2. For a completedescription, see “bind()” on page 23.int bind(int s, struct sockaddr *name, int namelen);.int rc;int s;struct sockaddr_in myname;C Sockets Application Program Interface./* clear the structure to be sure that the sin_zero field is clear */memset(&myname, 0, sizeof(myname));myname.sin_family = AF_INET; /* internet addressing family */myname.sin_addr.s_addr = inet_addr(“129.5.24.1”); /* specific interface */myname.sin_port = htons(1024); /* port number */rc = bind(s, (struct sockaddr *) &myname, sizeof(myname));Figure 2. An Application Uses the bind() CallThis example binds myname to socket s. The name specifies that the applicationis in the internet domain (AF_INET) at internet address 129.5.24.1, and isbound to port 1024. Servers must bind a name to become accessible from thenetwork. The example in Figure 2 shows two useful utility routines:vinet_addr() takes an internet address in dotted-decimal form and returns itin network byte order. For a complete description, see “inet_addr()” onpage 52.v htons() takes a port number in host byte order and returns the port innetwork byte order. For a complete description, see “htons()” on page 51.For another example of the bind() call, see Figure 3. It uses the utility routinegethostbyname() to find the internet address of the host, rather than usinginet_addr() with a specific address.int bind(int s, struct sockaddr_in name, int namelen);.int rc;int s;char *hostname = “myhost”;struct sockaddr_in myname;struct hostent *hp;hp = gethostbyname(hostname);/*clear the structure to be sure that the sin_zero field is clear*/memset(&myname,0,sizeof(myname));myname.sin_family = AF_INET;myname.sin_addr.s_addr = *((unsignedlong *)hp->h_addr);myname.sin_port = htons(1024);.rc = bind(s,(struct sockaddr *) &myname, sizeof(myname));Figure 3. A bind() Call Uses the gethostbyname() CallChapter 2. C Sockets Application Program Interface 9


C Sockets Application Program Interfaceof the client and length of the client name are returned, along with a newsocket descriptor. The new socket descriptor is associated with the client thatinitiated the connection and s is again available to accept new connections.For a complete description, see “accept()” on page 22.6. Clients and servers have many calls from which to choose for data transfer.The read() and write(), readv() and writev(), and send() and recv() calls can beused only on sockets that are in the connected state. The sendto() andrecvfrom() and sendmsg() and recvmsg() calls can be used at any time. Theexample shown in Figure 7 illustrates the use of send() and recv().int send(int socket, char *buf, int buflen, int flags);int recv(int socket, char *buf, int buflen, int flags);.int bytes_sent;int bytes_received;char data_sent[256];char data_received[256];int s;.bytes_sent = send(s, data_sent, sizeof(data_sent), 0);.bytes_received = recv(s, data_received, sizeof(data_received), 0);Figure 7. An Application Uses the send() and recv() CallsThe example in Figure 7 shows an application sending data on a connectedsocket and receiving data in response. The flags field can be used to specifyadditional options to send() or recv(), such as sending out-of-band data. Formore information about these routines, see “read()” on page 59, “readv()” onpage 60, “recv()” on page 61, “send()” on page 68, “write()” on page 87, and“writev()” on page 88.7. If the socket is not in a connected state, additional address information mustbe passed to sendto() and can be optionally returned from recvfrom(). Anexample of the use of the sendto() and recvfrom() calls is shown in Figure 8 onpage 12.Chapter 2. C Sockets Application Program Interface 11


C Sockets Application Program Interfaceint sendto(int socket, char *buf, int buflen, int flags,struct sockaddr *addr, int addrlen);int recvfrom(int socket, char *buf, int buflen, int flags,struct sockaddr *addr, int addrlen);.int bytes_sent;int bytes_received;char data_sent[256];char data_received[256];struct sockaddr_in to;struct sockaddr from;int addrlen;int s;.to.sin_family = AF_INET;to.sin_addr.s_addr = inet_addr(“129.5.24.1”);to.sin_port= htons(1024);.bytes_sent = sendto(s, data_sent, sizeof(data_sent), 0, (struct sockaddr *) &to, sizeof(to));.addrlen = sizeof(from); /* must be initialized */bytes_received = recvfrom(s, data_received,sizeof(data_received), 0, &from, &addrlen);Figure 8. An Application Uses the sendto() and recvfrom() CallsThe sendto() and recvfrom() calls take additional parameters that allow thecaller to specify the recipient of the data or to be notified of the sender of thedata. For more information about these additional parameters, see“recvfrom()” on page 62, “recvmsg()” on page 63, “sendmsg()” on page 69, and“sendto()” on page 70. Usually, sendto() and recvfrom() are used for datagramsockets, and send() and recv() are used for stream sockets.8. The writev(), readv(), sendmsg(), calls provide the additional features ofscatter and gather data. Scattered data can be located in multiple data buffers.The writev() and sendmsg() calls gather the scattered data and send it. Thereadv() and recvmsg() calls receive data and scatter it into multiple buffers.9. Applications can handle multiple sockets. In such situations, use the select()call to determine the sockets that have data to be read, those that are ready fordata to be written, and the sockets that have pending exceptional conditions.An example of how the select() call is used is shown in Figure 9 on page 13.12 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


C Sockets Application Program Interfacefd_set readsocks;fd_set writesocks;fd_set exceptsocks;struct timeval timeout;int number_of_sockets;int number_found;./* set bits in read write except bit masks. To set mask for a descriptor s use* fd_set(s,&readsocks);** set number of sockets to be checked* number_of_sockets = getdtablesize();*/.number_found = select(number_of_sockets,&readsocks, &writesocks, &exceptsocks, &timeout);Figure 9. An Application Uses the select() CallIn this example, the application sets bit masks to indicate the sockets beingtested for certain conditions and also indicates a time-out. If the time-outparameter is NULL, the call does not wait for any socket to become ready onthese conditions. If the time-out parameter is nonzero, select() waits up to thisamount of time for at least one socket to become ready on the indicatedconditions. This is useful for applications servicing multiple connections thatcannot afford to block, waiting for data on one connection. For a completedescription, see “select()” on page 64.10. In addition to select(), applications can use the ioctl() or fcntl() calls to helpperform asynchronous (nonblocking) socket operations. An example of the useof the ioctl() call is shown in Figure 10.int ioctl(int s, unsigned long command, char *command_data);.int s;int dontblock;char buf[256];int rc;dontblock = 1;.rc = ioctl(s, FIONBIO, (char *) &dontblock);.if (recv(s, buf, sizeof(buf), 0) == −1 && errno == EWOULDBLOCK)/* no data available */else/* either got data or some other error occurred */Figure 10. An Application Uses the ioctl() and fcntl() CallsThis example causes the socket s to be placed into nonblocking mode. Whenthis socket is passed as a parameter to calls that would block, such as recv()when data is not present, it causes the call to return with an error code, andthe global errno value is set to EWOULDBLOCK. Setting the mode of thesocket to be nonblocking allows an application to continue processing withoutbecoming blocked. For a complete description see: “fcntl()” on page 31 and“ioctl()” on page 54.Chapter 2. C Sockets Application Program Interface 13


C Sockets Application Program Interface11. A socket descriptor, s, is deallocated with the close() call. For a completedescription see: “close()” on page 27. An example of the close() call is shownin Figure 11.int close(int s);.int rc;int s;rc = close(s);Figure 11. An Application Uses the close() CallA Typical <strong>TCP</strong> Socket SessionYou can use <strong>TCP</strong> sockets for both passive (server) and active (client) processes.While some commands are necessary for both types, some are role-specific. Forsample C socket communication client and server programs, see “Sample C SocketPrograms” on page 89.Once you make a connection, it exists until you close the socket. During theconnection, data is either delivered or an error code is returned by <strong>TCP</strong>/<strong>IP</strong>.For the general sequence of calls to be followed for most socket routines using <strong>TCP</strong>sockets, see Figure 12 on page 15.14 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


C Sockets Application Program InterfaceCLIENTSERVER┌─────────────────────────────────────────────────┐ ┌─────────────────────────────────────────────────┐│ │ │ ││ Create a stream socket s with the socket() │ │ Create a stream socket s with the socket() ││ call. │ │ call. ││ │ │ │└────────────────────────┬────────────────────────┘ └────────────────────────┬────────────────────────┘││┌────────────────────────┴────────────────────────┐(Optional) │ │Bind socket s to a local address with the │ Bind socket s to a local address with the │bind() call. │ bind() call. │││└────────────────────────┬────────────────────────┘│││┌────────────────────────┴────────────────────────┐│ │ ││ │ With the listen() call, alert the <strong>TCP</strong>/<strong>IP</strong> ││ │ machine of your willingness to accept ││ │ connections. ││└────────────────────────┬────────────────────────┘││┌────────────────────────┴────────────────────────┐││ │ ││ Connect socket s to a foreign host with the │ ││ connect() call. │ ││ │ │└────────────────────────┬────────────────────────┘││││┌────────────────────────┴────────────────────────┐│ │ Accept the connection and receive a second ││ │ socket, for example ns, with the accept() ││ │ call. ││ │ ││└────────────────────────┬────────────────────────┘│││ For the server, socket s remains available ││ to accept new connections. Socket ns ││ is dedicated to the client. │││││┌────────────────────────┴────────────────────────┐ ┌────────────────────────┴────────────────────────┐│ Read and write data on socket s, using the │ │ Read and write data on socket ns, using the ││ send() and recv() calls, until all data has │ ─────►│ send() and recv() calls, until all data has ││ been exchanged. │◄───── │ been exchanged. ││ │ │ │└────────────────────────┬────────────────────────┘ └────────────────────────┬────────────────────────┘││┌────────────────────────┴────────────────────────┐ ┌────────────────────────┴────────────────────────┐│ │ │ ││ Close socket s and end the <strong>TCP</strong>/<strong>IP</strong> session │ │ Close socket ns with the close() call. ││ with the close() call. │ │ ││ │ │ │└─────────────────────────────────────────────────┘ └────────────────────────┬────────────────────────┘│┌────────────────────────┴────────────────────────┐│ Accept another connection from a client, or ││ close the original socket s with the close() ││ call.│││└─────────────────────────────────────────────────┘Figure 12. A Typical <strong>TCP</strong> Socket SessionChapter 2. C Sockets Application Program Interface 15


C Sockets Application Program InterfaceA Typical UDP Socket SessionUDP socket processes, unlike <strong>TCP</strong> socket processes, are not clearly distinguishedby server and client roles. Instead, the distinction is between connected andunconnected sockets. An unconnected socket can be used to communicate with anyhost; however, a connected socket, because it has a dedicated destination, can senddata to, and receive data from, only one host.Both connected and unconnected sockets send their data over the network withoutverification. Consequently, once a packet has been accepted by the UDP interface,the arrival of the packet and the integrity of the packet cannot be guaranteed.For the general sequence of calls to be followed for most socket routines usingUDP sockets, see Figure 13.CLIENTSERVER┌─────────────────────────────────────────────────┐┌────────────────────────────────────────────────┐│ │ │ ││ Create a datagram socket s with the socket() │ │ Create a datagram socket s with the socket() ││ call. │ │ call. ││ │ │ │└───────────────────────┬─────────────────────────┘└──────────────────────┬─────────────────────────┘││┌───────────────────────┴─────────────────────────┐│ │ (Optional)│ Bind socket s to a local address with the │ Bind socket s to a local address with the│ bind() call. │ bind() call.││└───────────────────────┬─────────────────────────┘││(Optional)Connect socket s using the connect() call toassociate s with the client address.(Optional)Connect socket s using the connect() call toassociate s with the server address.││┌───────────────────────┴─────────────────────────┐┌──────────────────────┴─────────────────────────┐│ Send and receive data on socket s, using the │ │ Send and receive data on socket s, using the ││ sendto() and recvfrom() calls, until all data │ ───────► │ sendto() and recvfrom() calls, until all data ││ has been exchanged. Use the send() and recv() │ ◄─────── │ has been exchanged. Use the send() and recv()││ calls if connect() was called. │ │ calls if connect() was called. │└───────────────────────┬─────────────────────────┘└──────────────────────┬─────────────────────────┘││┌───────────────────────┴─────────────────────────┐┌──────────────────────┴─────────────────────────┐│ │ │ ││ Close socket s and end the session with the │ │ Close socket s and end the session with the ││ close() call. │ │ close() call. ││ │ │ │└─────────────────────────────────────────────────┘└────────────────────────────────────────────────┘Figure 13. A Typical UDP Socket SessionC Socket LibraryTo use the socket routines described in this chapter, you must have the followingheader files available on your system:v bsdtypes.hv fcntl.hv if.hv in.h16 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


C Sockets Application Program Interfacevvvvvvinet.hioctl.hmanifest.hnetdb.hsaiucv.hsocket.hThe MANIFEST.H header file contains the prototypes for all the functions. Toreference the prototypes, you should include the following statement at thebeginning of each program:#include The socket library routines are contained in the COMMTXT TXTLIB file.PortingThe <strong>IBM</strong> socket implementation differs from the University of California atBerkeley socket implementation. The following list summarizes the differencesbetween the <strong>IBM</strong> socket implementation and the Berkeley implementation.vvvvvvvvIn the <strong>IBM</strong> implementation, you must make reference to the additional headerfile, <strong>TCP</strong>ERRNO.H, if you want to reference the networking errors other thanthose described in the compiler-supplied ERRNO.H file.In the <strong>IBM</strong> implementation, you must use the tcperror() routine to print thenetworking errno messages. tcperror() should be used only after socket calls.perror() should be used only after C library calls.In the <strong>IBM</strong> implementation, you must include the MANIFEST.H header file toinclude the prototypes of the socket function calls.The <strong>IBM</strong> ioctl() implementation can be different from the current Berkeley ioctl()implementation. See “ioctl()” on page 54 for a description of the functionssupported by the <strong>IBM</strong> implementation.The <strong>IBM</strong> getsockopt() and setsockopt() calls support only a subset of the optionsavailable. See “getsockopt()” on page 45 and “setsockopt()” on page 76 for detailsabout the supported options.The <strong>IBM</strong> fcntl() call supports only a subset of the options available. See “fcntl()”on page 31 for details on the supported options.The <strong>IBM</strong> implementation supports an additional addressing family calledAF_IUCV, which allows <strong>VM</strong> virtual machines on the same host to communicateusing IUCV.The <strong>IBM</strong> implementation now allows the program to increase the maximumnumber of simultaneous sockets through the use of the maxdesc() call.Previously, the total number of sockets was limited to 253 (numbered 3 through255) and the first 47 (numbered 3 through 49) could be AF_INET sockets. Thedefault maximum number of sockets is 47, any or all of which can be AF_INETsockets.Environment Variables Used by the Sockets LibraryEnvironment variables can be used to affect certain aspects of the execution of asockets program. If the sockets program is executed from a shell, the shell controlsthe contents of the program’s environment. For example, the following shellcommand could be used to set the X-SITE environment variable:export X-SITE=//MY.SITEINFOChapter 2. C Sockets Application Program Interface 17


C Sockets Application Program InterfaceIf the sockets program is being run from the CMS command line (or equivalent),then the global variables existing in the CENV group managed by the GLOBALVcommand are used as the environment variables for the process. In this case, aCMS command like the following could be used to temporarily set the X-SITEenvironment variable: 1GLOBALV SELECT CENV SET X-SITE MY.SITEINFOSome of the environment variables described below are set to values whichrepresent file names. For these environment variables, the given file names areinterpreted as POSIX-style file names, which means that case is significant, andthat the file name is interpreted as residing in the Byte File System unless youprecede the file name with two slashes. To specify the name of a file which resideson a minidisk or accessed SFS directory instead of in the BFS, precede the name ofthe file with two slashes, and separate the CMS file name and type (and mode, ifspecified) with a period.The following environment variables can be used to affect the execution of thesockets library:Variable DescriptionX-SITEX-ADDRThis environment variable tells the socket library resolver code touse the named file in place of the HOSTS SITEINFO file, whichcontains information about AF_INET hosts known to this host. Forexample, setting the variable to the string /etc/hosts tells theresolver to use the /etc/hosts file in place of the default file, whichis //HOSTS.SITEINFO. This environment variable is used by thegethostbyname() function call, the gethostent() function call, andseveral others.This environment variable tells the socket library resolver code touse the named file in place of the HOSTS ADDRINFO file, whichcontains information about AF_INET networks known to this host.For example, setting the variable to the string /etc/addrs tells theresolver to use the /etc/addrs file in place of the default file,which is //HOSTS.ADDRINFO. This environment variable is used bythe gethostbyaddr() function call, the getnetent() function call, andseveral others.X-XLATE This environment variable tells the socket library resolver code touse the named file in place of the STANDARD <strong>TCP</strong>XLBIN file, whichcontains ASCII to EBCDIC and EBCDIC to ASCII translation tablesfor use by the resolver when sending or receiving information froman AF_INET network. For example, setting the variable to thestring /etc/xlate tells the resolver to use the /etc/xlate file inplace of the default file, which is //STANDARD.<strong>TCP</strong>XLBIN. Thisenvironment variable is used by the gethostbyname() andgethostbyaddr() function calls.HOSTALIASESThis environment variable tells the socket library resolver code touse the named file when searching for aliases for AF_INET hostnames. For example, setting the variable to the string /etc/aliases1. Be aware, however, that some of the environment variables described accept values which are case sensitive, and which will oftenbe set to lowercase values. It can be difficult, using the GLOBALV command, to set lowercase values, because commands typed infrom the CMS command line are automatically uppercased by CMS before processing. One way to set the variable to amixed-case value is to issue the GLOBALV command from a REXX exec with “Address Command” in effect.18 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


C Socket <strong>Reference</strong>tells the resolver to use the /etc/aliases file when needed. Bydefault, no aliases files is used by the resolver.SOCK_DEBUGThis environment variable is used to activate internal socket librarydebugging messages. If this environment variable is set to thevalue ON (case is not important), then the debugging messages areactivated.This section provides a C socket reference table.Table 2. C Socket <strong>Reference</strong>Socket() Call Description Pageaccept()Accepts a connection request from a 22foreign host.bind() Assigns a local address to the socket. 23close()Closes the socket associated with the 27socket descriptor s.connect()Requests a connection to a foreign27host.endhostent()Closes the HOSTS SITEINFO and30HOSTS ADDRINFO files.endnetent() Closes the HOSTS SITEINFO file. 31endprotoent() Closes the ETC PROTO file. 31endservent() Closes the ETC SERVICES file. 31fcntl()Controls socket operating31characteristics.getclientid()Returns the identifier by which thecalling application is known to the<strong>TCP</strong><strong>IP</strong> virtual machine.32gethostbyaddr()gethostbyname()gethostent()gethostid()gethostname()getnetbyaddr()getnetbyname()getnetent()getpeername()C Sockets Application Program InterfaceReturns information about a hostspecified by an address.Returns information about a hostspecified by a name.Returns the next entry in the HOSTSSITEINFO file.Returns the unique identifier of thecurrent host.Returns the standard name of thecurrent host.Returns the network entry specifiedby address.Returns the network entry specifiedby name.Returns the next entry in the HOSTSSITEINFO file.Returns the name of the peerconnected to socket s.333435363638394040Chapter 2. C Sockets Application Program Interface 19


C Socket <strong>Reference</strong>Table 2. C Socket <strong>Reference</strong> (continued)Socket() Call Description Pagegetprotobyname()Returns a protocol entry specified by 41name.getprotobynumber()Searches the ETC PROTO file for a 41specified protocol number.getprotoent()Returns the next entry in the ETC42PROTO file.getservbyname()Returns a service entry specified by 43name.getservbyport()Returns a service entry specified by 43port number.getservent()Returns the next entry in the44SERVICES file.getsockname() Obtains local socket name. 44getsockopt()Gets options associated with sockets 45in the AF_INET domain.htonl()Translates host byte order to network 51byte order for a long integer.givesocket()Tells <strong>TCP</strong><strong>IP</strong> to make the specifiedsocket available to a takesocket() callissued by another application.49htons()inet_addr()inet_lnaof()inet_makeaddr()inet_netof()inet_network()inet_ntoa()ioctl()listen()maxdesc()ntohl()ntohs()Translates host byte order to networkbyte order for a short integer.Constructs an internet address fromcharacter strings set in standarddotted-decimal notation.Returns the local network portion ofan internet address.Constructs an internet address from anetwork number and a local address.Returns the network portion of theinternet address in network byteorder.Constructs a network number fromcharacter strings set in standarddotted-decimal notation.Returns a pointer to a string indotted-decimal notation.Performs special operations on ssocket descriptor.Indicates that a stream socket is readyfor a connection request from aforeign host.Allows socket numbers to extendbeyond default range of 0-49.Translates network byte order to hostbyte order for a long integer.Translates network byte order to hostbyte order for a short integer.51525253535354545657585920 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Table 2. C Socket <strong>Reference</strong> (continued)Socket() Call Description Pageread()Reads a set number of bytes into a 59buffer.readv()Obtains data from a socket and reads 60this data into specified buffers.recv()Receives messages from a connected 61socket.recvfrom()Receives messages from a datagramsocket, regardless of its connectionstatus.62recvmsg()select()selectex()send()sendmsg()sendto()Receives messages on a socket withthe descriptor s.Detects whether read is possible on agroup of sockets.Monitors activity on a set of differentsockets.Transmits messages to a connectedsocket.Sends messages on a socket withdescriptor s in an array of headers.Transmits messages to a datagramsocket, regardless of its connectionstatus.C Socket <strong>Reference</strong>sethostent()Opens the HOSTS SITEINFO file at 72the beginning.setnetent()Opens the HOSTS SITEINFO file at 75the beginning.setprotoent()Opens the ETC PROTO file at the75beginning.setservent()Opens the ETC SERVICES file at the 75beginning.setsockopt()Sets options associated with a socket 76in the AF_INET domain.shutdown()Shuts down all or part of a81full-duplex connection.socket() Requests that a socket be created. 82takesocket()Acquires a socket from another85application.write()Writes a set number of bytes from a 87buffer to a socket.writev()Writes data in the buffers specified byan array of iovec structures.88636467686970C Socket CallsThis section provides the syntax, parameters, and other appropriate information foreach C socket call supported by <strong>TCP</strong>/<strong>IP</strong>.Chapter 2. C Sockets Application Program Interface 21


accept()accept()#include #include int accept(s, name, namelen)int s;struct sockaddr *name;int *namelen;ParametersnamenamelenDescriptionSpecifies the socket descriptor.Specifies the socket address of the connecting client that is filled byaccept() before it returns. The format of name is determined by thedomain in which the client resides. This parameter can be NULL ifthe caller is not interested in the client address.Initially points to an integer that contains the size in bytes of thestorage pointed to by name. On return, that integer contains thesize of the data returned in the storage pointed to by name. Ifnameis NULL, then namelen is ignored and can be NULL.Description: The accept() call is used by a server to accept a connection requestfrom a client. The call accepts the first connection on its queue of pendingconnections. The accept() call creates a new socket descriptor with the sameproperties as s and returns it to the caller. If the queue has no pending connectionrequests, accept() blocks the caller unless s is in nonblocking mode. If noconnection requests are queued and s is in nonblocking mode, accept() returns −1and sets errno to EWOULDBLOCK. The new socket descriptor cannot be used toaccept new connections. The original socket, s, remains available to accept moreconnection requests.The s parameter is a stream socket descriptor created with the socket() call. It isusually bound to an address with the bind() call, and is made capable of acceptingconnections with the listen() call. The listen() call marks the socket as one thataccepts connections and allocates a queue to hold pending connection requests.The listen() call allows the caller to place an upper boundary on the size of thequeue.The name parameter is a pointer to a buffer into which the connection requester’saddress is placed. The name parameter is optional and can be set to be the NULLpointer. If set to NULL, the requester’s address is not copied into the buffer. Theexact format of name depends on the addressing domain from which thecommunication request originated. For example, if the connection requestoriginated in the AF_INET domain, name points to a sockaddr_in structure asdefined in the header file IN.H. The namelen parameter is used only if name is notNULL. Before calling accept(), you must set the integer pointed to by namelen tothe size of the buffer, in bytes, pointed to by name. On successful return, theinteger pointed to by namelen contains the actual number of bytes copied into thebuffer. If the buffer is not large enough to hold the address, up to namelen bytes ofthe requester’s address are copied.This call is used only with SOCK_STREAM sockets. You cannot screen requesterswithout calling accept(). The application cannot tell the system from which22 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


accept()requesters it accepts connections from. The caller can, however, choose to close aconnection immediately after discovering the identity of the requester.A socket can be checked for incoming connection requests using the select() call.||Return Values: A non-negative socket descriptor indicates success; the value −1indicates an error. The value of errno indicates the specific error.Errno ValueDescriptionEBADFIndicates that the s parameter is not a valid socketdescriptor.EINVALIndicates that the listen() was not called for sockets.EMFILEIndicates that the socket descriptor table is alreadyfull.ENOBUFSIndicates that there is insufficient buffer spaceavailable to create the new socket.EOPNOTSUPPIndicates that the s parameter is not of typeSOCK_STREAM.EFAULTIndicates that the use of name and namelen wouldresult in an attempt to copy the address into aportion of the caller’s virtual storage into whichinformation cannot be written.EWOULDBLOCKIndicates that the s parameter is in nonblockingmode and no connections are on the queue.E<strong>IBM</strong>IUCVERRIndicates that an IUCV error occurred.Examples: The following are two examples of the accept() call. In the first, thecaller wishes to have the requester’s address returned. In the second, the callerdoes not wish to have the requester’s address returned.int clientsocket;int s;struct sockaddr clientaddress;int addrlen;int accept(int s, struct sockaddr *addr, int *addrlen);/* socket(), bind(), and listen() have been called *//* EXAMPLE 1: I want the address now */addrlen = sizeof(clientaddress);clientsocket = accept(s, &clientaddress, &addrlen);/* EXAMPLE 2: I can get the address later using getpeername() */addrlen = 0;clientsocket = accept(s, (struct sockaddr *) 0, (int *) 0);See Also: bind(), connect(), getpeername(), listen(), socket().bind()Chapter 2. C Sockets Application Program Interface 23


ind()#include #include int bind(s, name, namelen)int s;struct sockaddr *name;int namelen;ParametersnamenamelenDescriptionSpecifies the socket descriptor returned by a previous socket() call.Points to a sockaddr structure containing the name that is to bebound to s.Specifies the size of name in bytes.Description: The bind() call binds a unique local name to the socket withdescriptor s. After calling socket(), a descriptor does not have a name associatedwith it. However, it does belong to a particular addressing family as specifiedwhen socket() is called. The exact format of a name depends on the addressingfamily. The bind() procedure also allows servers to specify from which networkinterfaces they wish to receive UDP packets and <strong>TCP</strong> connection requests.The s parameter is a socket descriptor of any type created by calling socket().The name parameter is a pointer to a buffer containing the name to be bound to s.The namelen parameter is the size, in bytes, of the buffer pointed to by name.Socket Descriptor Created in the AF_INET Domain: If the socket descriptor swas created in the AF_INET domain, then the format of the name buffer isexpected to be sockaddr_in as defined in the header file IN.H:struct in_addr{unsigned long s_addr;};struct sockaddr_in{short sin_family;unsigned short sin_port;struct in_addr sin_addr;char sin_zero[8];};The sin_family field must be set to AF_INET.The sin_port field is set to the port to which the application must bind. It must bespecified in network byte order. If sin_port is set to 0, the caller leaves it to thesystem to assign an available port. When the bind() call returns, this field is set tothe port chosen by the system. Alternatively, the application can call getsockname()to discover the port number assigned.The sin_addr.s_addr field is set to the internet address and must be specified innetwork byte order. On hosts with more than one network interface (calledmulti-homed hosts), a caller can select the interface with which it is to bind.Subsequently, only UDP packets and <strong>TCP</strong> connection requests from this interface(which match the bound name) are routed to the application. If this field is set tothe constant INADDR_ANY, as defined in the header file IN.H, the caller is leavingthe address unspecified and requesting that the socket be bound to all networkinterfaces on the host. Subsequently, UDP packets and <strong>TCP</strong> connections from all24 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


interfaces (which match the bound name) are routed to the application. Thisbecomes important when a server offers a service to multiple networks. By leavingthe address unspecified, the server can accept all UDP packets and <strong>TCP</strong> connectionrequests made for its port, regardless of the network interface on which therequests arrived.The sin_zero field is not used and must be set to all zeroes.Socket Descriptor Created in the AF_IUCV Domain: If the socket descriptor s iscreated in the AF_IUCV domain, the format of the name buffer is expected to besockaddr_iucv, as defined in the header file SAIUCV.H.struct sockaddr_iucv{short siucv_family; /* addressing family */unsigned short siucv_port; /* port number */unsigned long siucv_addr; /* address */unsigned char siucv_nodeid[8]; /* nodeid to connect to */unsigned char siucv_userid[8]; /* userid to connect to */unsigned char siucv_name[8]; /* iucvname for connect */};The siucv_family field must be set to AF_IUCV.The siucv_port, siucv_addr, and siucv_nodeid fields are reserved for future use. Thesiucv_port and siucv_addr fields must be zeroed.The siucv_nodeid field must be set to exactly eight blank characters.The siucv_userid field is set to the <strong>VM</strong> user ID of the application making the bindcall. This field must be eight characters long, padded with blanks to the right. Itcannot contain the NULL character.The siucv_name field is set to the application name by which the socket is to beknown. It must be unique, because only one socket can be bound to a given name.The recommended form of the name contains eight characters, padded with blanksto the right. The eight characters for a connect() call executed by a client mustexactly match the eight characters passed in the bind() call executed by the server.Note: Internally, dynamic names are built using hexadecimal character stringsrepresenting the internal memory address of the socket. An example of thisis when an application calls connect and specifies an unbound socket. Youshould choose names that contain at least one non-hexadecimal character toprevent potential conflicts. Hexadecimal characters include 0—9, and a—f.Uppercase A—F are considered nondecimal and can be used by the user inbuilding dynamic names.Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.Errno ValueDescriptionEBADFEADDRNOTAVAILEFAULTbind()Indicates that the s parameter is not a valid socketdescriptor.Indicates that the address specified is not valid onthis host. For example, if the internet address doesnot specify a valid network interface.Using name and namelen would result in an attemptChapter 2. C Sockets Application Program Interface 25


ind()EAFNOSUPPORTEADDRINUSEEINVALto copy the address into a non-writable portion ofthe caller’s virtual storage.Indicates that the address family is not supported(it is not AF_IUCV or AF_INET).Indicates that the address is already in use. See theSO_REUSEADDR option described under“getsockopt()” on page 45 and theSO_REUSEADDR described under the“setsockopt()” on page 76.Indicates that the socket is already bound to anaddress. For example, trying to bind a name to asocket that is in the connected state. If you areusing sockets in the AF_IUCV domain, this erroralso occurs if NULL characters appear in thesiucv_nodeid or siucv_user_id fields. This value isalso returned if namelen is not the expected length.Examples: The following are examples of the bind() call. The internet address andport must be in network byte order. To put the port into network byte order, autility routine, htons(), is called to convert a short integer from host byte order tonetwork byte order. The address field is set using another utility routine,inet_addr(), which takes a character string representing the dotted-decimal addressof an interface and returns the binary internet address representation in networkbyte order. Finally, you should zero the structure before using it to ensure that thename requested does not set any reserved fields. For examples of how a clientmight connect to servers, see “connect()” on page 27.AF_INET Domain Example: The following example illustrates the bind() callbinding to interfaces in the AF_INET domain.int rc;int s;struct sockaddr_in myname;struct sockaddr_iucv myvmname;int bind(int s, struct sockaddr *name, int namelen);/* Bind to a specific interface in the internet domain *//* make sure the sin_zero field is cleared */memset(&myname, 0, sizeof(myname));myname.sin_family = AF_INET;myname.sin_addr.s_addr = inet_addr(“129.5.24.1”); /* specific interface */myname.sin_port = htons(1024);.rc = bind(s, (struct sockaddr *) &myname, sizeof(myname));/* Bind to all network interfaces in the internet domain *//* make sure the sin_zero field is cleared */memset(&myname, 0, sizeof(myname));myname.sin_family = AF_INET;myname.sin_addr.s_addr = INADDR_ANY; /* specific interface */myname.sin_port = htons(1024);.rc = bind(s, (struct sockaddr *) &myname, sizeof(myname));/* Bind to a specific interface in the internet domain.Let the system choose a port *//* make sure the sin_zero field is cleared */memset(&myname, 0, sizeof(myname));myname.sin_family = AF_INET;myname.sin_addr.s_addr = inet_addr(“129.5.24.1”); /* specific interface */myname.sin_port.= 0;26 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


.rc = bind(s, (struct sockaddr *) &myname, sizeof(myname));bind()close()AF_IUCV Domain Example: The following example illustrates the bind() callbinding to interfaces in the AF_IUCV domain./* Bind to a name in the IUCV domain *//* make sure the siucv_addr, siucv_port fields are zeroed and thesiucv_nodeid fields is set to blanks */memset(&myvmname, 0, sizeof(myvmname));strncpy(myvmname.siucv_nodeid, “ ”, 8);strncpy(myvmname.siucv_userid, “”, 8);strncpy(myvmname.siucv_name, “”, 8);myvmname.siucv_family = AF_IUCV;strncpy(myvmname.siucv_userid, “<strong>VM</strong>USER1”, 7);strncpy(myvmname.siucv_name, “APPL”, 4);.rc = bind(s, (struct sockaddr *) &myname, sizeof(myname));The binding of a stream socket is not complete until a successful call to bind(),listen(), or connect() is made. Applications using stream sockets should check thereturn values of bind(), listen(), and connect() before using any function thatrequires a bound stream socket.See Also: connect(), gethostbyname(), getsockname(), htons(), inet_addr(), listen(),socket().int close(s)int s;ParametersDescriptionSpecifies the descriptor of the socket to be closed.connect()Description: The close() call shuts down the socket associated with the socketdescriptor s, and frees resources allocated to the socket. If s refers to an open <strong>TCP</strong>connection, the connection is closed. If a stream socket is closed when there isinput data queued, the <strong>TCP</strong> connection is reset rather than being cleanly closed.Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.Errno Value DescriptionEBADF Indicates that the s parameter is not a valid socket descriptor.See Also: accept(), getsockopt(), setsockopt(), socket().Chapter 2. C Sockets Application Program Interface 27


connect()#include #include int connect(s, name, namelen)int s;struct sockaddr *name;int namelen;ParametersnamenamelenDescriptionSpecifies the socket descriptor.Points to a socket address structure containing the address of thesocket to which a connection is attempted.Specifies the size of the socket address pointed to by name in bytes.Description: For stream sockets, the connect() call attempts to establish aconnection between two sockets. For UDP sockets, the connect() call specifies thepeer for a socket. The s parameter is the socket used to originate the connectionrequest. The connect() call performs two tasks when called for a stream socket.First, it completes the binding necessary for a stream socket (in case it has not beenpreviously bound using the bind() call). Second, it attempts to make a connectionto another socket.The connect() call on a stream socket is used by the client application to establish aconnection to a server. The server must have a passive open pending. If the serveris using sockets, this means the server must successfully call bind() and listen()before a connection can be accepted by the server with accept(). Otherwise,connect() returns −1 and errno is set to ECONNREFUSED.If s is in blocking mode, the connect() call blocks the caller until the connection isset up, or until an error is received. If the socket is in nonblocking mode thenconnect() returns −1 with errno set to EINPROGRESS if the connection can beinitiated (no other errors occurred). The caller can test the completion of theconnection setup by calling select() and testing for the ability to write to the socket.When called for a datagram or raw socket, connect() specifies the peer with whichthis socket is associated. This gives the application the ability to use data transfercalls reserved for sockets that are in the connected state. In this case, read(), write(),readv(), writev(), send(), recv() are then available in addition to sendto(),recvfrom(), sendmsg(), recvmsg(). Stream sockets can call connect() only once,however, datagram sockets can call connect() multiple times to change theirassociation. Datagram sockets can dissolve their association by connecting to aninvalid address such as the NULL address (all fields zeroed).The name parameter is a pointer to a buffer containing the name of the peer towhich the application needs to connect. The namelen parameter is the size, in bytes,of the buffer pointed to by name.Servers in the AF_INET Domain: If the server is in the AF_INET domain, theformat of the name buffer is expected to be sockaddr_in, as defined in the headerfile IN.H.struct in_addr{unsigned long s_addr;};struct sockaddr_in{28 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


connect()};short sin_family;unsigned short sin_port;struct in_addr sin_addr;char sin_zero[8];The sin_family field must be set to AF_INET. The sin_port field is set to the port towhich the server is bound. It must be specified in network byte order. The sin_zerofield is not used and must be set to all zeroes.Servers in the AF_IUCV Domain: If the server is in the AF_IUCV domain, theformat of the name buffer is expected to be sockaddr_iucv, as defined in the headerfile SAIUCV.H.struct sockaddr_iucv{short siucv_family; /* addressing family */unsigned short siucv_port; /* port number */unsigned long siucv_addr; /* address */unsigned char siucv_nodeid[8]; /* nodeid to connect to */unsigned char siucv_userid[8]; /* userid to connect to */unsigned char siucv_name[8]; /* iucvname for connect */};The siucv_family field must be set to AF_IUCV. The siucv_port, siucv_addr, andsiucv_nodeid fields are reserved for future use. The siucv_port and siucv_addr fieldsmust be zeroed. The siucv_nodeid field must be set to exactly 8 blank characters.The siucv_userid field is set to the <strong>VM</strong> user ID of the application to which theapplication is requesting a connection. This field must be 8 characters long, paddedwith blanks to the right. It cannot contain the NULL character. The siucv_name fieldis set to the application name by which the server socket is known. The name mustexactly match the 8 characters passed in the bind() call executed by the server.Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.Errno ValueDescriptionEADDRNOTAVAILEAFNOSUPPORTEALREADYEBADFECONNREFUSEDEFAULTEINPROGRESSIndicates that the calling host cannot reach thespecified destination.Indicates that the address family is not supported.Indicates that the socket s is marked nonblocking,and a previous connection attempt has notcompleted.Indicates that the s parameter is not a valid socketdescriptor.Indicates that the connection request was rejectedby the destination host.Indicates that the use of name and namelen wouldresult in an attempt to copy the address into aportion of the caller’s virtual storage to which datacannot be written.Indicates that the socket s is marked nonblocking,and the connection cannot be completedimmediately. The EINPROGRESS value does notindicate an error condition.Chapter 2. C Sockets Application Program Interface 29


connect()EINVALEISCONNENETUNREACHETIMEDOUTIndicates that the namelen parameter is not a validlength.Indicates that the socket s is already connected.Indicates that the network cannot be reached fromthis host.Indicates that the connection establishment timedout before a connection was made.Examples: The following are examples of the connect() call. The internet addressand port must be in network byte order. To put the port into network byte order autility routine, htons(), is called to convert a short integer from host byte order tonetwork byte order. The address field is set using another utility routine,inet_addr(), which takes a character string representing the dotted-decimal addressof an interface and returns the binary internet address representation in networkbyte order. Finally, note that it is a good idea to zero the structure before using itto ensure that the name requested does not set any reserved fields. These examplescould be used to connect to the servers shown in the examples listed with the call,“bind()” on page 23.int s;struct sockaddr_in servername;struct sockaddr_iucv vmservername;int rc;int connect(int s, struct sockaddr *name, int namelen);/* Connect to server bound to a specific interface in the internet domain *//* make sure the sin_zero field is cleared */memset(&servername, 0, sizeof(servername));servername.sin_family = AF_INET;servername.sin_addr.s_addr = inet_addr(“129.5.24.1”); /* specific interface */servername.sin_port = htons(1024);.rc = connect(s, (struct sockaddr *) &servername, sizeof(servername));/* Connect to a server bound to a name in the IUCV domain *//* make sure the siucv_addr, siucv_port, siucv_nodeid fields are cleared*/memset(&vmservername, 0, sizeof(vmservername));vmservername.siucv_family = AF_IUCV;strncpy(vmservername.siucv_nodeid, “ ”,8);/* The field is eight positions padded to the right with blanks */strncpy(vmservername.siucv_userid, “<strong>VM</strong>USER1 ”, 8);strncpy(vmservername.siucv_name, “APPL ”, 8);.rc = connect(s, (struct sockaddr *) &vmservername, sizeof(vmservername));endhostent()See Also: accept(), bind(), htons(), inet_addr(), listen(), select(), selectex(), socket().void endhostent()The endhostent() call has no parameters.Description: The endhostent() call closes the HOSTS SITEINFO and HOSTSADDRINFO files. The HOSTS SITEINFO and HOSTS ADDRINFO files containinformation about known hosts.30 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


endnetent()The endhostent() call is available only if RESOLVE_VIA_LOOKUP is definedbefore the MANIFEST.H header file is included.See Also: gethostbyaddr(), gethostbyname(), gethostent(), sethostent().endhostent()void endnetent()The endnetent() call has no parameters.Description: The endnetent() call closes the HOSTS SITEINFO file. The HOSTSSITEINFO file contains information about known networks.See Also: getnetbyaddr(), getnetbyname(), getnetent(), setnetent().endprotoent()endservent()void endprotoent()The endprotoent() call has no parameters.Description: The endprotoent() call closes the ETC PROTO file.See Also: getprotobyname(), getprotoent(), setprotoent().fcntl()void endservent()The endservent() call has no parameters.Description: The endservent() call closes the ETC SERVICES file.See Also: getservbyname(), getservbyport(), getservent(), setservent().#include #include int fcntl(s, cmd, data)int s;int cmd;int data;ParameterscmddataDescriptionSpecifies the socket descriptor.Specifies the command to perform.Specifies the data associated with the cmd parameter.Chapter 2. C Sockets Application Program Interface 31


fcntl()Description: The operating characteristics of sockets can be controlled with fcntl()requests. The operations to be controlled are determined by the cmd parameter. Thedata parameter is a variable with a meaning that depends on the value of the cmdparameter.The following are valid fcntl() commands:Command DescriptionF_SETFL Sets the status flags of socket s. One flag, FNDELAY, can be set.v Setting the FNDELAY flag marks s as being in nonblockingmode. If data is not present on calls that can block, such asread(), readv(), recv(), the call returns −1 and errno is set toEWOULDBLOCK.F_GETFL Gets the status flags of socket s. One flag, FNDELAY, can bequeried.v The FNDELAY flag marks s as being in nonblocking mode. Ifdata is not present on calls that can block, such as read(),readv(), recv(), the call returns with −1 and errno is set toEWOULDBLOCK.Return Values: For the F_GETFL command, the return value is the flags, set as abit mask. For the F_SETFL command, the value 0 indicates success; the value −1indicates an error. The value of errno indicates the specific error.Errno Value DescriptionEBADF Indicates that the s parameter is not a valid socket descriptor.EINVAL Indicates that the data parameter is not a valid flag.Examples:getclientid()The following are examples of the fcntl() call.int s;int rc;int flags;./* Place the socket into nonblocking mode */rc = fcntl(s, F_SETFL, FNDELAY);/* See if asynchronous notification is set */flags = fcntl(s, F_GETFL, 0);if (flags & FNDELAY)/* it is set */else/* it is not */See Also: fcntl(), ioctl(), getsockopt(), setsockopt(), socket().#include #include int getclientid(domain, clientid)int domain,struct clientid *clientid;ParameterdomainDescriptionSpecifies the address family domain and must be AF_INET.32 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


getclientid()clientidPoints to a clientid structure to be filled.Description: The getclientid() call returns the identifier by which the callingprogram is known to the <strong>TCP</strong><strong>IP</strong> virtual machine. The clientid is used in thegivesocket() and takesocket() calls.Return Values: The value 0 indicates success. The value −1 indicates an error. Thevalue of errno indicates the specific error.Errno Value DescriptionEFAULT Indicates that using the clientid parameter as specified would resultin an attempt to access storage outside the caller’s virtual storage,or storage not modifiable by the caller.EPFNOSUPPORTIndicates that the domain is not AF_INET.See Also: givesocket(), takesocket().getdtablesize()int getdtablesize()The getdtablesize() call has no parameters.Description: The <strong>TCP</strong><strong>IP</strong> virtual machine reserves a fixed-size table for eachmachine using sockets. The size of this table is the number of sockets a machinecan allocate simultaneously. The getdtablesize() function returns the size of thistable.To increase the table size, use maxdesc(). After calling maxdesc(), always usegetdtablesize() to verify that the table was changed.See Also: maxdesc().gethostbyaddr()#include struct hostent *gethostbyaddr(addr, addrlen, domain)char *addr;int addrlen;int domain;ParameteraddraddrlendomainDescriptionPoints to a structure containing the address of the socket. ForAF_INET, addr is a pointer to an in_addr structure.Specifies the size of addr in bytes.Specifies the address domain supported (AF_INET).Description: The gethostbyaddr() call tries to resolve the host name through aname server, if one is present. If a name server is not present, gethostbyaddr()Chapter 2. C Sockets Application Program Interface 33


gethostbyaddr()searches the HOSTS ADDRINFO file until a matching host address is found or anEOF marker is reached. These files are described in <strong>TCP</strong>/<strong>IP</strong> Planning andCustomization.The gethostbyaddr() call returns a pointer to a hostent structure for the hostaddress specified on the call.If RESOLVE_VIA_LOOKUP is defined before including the MANIFEST.H headerfile, gethostbyaddr() uses only the HOSTS ADDRINFO file for resolution.Otherwise, the name server is required.Note: The HOSTS ADDRINFO file is created when MAKESITE is run against theHOSTS LOCAL file. These files are described in the <strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong>: Planningand Customization.The NETDB.H header file defines the hostent structure, and contains the followingelements:Element Descriptionh_name Indicates the official name of the host.h_aliases Indicates a zero-terminated array of alternative names for the host.h_addrtypeh_lengthh_addrIndicates the type of address returned; currently, always set toAF_INET.Indicates the length of the address in bytes.Indicates a pointer to a pointer to a string of bytes of length hlength, which is the network address number of the host.Return Values: The return value points to static data that is overwritten bysubsequent calls. A pointer to a hostent structure indicates success. A NULL pointerindicates an error or end-of-file.See Also: gethostbyname(), gethostent(), sethostent().gethostbyname()#include struct hostent *gethostbyname(name)char *name;ParameternameDescriptionSpecifies the name of the host being queried.Description: The gethostbyname() call tries to resolve the host name through aname server, if one is present. If a name server is not present, gethostbyname()searches the HOSTS SITEINFO file until a matching host name is found or an EOFmarker is reached.The gethostbyname() call returns a pointer to a hostent structure for the host namespecified on the call.If RESOLVE_VIA_LOOKUP is defined before including the MANIFEST.H headerfile, gethostbyname() uses only the HOSTS ADDRINFO file for resolution.34 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Note: The HOSTS ADDRINFO file is created when MAKESITE is run against theHOSTS LOCAL file. These files are described in <strong>TCP</strong>/<strong>IP</strong> Planning andCustomization.The NETDB.H header file defines the hostent structure and contains the followingelements:Element Descriptionh_name Indicates the official name of the host.h_aliases Indicates a zero-terminated array of alternative names for the host.h_addrtypeh_lengthh_addrgethostent()Indicates the type of address returned; currently, it is always set toAF_INET.Indicates the length of the address in bytes.Indicates a pointer to a pointer to a string of bytes of length hlength, which is the network address number of the host.Return Values: The return value points to static data that is overwritten bysubsequent calls. A pointer to a hostent structure indicates success. A NULL pointerindicates an error or end-of-file.See Also: gethostbyaddr(), gethostent(), sethostent().gethostbyname()#include struct hostent *gethostent()The gethostent() call has no parameters.Description: The gethostent() call reads the next line of the HOSTS SITEINFO file.The gethostent() call returns a pointer to the next entry in the HOSTS SITEINFOfile. gethostent() uses HOSTS ADDRINFO to get aliases.gethostent() is available only if RESOLVE_VIA_LOOKUP is defined before theMANIFEST.H header file is included. The NETDB.H header file defines the hostentstructure, and contains the following elements:Element Descriptionh_name Indicates the official name of the host.h_aliases Indicates a zero-terminated array of alternative names for host.h_addrtypeh_lengthh_addrIndicates the type of address returned; currently, always set toAF_INET.Indicates the length of the address in bytes.Indicates a pointer to a pointer to a string of bytes of length hlength, which is the network address number of the host.Return Values: The return value points to static data that is overwritten bysubsequent calls. A pointer to a hostent structure indicates success. A NULL pointerindicates an error or end-of-file.Chapter 2. C Sockets Application Program Interface 35


gethostid()gethostid()See Also: gethostbyaddr(), gethostbyname(), sethostent().#include unsigned long gethostid()The gethostid() call has no parameters.Description: The gethostid() call gets the unique 32-bit identifier for the currenthost. This value is the default home internet address.Return Values: The gethostid() call returns the 32-bit identifier of the current host,which should be unique across all hosts.gethostname()int gethostname(name, namelen)char *name;int namelen;ParameternamenamelenDescriptionSpecifies the character array to be filled with the host name.Specifies the length of name.Description: The gethostname() call returns the name of the host processor onwhich the program is running. Up to namelen characters are copied into the namearray. The returned name is NULL terminated unless there is insufficient room inthe name array.Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.See Also: gethostbyname().getibmsockopt()Like getsockopt(), the getibmsockopt() gets the options associated with a socket inthe AF_INET domain. This call is for options specific to the <strong>IBM</strong> implementation ofsockets. Currently, only the SOL_SOCKET level and the socket optionsSO_BULKMODE and SO_IGNOREINCOMINGPUSH are supported.Use getibmsockopt() with the socket option SO_BULKMODE to test whether theUDP socket s is in bulk mode. The bulkmode socket option enables an applicationto queue multiple datagrams, sending all of the datagrams in one send. Thisreduces the CPU consumption for each datagram.This call can be used only in the AF_INET domain.36 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


getibmsockopt()#include #include int getibmsockopt(int s, int level, int optname, char *optval, int *optlen)ParametersleveloptnameoptvaloptlenDescriptionThe socket descriptor.The level for which the option is set.The name of a specified socket option.The pointer to option data.The pointer to the length of the option data.For SO_BULKMODE, optval should point to an ibm_bulkmode_struct, which isdefined in SOCKET.H. The ibm_bulkmode_struct contains the following fields:ElementDescriptionb_onoffb_max_receive_queue_sizeb_max_send_queue_sizeb_teststorb_max_send_queue_size_availb_num_IUCVs_sentb_num_IUCVs_received1 means bulk mode is on; 0 means bulk mode isoff.The maximum receiving queue size in bytes.The maximum sending queue size in bytes.If this element is nonzero, the address of themessage buffer and the message buffer itself ischecked for addressability during each socket call.errno is set to EFAULT if there is an addressingexception. If this element is zero, no checking isperformed.The maximum send queue size in bytes that can beset with setibmsockopt().The number of actual IUCVs issued in sendingdatagrams to <strong>TCP</strong><strong>IP</strong>.The number of actual IUCVs issued in receivingdatagrams from <strong>TCP</strong><strong>IP</strong>.The fields b_num_IUCVs_sent and b_num_IUCVs_received represent cumulativetotals for this socket since the time the application was started.For SO_IGNOREINCOMINGPUSH, optval should point to an integer.getibmsockopt() returns 0 in optval if the option is not set, and returns 1 in optvalif the option is set.Example:The following is an example of the getibmsockopt() call.Chapter 2. C Sockets Application Program Interface 37


getibmsockopt()#include #include #include { struct ibm_bulkmode_struct bulkstr;int optlen, rc;optlen = sizeof(bulkstr);rc = getibmsockopt(s, SOL_SOCKET, SO_BULKMODE, (char *), &bulkstr, &optlen);if (rc < 0){ tcperror("on getibmsockopt()");exit(1);}fprintf(stream,"%d byte buffer available for outbound queue.\n",bulkstr.b_max_send_queue_size_avail);}Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.Errno ValueDescriptionEBADFThe s parameter is not a valid socket descriptor.EFAULTUsing optval and optlen parameters would resultin an attempt to access storage outside the caller’saddress space.E<strong>IBM</strong>IUCVERRAn IUCV error occurred.ENOPROTOOPTThe optname parameter is unrecognized, or thelevel parameter is not SOL_SOCKET.Related Calls:ibmsflush(), setibmsockopt(), getsockopt().getnetbyaddr()#include struct netent *getnetbyaddr(net, type)unsigned long net;int type;ParameternettypeDescriptionSpecifies the network address.Specifies the address domain supported (AF_INET).Description: The getnetbyaddr() call searches the HOSTS ADDRINFO file for thespecified network address.Note: HOSTS LOCAL, HOSTS ADDRINFO, and HOSTS SITEINFO are describedin <strong>TCP</strong>/<strong>IP</strong> Planning and Customization.The netent structure is defined in the NETDB.H header file and contains thefollowing elements:Element Descriptionn_name Indicates the official name of the network.n_aliasesIndicates an array, terminated with a NULL pointer, of alternativenames for the network.38 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


getnetbyaddr()n_addrtypen_netIndicates the type of network address returned. The call alwayssets this value to AF_INET.Indicates the network number, returned in host byte order.Return Values: The return value points to static data that is overwritten bysubsequent calls. A pointer to a netent structure indicates success. A NULL pointerindicates an error or end-of-file.See Also: endnetent(), getnetbyname(), getnetent(), setnetent().getnetbyname()#include struct netent *getnetbyname(name)char *name;ParameternameDescriptionPoints to a network name.Description: The getnetbyname() call searches the HOSTS ADDRINFO file for thespecified network name.Note: HOSTS LOCAL, HOSTS ADDRINFO, and HOSTS SITEINFO are describedin <strong>TCP</strong>/<strong>IP</strong> Planning and Customization.The getnetbyname() call returns a pointer to a netent structure for the networkname specified on the call.The netent structure is defined in the NETDB.H header file and contains thefollowing elements:Element Descriptionn_name Indicates the official name of the network.n_aliasesn_addrtypen_netIndicates an array, terminated with a NULL pointer, of alternativenames for the network.Indicates the type of network address returned. The call alwayssets this value to AF_INET.Indicates the network number, returned in host byte order.Return Values: The return value points to static data that is overwritten bysubsequent calls. A pointer to a netent structure indicates success. A NULL pointerindicates an error or end-of-file.See Also: endnetent(), getnetbyaddr(), getnetent(), setnetent().Chapter 2. C Sockets Application Program Interface 39


getnetent()getnetent()#include struct netent *getnetent()The getnetent() call has no parameters.Description: The getnetent() call reads the next entry of the HOSTS SITEINFO file.Note: HOSTS LOCAL, HOSTS ADDRINFO, and HOSTS SITEINFO are describedin <strong>TCP</strong>/<strong>IP</strong> Planning and Customization.The netent structure is defined in the NETDB.H header file and contains thefollowing elements:Element Descriptionn_name Indicates the official name of the network.n_aliasesn_addrtypen_netIndicates an array, terminated with a NULL pointer, of alternativenames for the network.Indicates the type of network address being returned. The callalways sets this value to AF_INET.Indicates the network number, returned in host byte order.Return Values: The return value points to static data that is overwritten bysubsequent calls. A pointer to a netent structure indicates success. A NULL pointerindicates an error or end-of-file.See Also: endnetent(), getnetbyaddr(), getnetbyname(), setnetent().getpeername()#include #include int getpeername(s, name, namelen)int s;struct sockaddr *name;int *namelen;ParametersnamenamelenDescriptionSpecifies the socket descriptor.Specifies the internet address of the connected socket that is filledby getpeername() before it returns. The exact format of the nameparameter is determined by the domain in which communicationoccurs.Specifies the size of the address structure pointed to by the nameparameter in bytes.Description: The getpeername() call returns the name of the peer connected tosocket s. The namelen pointer must be initialized to indicate the size of the spacepointed to by name and is set to the number of bytes copied into the space before40 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


the call returns. The size of the peer name is returned in bytes. If the buffer of thelocal host is too small, the peer name is truncated.Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.Errno ValueDescriptionEBADFEFAULTENOTCONNSee Also: accept(), connect(), getsockname(), socket().getprotobyname()getpeername()Indicates that the s parameter is not a valid socketdescriptor.Indicates that using the name and namelenparameters as specified would result in an attemptto access storage outside of the caller’s virtualstorage.Indicates that the socket is not in the connectedstate.#include struct protoent *getprotobyname(name)char *name;ParameternameDescriptionPoints to the specified protocol.Description: The getprotobyname() call searches the ETC PROTO file for thespecified protocol name.The getprotobyname() call returns a pointer to a protoent structure for the networkprotocol specified on the call.The protoent structure is defined in the NETDB.H header file and contains thefollowing elements:Element Descriptionp_name Indicates the official name of the protocol.p_aliasesp_protoIndicates an array, terminated with a NULL pointer, of alternativenames for the protocol.Indicates the protocol number.Return Values: The return value points to static data that is overwritten bysubsequent calls. A pointer to a protoent structure indicates success. A NULLpointer indicates an error or end-of-file.See Also: endprotoent(), getprotobynumber(), getprotoent(), setprotoent().getprotobynumber()Chapter 2. C Sockets Application Program Interface 41


getprotobynumber()#include struct protoent * getprotobynumber(proto)int proto;ParameterprotoDescriptionSpecifies the protocol number.Description: The getprotobynumber() call searches the ETC PROTO file for thespecified protocol number.The getprotobynumber() call returns a pointer to a protoent structure for thenetwork protocol specified on the call.The protoent structure is defined in the NETDB.H header file and contains thefollowing elements:Element Descriptionp_name Indicates the official name of the protocol.p_aliasesp_protoIndicates an array, terminated with a NULL pointer, of alternativenames for the protocol.Indicates the protocol number.Return Values: The return value points to static data that is overwritten bysubsequent calls. A pointer to a protoent structure indicates success. A NULLpointer indicates an error or end-of-file.getprotoent()See Also: endprotoent(), getprotobyname(), getprotoent(), setprotoent().#include struct protoent *getprotoent()The getprotoent() call has no parameters.Description: The getprotoent() call reads the ETC PROTO file.The getprotoent() call returns a pointer to the next entry in the ETC PROTO file.The protoent structure is defined in the NETDB.H header file and contains thefollowing elements:Element Descriptionp_name Indicates the official name of the protocol.p_aliasesp_protoIndicates an array, terminated with a NULL pointer, of alternativenames for the protocol.Indicates the protocol number.Return Values: The return value points to static data that is overwritten bysubsequent calls. A pointer to a protoent structure indicates success. A NULLpointer indicates an error or end-of-file.42 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


See Also: endprotoent(), getprotobyname(), getprotobynumber(), setprotoent().getservbyname()getservbyname()#include struct servent *getservbyname(name, proto)char *name;char *proto;ParameternameprotoDescriptionPoints to the specified service name.Points to the specified protocol.Description: The getservbyname() call searches the ETC SERVICES file for thespecified service name. Searches for a service name must match the protocol, if aprotocol is stated.The getservbyname() call returns a pointer to a servent structure for the networkservice specified on the call.The servent structure is defined in the NETDB.H header file and contains thefollowing elements:Element Descriptions_name Indicates the official name of the service.s_aliasess_ports_protoIndicates an array, terminated with a NULL pointer, of alternativenames for the service.Indicates the port number of the service.Indicates the required protocol to contact the service.Return Values: The return value points to static data that is overwritten bysubsequent calls. A pointer to a servent structure indicates success. A NULL pointerindicates an error or end-of-file.See Also: endservent(), getservbyport(), getservent(), setservent().getservbyport()#include struct servent *getservbyport(port, proto)int port;char *proto;ParameterportprotoDescriptionSpecifies the port.Points to the specified protocol.Description: The getservbyport() call searches the ETC SERVICES file for thespecified port number. Searches for a port number must match the protocol if aprotocol is stated.Chapter 2. C Sockets Application Program Interface 43


getservbyport()The getservbyport() call returns a pointer to a servent structure for the port numberspecified on the call.The servent structure is defined in the NETDB.H header file and contains thefollowing elements:Element Descriptions_name Specifies the official name of the service.s_aliasess_ports_protogetservent()Indicates an array, terminated with a NULL pointer, of alternativenames for the service.Specifies the port number of the service.Specifies the protocol required to contact the service.Return Values: The return value points to static data that is overwritten bysubsequent calls. A pointer to a servent structure indicates success. A NULLpointer indicates an error or end-of-file.See Also: endservent(), getservbyname(), getservent(), setservent().#include struct servent *getservent()The getservent() call has no parameters.Description: The getservent() call reads the next line of the ETC SERVICES file.The getservent() call returns a pointer to the next entry in the ETC SERVICES file.The servent structure is defined in the NETDB.H header file and contains thefollowing elements:Element Descriptions_name Specifies the official name of the service.s_aliasess_ports_protoIndicates an array, terminated with a NULL pointer, of alternativenames for the service.Specifies the port number of the service.Specifies the required protocol to contact the service.Return Values: The return value points to static data that is overwritten bysubsequent calls. A pointer to a servent structure indicates success. A NULL pointerindicates an error or end-of-file.See Also: endservent(), getservbyname(), getservbyport(), setservent().getsockname()44 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


getsockname()#include #include int getsockname(s, name, namelen)int s;struct sockaddr *name;int *namelen;ParametersnamenamelenDescriptionSpecifies the socket descriptor.Specifies the address of the buffer into which getsockname() copiesthe name of s.Initially points to an integer that contains the size in bytes of thestorage pointed to by name. Upon return, this integer contains thesize of the data returned in the storage pointed to by name.Description: The getsockname() call stores the current name for the socketspecified by the s parameter into the structure pointed to by the name parameter. Itreturns the address to the socket that has been bound. If the socket is not bound toan address, the call returns with the family set and the rest of the structure set tozero. For example, an inbound socket in the internet domain would cause thename to point to a sockaddr_in structure with the sin_family field set to AF_INETand all other fields zeroed.Stream sockets are not assigned a name, until after a successful call to eitherbind(), connect(), or accept().The getsockname() call is often used to discover the port assigned to a socket afterthe socket has been implicitly bound to a port. For example, an application can callconnect() without previously calling bind(). In this case, the connect() callcompletes the binding necessary by assigning a port to the socket. This assignmentcan be discovered with a call to getsockname().Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.Errno Value DescriptionEBADF Indicates that the s parameter is not a valid socket descriptor.EFAULTgetsockopt()Using the name and namelen parameters as specified would resultin an attempt to access storage outside of the caller’s virtualstorage.See Also: accept(), bind(), connect(), getpeername(), socket().Chapter 2. C Sockets Application Program Interface 45


||||||||||||||getsockopt()#include #include int getsockopt(s, level, optname, optval, optlen)int s;int level;int optname;char *optval;int *optlen;ParametersleveloptnameoptvaloptlenDescriptionSpecifies the socket descriptor.Specifies the level for which the option is set. Only SOL_SOCKETand <strong>IP</strong>PROTO_<strong>IP</strong> are supported.Specifies the name of a specified socket option.Points to option data.Points to the length of the option data.Description: The getsockopt() call gets options associated with a socket. It can becalled only for sockets in the AF_INET domain. This call is not supported in theAF_IUCV domain. Options can exist at multiple protocol levels; they are alwayspresent at the highest socket level.When manipulating socket options, you must specify the level at which the optionresides and the name of the option. To manipulate options at the socket level or <strong>IP</strong>level, the level parameter must be set to SOL_SOCKET or <strong>IP</strong>PROTO_<strong>IP</strong>, as definedin SOCKET.H. To manipulate options at any other level, such as the <strong>TCP</strong> or <strong>IP</strong>level, supply the appropriate protocol number for the protocol controlling theoption. Currently, only the SOL_SOCKET and <strong>IP</strong>PROTO_<strong>IP</strong> levels are supported.The getprotobyname() call can be used to return the protocol number for a namedprotocol.The optval and optlen parameters are used to return data used by the particular getcommand. The optval parameter points to a buffer that is to receive the datarequested by the get command. The optlen parameter points to the size of thebuffer pointed to by the optval parameter. It must be initially set to the size of thebuffer before calling getsockopt(). On return it is set to the actual size of the datareturned.All of the socket level options except SO_LINGER expect optval to point to aninteger and optlen to be set to the size of an integer. When the integer is nonzero,the option is enabled. When it is zero, the option is disabled. The SO_LINGERoption expects optval to point to a linger structure as defined in SOCKET.H. Thisstructure is defined in the following example:struct linger{};int l_onoff; /* option on/off */int l_linger; /* linger time */The l_onoff field is set to zero if the SO_LINGER option is being disabled. Anonzero value enables the option. The l_linger field specifies the amount of timeto linger on close.The following options are recognized at the <strong>IP</strong> level (<strong>IP</strong>PROTO_<strong>IP</strong>):46 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


||||||||||||||||||||||Option<strong>IP</strong>_MULTICAST_TTL<strong>IP</strong>_MULTICAST_LOOP<strong>IP</strong>_MULTICAST_IFDescriptiongetsockopt()Returns the <strong>IP</strong> time-to-live of outgoing multicastdatagrams. The TTL value is passed back asu_char. This option is only supported for socketswith an address family of AF_INET and type ofSOCK_DGRAM or SOCK_RAW.Determines whether loopback of outgoingmulticast datagrams is enabled or disabled. Whenloopback is enabled, datagrams sent by this systemshould also be delivered to this system as long as itis a member of the multicast group. The loopbackindicator is passed back as u_char. A value of 0means loopback is disabled; a value of 1 means itis enabled. This option is only supported forsockets with an address family of AF_INET andtype of SOCK_DGRAM or SOCK_RAW.Returns the interface <strong>IP</strong> address used for sendingoutbound multicast datagrams from socketapplications. The <strong>IP</strong> Address is passed back usingstructure in_addr. This option is only supported forsockets with an address family of AF_INET andtype of SOCK_DGRAM or SOCK_RAW.|The following options are recognized at the socket level:OptionDescriptionSO_BROADCASTIndicates the ability to broadcast messages. If thisoption is enabled, it allows the application to sendbroadcast messages over s, if the interface specifiedin the destination supports broadcasting of packets.This option has no meaning for stream sockets.SO_ERRORReturns any pending error on the socket and clearsthe error status. It can be used to check forasynchronous errors on connected datagramsockets or for other asynchronous errors (errorsthat are not returned explicitly by one of the socketcalls).SO_KEEPALIVEToggles the <strong>TCP</strong> keep-alive mechanism for a streamsocket. When activated, the keep-alive mechanismperiodically sends a packet on an otherwise idleconnection. If the remote <strong>TCP</strong> does not respond tothe packet or to retransmissions of the packet, theconnection is terminated with the errorETIMEDOUT.SO_LINGERLingers on close if data is present. When thisoption is enabled and there is unsent data presentwhen close() is called, the calling application isblocked during the close() call until the data istransmitted or the connection has timed out. If thisoption is disabled, the <strong>TCP</strong><strong>IP</strong> virtual machine waitsto try to send the data. Although the data transferis usually successful, it cannot be guaranteed,because the <strong>TCP</strong><strong>IP</strong> virtual machine waits only aChapter 2. C Sockets Application Program Interface 47


getsockopt()SO_OOBINLINESO_REUSEADDRSO_SNDBUFSO_TYPEfinite amount of time trying to send the data. Theclose() call returns without blocking the caller. Thisoption has meaning only for stream sockets.Indicates reception of out-of-band data. When thisoption is enabled, it causes out-of-band data to beplaced in the normal data input queue as it isreceived, making it available to recv(), recvfrom(),and recvmsg() without having to specify theMSG_OOB flag in those calls. When this option isdisabled, it causes out-of-band data to be placed inthe priority data input queue as it is received,making it available to recv(), recvfrom(), andrecvmsg() only by specifying the MSG_OOB flag inthose calls. This option has meaning only forstream sockets.Toggles local address reuse. When enabled, thisoption allows local addresses that are already inuse to be bound. This alters the normal algorithmused in the bind() call. The system checks atconnect time to be sure that no local address andport have the same foreign address and port. Theerror EADDRINUSE is returned if the associationalready exists.Returns the size of the <strong>TCP</strong>/<strong>IP</strong> send buffer inoptval.Returns the type of the socket. On return, theinteger pointed to by optval is set to one ofSOCK_STREAM, SOCK_DGRAM, or SOCK_RAW.||Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.Errno ValueDescriptionEBADFEFAULTE<strong>IBM</strong>IUCVERRENOPROTOOPTEOPNOTSUPPIndicates that the s parameter is not a valid socketdescriptor.Using optval and optlen parameters would result inan attempt to access memory outside the caller’svirtual storage.Indicates that an IUCV error occurred.Indicates that the optname parameter isunrecognized, or the level parameter is notSOL_SOCKET.Indicates the s parameter is not a socket descriptorthat supports the optname parameter.48 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>Examples: The following are examples of the getsockopt() call. See “setsockopt()”on page 76 for examples of how the setsockopt() call options are set.int rc;int s;int optval;int optlen;struct linger l;int getsockopt(int s, int level, int optname, char *optval, int *optlen);


getsockopt()./* Is out of band data in the normal input queue? */optlen = sizeof(int);rc = getsockopt(s, SOL_SOCKET, SO_OOBINLINE, (char *) &optval, &optlen);if (rc == 0){if (optlen == sizeof(int)){if (optval)/* yes it is in the normal queue */else/* no it is not */}}./* Do I linger on close? */optlen = sizeof(l);rc = getsockopt(s, SOL_SOCKET, SO_LINGER, (char *) &l, &optlen);if (rc == 0){if (optlen == sizeof(l)){if (l.l_onoff)/* yes I linger */else/* no I do not */}}givesocket()See Also: getprotobyname(), setsockopt(), socket().#include #include int givesocket(s, clientid)int s,struct clientid *clientid;ParametersclientidDescriptionSpecifies the descriptor of a socket to be given to anotherapplication.Points to a struct clientid structure specifying the target program towhom the socket is to be given. Your program sets the fields of thestructure as follows:domain Specifies AF_INETnameSpecifies the virtual storage name or virtualmachine name of the target program, left-justifiedand padded with blanks. The target program canrun in the same virtual storage or virtual machineChapter 2. C Sockets Application Program Interface 49


givesocket()subtasknamereservedas your program, in which case your program setsthis field to its own virtual storage name or virtualmachine name.Contains blanks.Contains binary zeros.Any program running in the specified virtual storage or virtualmachine can use takesocket() to take control of the socket if itknows the client ID and the socket descriptor of your program.For backward compatibility, clientid may point to the struct clientidstructure when the target program calls getclientid(). In this case,only the target program can take the socket.Description: The givesocket() call tells <strong>TCP</strong><strong>IP</strong> to make the specified socketavailable to a takesocket() call issued by another application running on the samehost. Any connected stream socket can be given. Typically, givesocket() is used bya master program that obtains sockets by means of accept() and gives them toagent programs that handle one socket at a time.After calling givesocket(), your program passes its client ID (obtained by using thegetclientid() call) and the socket descriptor to the target program by passing it inthe target program’s startup parameter list. Your program then uses the select() callto check for a pending exception condition on the given socket, indicating that thetarget program has successfully called takesocket(). When the select() call indicatesa pending exception condition, your program calls close() to close the given socket.If your program closes the socket before a pending exception condition isindicated, the <strong>TCP</strong> connection is immediately reset, and the target program’s call totakesocket() is unsuccessful. Calls other than close() issued on a given socket returna value of −1, with errno set to EBADF.Return Values: The value 0 indicates success. The value −1 indicates an error. Thevalue of errno indicates a specific error.Errno ValueDescriptionEBADFEBUSYEFAULTEINVALENOTCONNEOPNOTSUPPSee Also: getclientid(), takesocket().Indicates that the d parameter is not a valid socketdescriptor. The socket has already been given. Thesocket domain is not AF_INET.Indicates that listen() has been called for the socket.Using the clientid parameter as specified wouldresult in an attempt to access storage outside thecaller’s virtual storage.Indicates that the clientid parameter does notspecify a valid client identifier.Indicates that the socket is not connected.Indicates that the socket type is notSOCK_STREAM.50 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


htonl()htonl()#include unsigned long htonl(a)unsigned long a;ParameteraDescriptionSpecifies the unsigned long integer to be put into network byteorder.htons()Description: The htonl() call translates a long integer from host byte order tonetwork byte order.Return Values: Returns the translated long integer.See Also: htons(), ntohs(), ntohl().#include unsigned short htons(a)unsigned short a;ParameteraDescriptionSpecifies the unsigned short integer to be put into network byteorder.Description: The htons() call translates a short integer from host byte order tonetwork byte order.Return Values: Returns the translated short integer.See Also: ntohs(), htonl(), ntohl().ibmsflush()For outbound sockets, the application-side datagram queue is flushed (transferredto the <strong>TCP</strong><strong>IP</strong> address space) if any one of the following occur:v An ibmsflush() is issued on the socket.v The queue is full and another send-type socket call is issued.v The socket is closed.v Another setibmsockopt() is issued.#include #include int ibmsflush(int s)ParametersRelated Calls:DescriptionThe socket descriptor.getibmsockopt(), setibmsockopt().Chapter 2. C Sockets Application Program Interface 51


inet_addr()inet_addr()#include unsigned long inet_addr(cp)char *cp;ParametercpDescriptionSpecifies a character string in standard dotted-decimal (.) notation.inet_lnaof()Description: The inet_addr() call interprets character strings representing numbersexpressed in standard dotted-decimal notation and returns numbers suitable foruse as an internet address.Values specified in standard dotted-decimal notation take one of the followingforms:a.b.c.da.b.ca.baWhen a four-part address is specified, each part is interpreted as a byte of dataand assigned, from left to right, to one of the four bytes of an internet address.When a three-part address is specified, the last part is interpreted as a 16-bitquantity and placed in the two rightmost bytes of the network address. This makesthe three-part address format convenient for specifying Class B network addressesas 128.net.host.When a two-part address is specified, the last part is interpreted as a 24-bitquantity and placed in the three rightmost bytes of the network address. Thismakes the two-part address format convenient for specifying Class A networkaddresses as net.host.When a one-part address is specified, the value is stored directly in the networkvirtual storage without any rearrangement of its bytes.Numbers supplied as address parts in standard dotted-decimal notation can bedecimal, hexadecimal, or octal. Numbers are interpreted in C language syntax. Aleading 0x implies hexadecimal; a leading 0 implies octal. A number without aleading 0 implies decimal.Return Values: The internet address is returned in network byte order.See Also: inet_lnaof(), inet_makeaddr(), inet_netof(), inet_network(), inet_ntoa().#include #include #include unsigned long inet_lnaof(in)struct in_addr in;52 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


inet_lnaof()ParameterinDescriptionSpecifies the host internet address.Description: The inet_lnaof() call breaks apart the internet host address andreturns the local network address portion.Return Values: The local network address is returned in host byte order.See Also: inet_addr(), inet_makeaddr(), inet_netof(), inet_network(), inet_ntoa().inet_makeaddr()#include #include struct in_addrinet_makeaddr(net, lna)unsigned long net;unsigned long lna;ParameternetlnaDescriptionSpecifies the network number.Specifies the local network address.inet_netof()Description: The inet_makeaddr() call takes a network number and a localnetwork address and constructs an internet address.Return Values: The internet address is returned in network byte order.See Also: inet_addr(), inet_lnaof(), inet_netof(), inet_network(), inet_ntoa().#include #include unsigned long inet_netof(in)struct in_addr in;ParameterinDescriptionSpecifies the internet address in network byte order.Description: The inet_netof() call breaks apart the internet host address andreturns the network number portion.Return Values: The network number is returned in host byte order.See Also: inet_addr(), inet_lnaof(), inet_makeaddr(), inet_ntoa().inet_network()Chapter 2. C Sockets Application Program Interface 53


inet_network()#include unsigned long inet_network(cp)char *cp;ParametercpDescriptionSpecifies a character string in standard dotted-decimal (.) notation.inet_ntoa()Description: The inet_network() call interprets character strings representingnumbers expressed in standard dotted-decimal notation and returns numberssuitable for use as a network number.Numbers supplied as address parts in standard dotted-decimal notation can bedecimal, hexadecimal, or octal. Numbers are interpreted in C language syntax. Aleading 0x implies hexadecimal; a leading 0 implies octal. A number without aleading 0 implies decimal.Return Values: The network number is returned in host byte order.See Also: inet_addr(), inet_lnaof(), inet_makeaddr(), inet_ntoa().#include #include char *inet_ntoa(in)struct in_addr in;ParameterinDescriptionSpecifies the host internet address.Description: The inet_ntoa() call returns a pointer to a string expressed in thedotted-decimal notation. inet_ntoa() accepts an internet address expressed as a32-bit quantity in network byte order and returns a string expressed indotted-decimal notation.Return Values: Returns a pointer to the internet address expressed indotted-decimal notation.See Also: inet_addr(), inet_lnaof(), inet_makeaddr(), inet_network(), inet_ntoa().ioctl()#include #include #include #include int ioctl(s, cmd, data)int s;unsigned long cmd;char *data;ParametersDescriptionSpecifies the socket descriptor.54 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


ioctl()cmddataSpecifies the command to perform.Points to the data associated with cmd.Description: The operating characteristics of sockets can be controlled with ioctl()requests. The operations to be controlled are determined by cmd. The dataparameter is a pointer to data associated with the particular command, and itsformat depends on the command that is requested. The following are valid ioctl()commands:Option DescriptionFIONBIOFIONREADSets or clears nonblocking input-output for a socket. data is apointer to an integer. If the integer is 0, nonblocking input-outputon the socket is cleared. Otherwise, the socket is set fornonblocking input-output.Gets the number of immediately readable bytes for the socket. datais a pointer to an integer. Sets the value of the integer to thenumber of immediately readable characters for the socket.SIOCADDRT Adds a routing table entry. The data parameter is a pointer to artentry structure, as defined in the RTROUTEH.H header file. Therouting table entry, passed as an argument, is added to the routingtables.SIOCATMARKQueries whether the current location in the data input is pointingto out-of-band data. The data parameter is a pointer to an integer.Sets the argument to 1 if the socket points to a mark in the datastream for out-of-band data. Otherwise, sets the argument to 0.SIOCDELRT Deletes a routing table entry. The data parameter is a pointer to artentry structure, as defined in the RTROUTEH.H header file. If itexists, the routing table entry passed as an argument is deletedfrom the routing tables.SIOCGIFADDRGets the network interface address. The data parameter is a pointerto an ifreq structure, as defined in the IF.H header file. The interfaceaddress is returned in the argument.SIOCGIFBRDADDRGets the network interface broadcast address. The data parameter isa pointer to an ifreq structure, as defined in the IF.H header file.The interface broadcast address is returned in the argument.SIOCGIFCONFGets the network interface configuration. The data parameter is apointer to an ifconf structure, as defined in the IF.H header file. Theinterface configuration is returned in the argument.SIOCGIFDSTADDRGets the network interface destination address. The data parameteris a pointer to an ifreq structure, as defined in the IF.H header file.The interface destination (point-to-point) address is returned in theargument.SIOCGIFFLAGSGets the network interface flags. The data parameter is a pointer toan ifreq structure, as defined in the IF.H header file. The interfaceflags are returned in the argument.Chapter 2. C Sockets Application Program Interface 55


ioctl()SIOCGIFMETRICGets the network interface routing metric. The data parameter is apointer to an ifreq structure, as defined in the IF.H header file. Theinterface routing metric is returned in the argument.SIOCGIFNETMASKGets the network interface network mask. The data parameter is apointer to an ifreq structure, as defined in the IF.H header file. Theinterface network mask is returned in the argument.SIOCSIFMETRICSets the network interface routing metric. The data parameter is apointer to an ifreq structure, as defined in the IF.H header file. Setthe interface routing metric to the value passed in the argument.SIOCSARPSets an address translation entry. The variable arg is a pointer to anarpreq structure, as defined in IF ARP.H.Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.Errno Value DescriptionEBADF Indicates that the s parameter is not a valid socket descriptor.EINVAL Indicates that the request is invalid or not supported.Example:The following is an example of the ioctl() call.int s;int dontblock;int rc;./* Place the socket into nonblocking mode */dontblock = 1;rc = ioctl(s, FIONBIO, (char *) &dontblock);.listen()#include #include int listen(s, backlog)int s;int backlog;ParametersbacklogDescriptionSpecifies the socket descriptor.Defines the maximum length for the queue of pending connections.Description: The listen() call applies only to stream sockets. It performs two tasks:it completes the binding necessary for a socket s, if bind() has not been called for s,and it creates a connection request queue of length backlog to queue incomingconnection requests. Once full, additional connection requests are ignored.The listen() call indicates a readiness to accept client connection requests. Ittransforms an active socket into a passive socket. Once called, s can never be used56 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


as an active socket to initiate connection requests. Calling listen() is the third offour steps that a server performs to accept a connection. It is called after allocatinga stream socket with socket(), and after binding a name to s with bind(). It must becalled before calling accept().If the backlog is less than 0, backlog is set to 0. If the backlog is greater thanSOMAXCONN, as defined in the SOCKET.H header file, backlog is set toSOMAXCONN.Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.Errno ValueDescriptionEBADFmaxdesc()EOPNOTSUPPSee Also: accept(), bind(), connect(), socket().Indicates that the s parameter is not a valid socketdescriptor.Indicates that the s parameter is not a socketdescriptor that supports the listen() call.listen()#include #include int maxdesc(totdesc, inetdesc)int *totdesc;int *inetdesc;ParametertotdescinetdescDescriptionPoints to an integer containing a value one greater than the largestdesired socket number.Points to an integer containing a value one greater than the largestdesired socket number usable for AF_INET sockets.Description: The maxdesc() call reserves additional space in the <strong>TCP</strong><strong>IP</strong> virtualmachine to allow socket numbers to extend beyond the default range of 0 through49. Socket numbers 0 through 2 are never assigned, so the default maximumnumber of sockets is 47.Set the integer pointed to by totdesc, to one more than the desired maximum socketnumber. If your program does not use AF_INET sockets, set the integer pointed toby inetdesc to 0. If your program uses AF_INET sockets, set the integer pointed toby inetdesc, to the same value as totdesc. maxdesc() must be called before yourprogram creates its first socket or after all sockets have been closed. Your programshould use getdtablesize() to verify that the number of sockets was changed.Return Values: The value 0 indicates success. Your application should check theinteger pointed to by inetdesc. It can contain less than the original value, if therewas insufficient storage available in the <strong>TCP</strong><strong>IP</strong> virtual machine. In this case thedesired number of AF_INET sockets are not available. The value −1 indicates anerror. The value of errno indicates the specific error.Errno ValueDescriptionChapter 2. C Sockets Application Program Interface 57


maxdesc()EFAULTEALREADYEINVALENOMEME<strong>IBM</strong>IUCVERRUsing the totdesc or inetdesc parameters as specifiedwould result in an attempt to access storageoutside of the caller’s virtual storage, or storagenot modifiable by the caller.Indicates that your program called maxdesc() toallocate a new socket descriptor set but was usingone or more sockets in the current set.Indicates that *totdesc is less than *inetdesc; *totdescis less than or equal to 0; or *inetdesc is less than 0.Indicates that your virtual machine has insufficientmemory.Indicates that an IUCV error occurred.ntohl()Examples:The following are examples of the maxdesc() call.int totdesc, inetdesc;totdesc = 100;inetdesc =0;rc = maxdesc(&totdesc, &inetdesc)If successful, your application can create 97 sockets, all of type AF_IUCV. Thesocket numbers run from 3 through 99.int totdesc, inetdesc;totdesc = 100;inetdesc = 100;rc = maxdesc(&totdesc, &inetdesc)If successful, your application can create 97 sockets, each of which can be of typeAF_INET or AF_IUCV. The socket numbers run from 3 through 99.If your application calls maxdesc() to define a socket descriptor set with more than255 sockets, then the socket descriptor bit set (fd_set) it uses on subsequent calls toselect() should be the defined with the same totdesc size used on the call tomaxdesc(). The default size of an fd_set (the FD_SETSIZE) can accommodate up to255 sockets. You can define an fd_set larger than FD_SETSIZE at either compiletime or runtime.To define an fd_set at compile time, set the FD_SETSIZE macro in your sourcecode to the desired value before including the BSDTYPES.H header file. Recompileyour source code to generate fd_sets that can handle up to the specified number ofsockets. Use the macros FD_ZERO, FD_SET, FD_CLR, and FD_ISSET in your codeto manipulate your fd_sets.To define an fd_set dynamically at runtime, include the TYPES.H header file inplace of BSDTYPES.H. Use the _GET_FDSET, _FREE_FDSET, _GET_FDSETSIZE,_FDSET_ZERO, and FD_ISSET macros defined in TYPES.H to manipulate yourfd_sets.See Also: select(), socket(), getdtablesize().58 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


ntohl()#include unsigned long ntohl(a)unsigned long a;ParameteraDescriptionSpecifies the unsigned long integer to be put into host byte order.ntohs()Description: The ntohl() call translates a long integer from network byte order tohost byte order.Return Values: Returns the translated long integer.See Also: htonl(), htons(), ntohs().#include unsigned short ntohs(a)unsigned short a;ParameteraDescriptionSpecifies the unsigned short integer to be put into host byte order.Description: The ntohs() call translates a short integer from network byte order tohost byte order.Return Values: Returns the translated short integer.See Also: ntohl(), htons(), htonl().read()int read(s, buf, len)int s;char *buf;int len;ParametersbuflenDescriptionSpecifies the socket descriptor.Points to the buffer that receives the data.Indicates the length in bytes of the buffer pointed to by the bufparameter.Description: The read() call reads data on a socket with descriptor s and stores itin a buffer. The read() call applies only to connected sockets.This call returns up to len bytes of data. If less than the number of bytes requestedis available, the call returns the number currently available. If data is not availableat the socket with descriptor s, the read() call waits for data to arrive and blocksthe caller, unless the socket is in nonblocking mode. See “ioctl()” on page 54 or“fcntl()” on page 31 for a description of how to set nonblocking mode.Chapter 2. C Sockets Application Program Interface 59


ead()readv()Return Values: If successful, the number of bytes copied into the buffer isreturned. The value 0 indicates that the connection was closed to the remote host.The value −1 indicates an error. The value of errno indicates the specific error.Errno ValueDescriptionEBADFIndicates that s is not a valid socket descriptor.EFAULTEWOULDBLOCKUsing the buf and len parameters would result inan attempt to access memory outside the caller’svirtual storage.Indicates that s is in nonblocking mode, and nodata is available to read.See Also: connect(), fcntl(), getsockopt(), ioctl(), readv(), recv(), recvmsg(),recvfrom(), select(), selectex(), send(), sendmsg(), sendto(), setsockopt(), socket(),write(), writev().#include #include int readv(s, iov, iovcnt)int s;struc iovec *iov;int iovcnt;ParametersioviovcntDescriptionSpecifies the socket descriptor.Points to an iovec structure.Specifies the number of buffers pointed to by the iov parameter.Description: The readv() call reads data on a socket with descriptor s and stores itin a set of buffers. The data is scattered into the buffers specified byiov[0]...iov[iovcnt−1]. The iovec structure is defined in the UIO.H header file andcontains the following fields:Element Descriptioniov_base Points to the buffer.iov_len Defines the length of the buffer.The readv() call applies only to connected sockets.This call returns up to len bytes of data. If less than the number of bytes requestedis available, the call returns the number currently available. If data is not availableat the socket with descriptor s, the readv() call waits for data to arrive and blocksthe caller, unless the socket is in nonblocking mode. See “fcntl()” on page 31 or“ioctl()” on page 54 for a description of how to set nonblocking mode.Return Values: If successful, the number of bytes read into the buffer(s) isreturned. The value 0 indicates that the connection was closed to the remote host.The value −1 indicates an error. The value of errno indicates the specific error.Errno ValueDescriptionEBADFIndicates that s is not a valid socket descriptor.60 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


eadv()EFAULTEINVALEWOULDBLOCKUsing iov and iovcnt would result in an attempt toaccess memory outside the caller’s virtual storage.Indicates that iovcnt was not valid, or one of thefields in the iov array was not valid.Indicates that s is in nonblocking mode, and nodata is available to read.See Also: connect(), fcntl(), getsockopt(), ioctl(), read(), recv(), recvmsg(),recvfrom(), select(), selectex(), send(), sendmsg(), sendto(), setsockopt(), socket(),write(), writev().recv()#include #include int recv(s, buf, len, flags)int s;char *buf;int len;int flags;ParametersbuflenflagsDescriptionSpecifies the socket descriptor.Points to the buffer that receives the data.Indicates the length in bytes of the buffer pointed to by the bufparameter.Set by specifying one or more of the following flags. If more thanone flag is specified, the logical OR operator (|)must be used toseparate them. Setting this parameter is supported only for socketsin the AF_INET domain. Setting these flags is not supported in theAF_IUCV domain.MSG_OOB Reads any out-of-band data on the socket.MSG_PEEKPeeks at the data present on the socket; the data isreturned but not consumed, so that a subsequentreceive operation sees the same data.Description: The recv() call receives data on a socket with descriptor s and stores itin a buffer. The recv() call applies only to connected sockets.This call returns the length of the incoming message or data. If a datagram packetis too long to fit in the supplied buffer, datagram sockets discard excess bytes. Ifdata is not available at the socket with descriptor s, the recv() call waits for amessage to arrive and blocks the caller, unless the socket is in nonblocking mode.See “fcntl()” on page 31 or “ioctl()” on page 54 for a description of how to setnonblocking mode.Return Values: If successful, the length of the message or datagram in bytes isreturned. The value 0 indicates that the connection was closed to the remote host.The value −1 indicates an error. The value of errno indicates the specific error.Errno ValueDescriptionChapter 2. C Sockets Application Program Interface 61


ecv()EBADFEFAULTEWOULDBLOCKIndicates that s is not a valid socket descriptor.Using the buf and len parameters would result inan attempt to access memory outside the caller’svirtual storage.Indicates that s is in nonblocking mode, and nodata is available to read.recvfrom()See Also: connect(), fcntl(), getsockopt(), ioctl(), read(), readv(), recvfrom(),recvmsg(), select(), selectex(), send(), sendmsg(), sendto(), setsockopt(), socket(),write(), writev().#include #include int recvfrom(s, buf, len, flags, name, namelen)int s;char *buf;int len;int flags;struct sockaddr *name;int *namelen;ParametersbuflenflagsnamenamelenDescriptionSpecifies the socket descriptor.Points to the buffer that receives the data.Indicates the length in bytes of the buffer pointed to by the bufparameter.Set to 0 or MSG_PEEK. Setting this parameter is supported onlyfor sockets in the AF_INET domain. Setting these flags is notsupported in the AF_IUCV domain.MSG_OOB Reads any out-of-band data on the socket.MSG_PEEKPeeks at the data present on the socket; the data isreturned but not consumed, so that a subsequentreceive operation sees the same data.Points to a socket address structure from which data is received. Ifname is a nonzero value, the source address is returned.Indicates the size of name in bytes.Description: The recvfrom() call receives data on a socket with descriptor s andstores it in a buffer. The recvfrom() call applies to any datagram socket, whetherconnected or unconnected.If the name parameter is nonzero, the source address of the message is filled. Thenamelen parameter must first be initialized to the size of the buffer associated withthe name parameter, and is then modified on return to indicate the actual size ofthe address stored there.This call returns the length of the incoming message or data. If a datagram packetis too long to fit in the supplied buffer, datagram sockets discard excess bytes. Ifdatagram packets are not available at the socket with descriptor s, the recvfrom()62 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


call waits for a message to arrive and blocks the caller, unless the socket is innonblocking mode. See “fcntl()” on page 31 or “ioctl()” on page 54 for a descriptionof how to set nonblocking mode.Return Values: If successful, the length of the message or datagram in bytes isreturned. The value 0 indicates that the connection was closed to the remote host.The value −1 indicates an error. The value of errno indicates the specific error.Errno ValueDescriptionEBADFIndicates that s is not a valid socket descriptor.EFAULTrecvmsg()EWOULDBLOCKrecvfrom()Using the buf and len parameters would result inan attempt to access memory outside the caller’svirtual storage.Indicates that s is in nonblocking mode, and nodata is available to read.See Also: fcntl(), getsockopt(), ioctl(), read(), readv(), recv(), recvmsg(), select(),selectex(), send(), sendmsg(), sendto(), setsockopt(), socket(), write(), writev().#include #include int recvmsg(s, msg, flags)int s;struct msghdr msg[];int flags;ParametersmsgflagsDescriptionSpecifies the socket descriptor.Specifies an array of message headers into which messages arereceived.Set by specifying one or more of the following flags. If more thanone flag is specified, the logical OR operator (|)must be used toseparate them. Setting this parameter is supported only for socketsin the AF_INET domain. Setting these flags is not supported in theAF_IUCV domain.MSG_OOB Reads any out-of-band data on the socket.MSG_PEEKPeeks at the data present on the socket; the data isreturned but not consumed, so that a subsequentreceive operation will see the same data.Description: The recvmsg() call receives messages on a socket with descriptor sand stores them in an array of message headers. A message header is defined by amsghdr. The definition of this structure can be found in the SOCKET.H header fileand contains the following elements:Element Descriptionmsg_namemsg_namelenSpecifies an optional pointer to a buffer where the sender’s addressis stored.Indicates the size of the address buffer.Chapter 2. C Sockets Application Program Interface 63


ecvmsg()select()msg_iov Specifies an array of iovec buffers into which the message is placed.msg_iovlen Specifies the number of elements in the msg_iov array.msg_accrights Indicates the access rights received. This field is ignored.msg_accrightslenIndicates the length of access rights received. This field is ignored.The recvmsg() call applies to sockets, regardless of whether they are in theconnected state.This call returns the length of the data received. If data is not available at thesocket with descriptor s, the recvmsg() call waits for a message to arrive andblocks the caller, unless the socket is in nonblocking mode. See “fcntl()” on page 31or “ioctl()” on page 54 for a description of how to set nonblocking mode.Return Values: If successful, the length of the message in bytes is returned. Thevalue 0 indicates that the connection was closed to the remote host. The value −1indicates an error. The value of errno indicates the specific error.Errno ValueDescriptionEBADFIndicates that s is not a valid socket descriptor.EFAULTEWOULDBLOCKUsing msg would result in an attempt to accessmemory outside the caller’s virtual storage.Indicates that s is in nonblocking mode, and nodata is available to read.See Also: connect(), fcntl(), getsockopt(), ioctl(), read(), readv(), recv(), recvfrom(),select(), selectex(), send(), sendmsg(), sendto(), setsockopt(), socket(), write(),writev().#include #include int select(nfds, readfds, writefds, exceptfds, timeout)int nfds;fd_set *readfds;fd_set *writefds;fd_set *exceptfds;struct timeval *timeout;Parameter Descriptionnfds Specifies the greatest socket descriptor to check plus 1.readfds Points to a bit set of descriptors to check for reading.writefds Points to a bit set of descriptors to check for writing.exceptfds Points to a bit set of descriptors to be checked for exceptionalpending conditions.timeout Points to the time to wait for the select() call to complete.64 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


select()Description: The select() call monitors activity on a set of sockets to see if any ofthe sockets are ready for reading, writing, or have an exceptional conditionpending.If timeout is not a NULL pointer, it specifies a maximum interval to wait for theselection to complete. If timeout is a NULL pointer, the select call blocks until asocket becomes ready. To poll the sockets and return immediately, timeout shouldbe a non-NULL pointer to a zero-valued timeval structure.To completely understand the implementation of the select call, you mustrecognize the difference between a socket and a port. <strong>TCP</strong>/<strong>IP</strong> defines ports torepresent a certain process on a certain machine. A port represents the location ofone process; it does not represent a connection between processes. In the <strong>VM</strong>programming interface for <strong>TCP</strong>/<strong>IP</strong>, a socket describes an endpoint ofcommunication. Therefore, a socket describes both a port and a machine. Like filedescriptors, a socket is a small integer representing an index into a table ofcommunication endpoints in a <strong>TCP</strong><strong>IP</strong> virtual machine.If your program specified apitype=2, only one SELECT may be outstanding on theIUCV path, and will be cancelled with a return value of zero when any subsequentfunction is performed on the same path, without regard to the specific socketdescriptors involved.To allow you to test more than one socket at a time, the sockets to test are placedinto a bit set of type FD_SET. A bit set is a string of bits such that if X is anelement of the set, the bit representing X is set to 1. If X is not an element of theset, the bit representing X is set to 0. For example, if socket 33 is an element of abit set, then bit 33 is set to 1. If socket 33 is not an element of a bit set, then bit 33is set to 0.Because the bit sets contain a bit for every socket that a process can allocate, the bitsets are of constant size. The function getdtablesize() returns the number of socketsthat your program can allocate. If your program needs to allocate a large numberof sockets, use getdtablesize() and maxdesc() to increase the number of sockets thatcan be allocated. Increasing the size of the bit sets must be done at compile time.To increase the size of the bit sets before including the BSDTYPES.H header file,define FD_SETSIZE to be the largest value of any socket. The default size ofFD_SETSIZE is 255 sockets.The following macros are provided to manipulate bit sets.MacroDescriptionFD_ZERO(&fdset)Sets all bits in the bit set fdset to zero. After thisoperation, the bit set has no sockets as elements.This macro should be called to initialize the bit setbefore calling FD_SET() to set a socket as amember.FD_SET(sock, &fdset) Sets the bit for the socket sock to a 1, making sock amember of the bit set fdset.FD_CLR(sock, &fdset) Clears the bit for the socket sock in bit set fdset.This operation sets the appropriate bit to a zero.FD_ISSET(sock, &fdset) Returns >0ifsock is a member of the bit set fdset.Returns zero if sock is not a member of fdset. (Thisoperation returns the bit representing sock.)Chapter 2. C Sockets Application Program Interface 65


select()A socket is ready for reading when incoming data is buffered for it or when aconnection request is pending. A call to accept(), read(), recv(), or recvfrom() doesnot block. To test whether any sockets are ready for reading, use FD_ZERO() tointialize the readfds bit set, and invoke FD_SET() for each socket to test.A socket is ready for writing if there is buffer space for outgoing data. Anonblocking stream socket in the process of connecting (connect() returnedEINPROGRESS) is selected for write when the connect() completes. A call towrite(), send(), or sendto() does not block providing that the amount of data is lessthan the amount of buffer space. If a socket is selected for write, the amount ofavailable buffer space is guaranteed to be at least as large as the size returned fromusing SO_SNDBUF with getsockopt(). To test whether any sockets are ready forwriting, initialize writefds with FD_ZERO(), and use FD_SET() for each socket totest.The select() call checks for a pending exception condition on the given socket,indicating that the target program has successfully called takesocket(). Whenselect() indicates a pending exception condition, your program calls close() to closethe given socket. A socket has exceptional conditions pending if it has receivedout-of-band data. A stream socket that was given using givesocket() is selected forexception when another application successfully takes the socket usingtakesocket().The programmer can pass NULL for any bit sets that do not have any sockets totest. For example, if a program need only check a socket for reading, it can passNULL for both writefds and exceptfds.Because the sets of sockets passed to select() are bit sets, the select() call must testeach bit in each bit set before polling the socket for its status. For efficiency, thenfsd parameter specifies the largest socket that is passed in any of the bit sets. Theselect call then tests only sockets in the range 0 to nfsd−1. nfsd can be the result ofgetdtablesize(); but if the application only has two sockets and nfsd is the result ofgetdtablesize(), select() is going to test every bit in each bit set.Return Values: The total number of ready sockets in all bit sets is returned. Thevalue −1 indicates errno should be checked for an error. The value zero indicatesan expired time limit. If the return value is greater than zero, the sockets that areready in each bit set are set 1. Sockets in each bit set that are not ready are set tozero. Use the macro FD_ISSET() with each socket to test its status.Errno Value DescriptionEBADFEFAULTEINVAL66 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>Indicates that one of the bit sets specified an invalid socket.FD_ZERO() was probably not called to clear the bit set before thesockets were set.Indicates that one of the bit sets pointed to a value outside thecaller’s virtual storage.Indicates that one of the fields in the timeval structure is invalid.Examples: In the following example, select() is used to poll three sockets: one forreading, one for writing, and one for exceptional conditions./* sock_stats(r, w, e) - Print the status of sockets r, w, and e. */int sock_stats(r, w, e)int r, w, e;{fd_set reading, writing, except;struct timeval timeout;


select()int rc, max_sock;/* initialize the bit sets */FD_ZERO( &reading );FD_ZERO( &writing );FD_ZERO( &except );/* add r, w, and e to the appropriate bit set */FD_SET( r, &reading );FD_SET( w, &writing );FD_SET( e, &except );/* for efficiency, what’s the maximum socket number? */max_sock = MAX( r, w );max_sock = MAX( max_sock, e );/* make select poll by sending a 0 timeval */memset( &timeout, 0, sizeof(timeout) );/* poll */rc = select( max_sock, &reading, &writing, &except, &timeout );}if(rc


selectex()ecbptrPoints to the event control block (ECB).Description: The selectex() call monitors activity on a set of different sockets untila time-out expires, to see if any sockets are ready for reading or writing, or if anyexceptional conditions are pending. Bit mask is made up of an array of integers.Macros are provided to manipulate the bit masks. Refer to the select() call for acomplete description of the macros.Return Values: The total number of ready sockets (in all bit masks) is returned.The value −1 indicates an error. The value 0 indicates an expired time limit. If thereturn value is greater than 0, the socket descriptors in each bit mask that areready are set to 1. All others are set to 0.Errno Value DescriptionEBADFEFAULTEINVALIndicates that one of the descriptor sets specified an invaliddescriptor.Indicates that one of the parameters pointed to a value outside thecaller’s virtual storage.Indicates that one of the fields in the timeval structure is invalid.See Also: accept(), connect(), getdtablesize(), recv(), send(), select().send()#include #include int send(s, msg, len, flags)int s;char *msg;int len;int flags;ParametersmsglenflagsDescriptionSpecifies the socket descriptor.Points to the buffer containing the message to transmit.Specifies the length of the message pointed to by the buf parameter.Set by specifying one or more of the following flags. If more thanone flag is specified, the logical OR operator (|) must be used toseparate them. Setting this parameter is supported only for socketsin the AF_INET domain. Setting these flags is not supported in theAF_IUCV domain.MSG_OOBMSG_DONTROUTESends out-of-band data on socketsthat support this notion. OnlySOCK_STREAM sockets created inthe AF_INET address familysupport out-of-band data.Indicates that theSO_DONTROUTE option is turnedon for the duration of theoperation. This is usually used onlyby diagnostic or routing programs.68 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Description: The send() call sends packets on the socket with descriptor s. Thesend() call applies to all connected sockets.If buffer space is not available at the socket to hold the message to be transmitted,the send() call normally blocks, unless the socket is placed in nonblockingInput/Output (I/O) mode. See “ioctl()” on page 54 or “fcntl()” on page 31 for adescription of how to set nonblocking mode. The select() call can be used todetermine when it is possible to send more data.Return Values: No indication of failure to deliver is implicit in a send() routine.The value −1 indicates locally detected errors. The value of errno indicates thespecific error.Errno ValueDescriptionEBADFIndicates that s is not a valid socket descriptor.EFAULTENOBUFSsendmsg()EWOULDBLOCKUsing the buf and len parameters would result inan attempt to access memory outside the caller’svirtual storage.Indicates that no buffer space is available to sendthe message.Indicates that s is in nonblocking mode, and nodata is available to read.send()See Also: connect(), fcntl(), getsockopt(), ioctl(), read(), readv(), recv(), recvfrom(),recvmsg(), select(), selectex(), sendmsg(), sendto(), socket(), write(), writev().#include #include int sendmsg(s, msg, flags)int s;struct msghdr msg[];int flags;ParametersmsgflagsDescriptionSpecifies the socket descriptor.Specifies an array of message headers from which messages aresent.Set by specifying one or more of the following flags. If more thanone flag is specified, the logical OR operator (|) must be used toseparate them. Setting this parameter is supported only for socketsin the AF_INET domain. Setting these flags is not supported in theAF_IUCV domain.MSG_OOBMSG_DONTROUTESends out-of-band data on thesocket.Indicates that theSO_DONTROUTE option is turnedon for the duration of theoperation. This is usually used onlyby diagnostic or routing programs.Chapter 2. C Sockets Application Program Interface 69


sendmsg()sendto()Description: The sendmsg() call sends messages on a socket with descriptor spassed in an array of message headers. A message header is defined by a msghdr.The definition of this structure can be found in the SOCKET.H header file andcontains the following elements:Element Descriptionmsg_name Specifies the optional pointer to the buffer containing therecipient’s address.msg_namelen Indicates the size of the address buffer.msg_iov Specifies an array of iovec buffers containing the message.msg_iovlen Specifies the number of elements in the msg_iov array.msg_accrights Indicates the access rights sent. This field is ignored.msg_accrightslenIndicates the length of the access rights sent. This field is ignored.The sendmsg() call applies to sockets regardless of whether they are in theconnected state.This call returns the length of the data sent. If the socket with descriptor s is notready for sending data, the sendmsg() call waits for the ability to send data andblocks the caller. s is in nonblocking mode unless the socket is in nonblockingmode. See “fcntl()” on page 31 or “ioctl()” on page 54 for a description of how toset nonblocking mode.Return Values: If successful, the length of the message in bytes is returned. Thevalue −1 indicates an error. The value of errno indicates the specific error.Errno ValueDescriptionEBADFIndicates that s is not a valid socket descriptor.EFAULTEINVALEMSGSIZEENOBUFSEWOULDBLOCKUsing msg would result in an attempt to accessmemory outside the caller’s virtual storage.Indicates that tolen is not the size of a valid addressfor the specified address family.Indicates that the message was too big to be sent asa single datagram. The default is 8192, and themaximum is 32 767.Indicates that no buffer space is available to sendthe message.Indicates that s is in nonblocking mode, and nodata is available to read.See Also: connect(), fcntl(), getsockopt(), ioctl(), read(), readv(), recv(), recvfrom(),recvmsg(), select(), selectex(), send(), sendto(), setsockopt(), socket(), write(),writev().70 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


sendto()#include #include int sendto(s, msg, len, flags, to, tolen)int s;char *msg;int len;int flags;struct sockaddr *to;int tolen;ParametersmsglenflagstotolenDescriptionSpecifies the socket descriptor.Points to the buffer containing the message to transmit.Specifies the length of the message in the buffer pointed to by themsg parameter.Set to 0 or MSG_DONTROUTE. Setting this parameter issupported only for sockets in the AF_INET domain. Setting theseflags is not supported in the AF_IUCV domain.MSG_DONTROUTEThe SO_DONTROUTE option is turned on for theduration of the operation. This is usually used onlyby diagnostic or routing programs.Specifies the address of the target.Indicates the size of the address pointed to by the to pointer.Description: The sendto() call sends packets on the socket with descriptor s. Thesendto() call applies to any datagram socket, whether connected or unconnected.Return Values: If successful, the number of characters sent is returned. The value−1 indicates an error. The value of errno indicates the specific error.No indication of failure to deliver is implied in the return value of this call whenused with datagram sockets.Errno ValueDescriptionEBADFIndicates that s is not a valid socket descriptor.EFAULTEINVALEMSGSIZEENOBUFSEWOULDBLOCKUsing the buf and len parameters would result inan attempt to access memory outside the caller’svirtual storage.Indicates that tolen is not the size of a valid addressfor the specified address family.Indicates that the message was too big to be sent asa single datagram. The default is 8192, and themaximum is 32,767.Indicates that no buffer space is available to sendthe message.Indicates that s is in nonblocking mode, and nodata is available to read.See Also: read(), readv(), recv(), recvfrom(), recvmsg(), send(), select(), selectex(),sendmsg(), socket() write(), writev().Chapter 2. C Sockets Application Program Interface 71


sethostent()sethostent()int sethostent(stayopen)int stayopen;The sethostent() call has no parameters.Description: The sethostent() call opens and rewinds the HOSTS SITEINFO file.The HOSTS file contains information about known hosts. If the stayopen flag isnonzero, the HOSTS file remains open after each call.The sethostent() call is available only if RESOLVE_VIA_LOOKUP is defined beforethe MANIFEST.H header file is included.Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.See Also: endhostent(), gethostbyaddr(), gethostbyname(), gethostent().setibmsockopt()Setibmsockopt() controls socket options specific to the <strong>IBM</strong> <strong>TCP</strong>/<strong>IP</strong>implementation.#include #include int setibmsockopt(int s, int level, int optname, char *optval, int optlen)ParametersleveloptnameoptvaloptlenDescriptionThe socket descriptor.The level for which the option is being set. Only SOL_SOCKET issupported.The name of a specified socket option:v SO_BULKMODEv SO_NONBLOCKLOCALv SO_IGNOREINCOMINGPUSHThe pointer to option data.The length of the option data.SO_BULKMODEUse setibmsockopt() with the optname SO_BULKMODE to place the UDP socket sin bulk mode. The bulk mode socket option enables an application to queuemultiple datagrams, sending all of the datagrams in one large buffer. This reducesthe CPU consumption for each datagram.For inbound datagrams, a queue of pending datagrams is maintained on theapplication side of the interface. As the application performs receive calls, it drawsfrom that queue. When the queue is empty, recv() call requests that <strong>TCP</strong><strong>IP</strong> passover whatever datagrams are pending in one transaction. The oldest datagram isreturned to the caller, and the application-side queue is replenished.72 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


setibmsockopt()For outbound datagrams, a separate queue is kept on the application side of theinterface. When the application performs send calls, the datagram is queued. Whenthere are no more datagrams to send out, ibmsflush() is called to send the queueddatagrams to the <strong>TCP</strong><strong>IP</strong> address space in one transaction.Note: Bulk mode is valid for all send calls--send(), sendmsg(), sendto(), andwrite()--except for the writev() call. Bulk mode is valid for all readcalls--read(), recv(), recvmsg(), and recvfrom()--except for the readv() call.However, for the sendmsg() and recvmsg() calls, only one datagram isprocessed per call.Use of bulk mode can improve program performance. Performance improvementdepends on the system load and the arrival pattern of the datagram messages atthe socket. As system load increases, the reduction in CPU use because of bulkmode should also increase. When datagrams for the socket are processed, thereshould be an even greater reduction in CPU usage.When optname is SO_BULKMODE, optval must point to an ibm_bulkmode_structwith values set as follows:Element Descriptionb_onoff 1 means bulk mode is on; 0 means bulk mode is off.b_max_receive_queue_sizeThe maximum receiving queue size in bytes. Specifying a value of0 prevents queuing for inbound datagrams.b_max_send_queue_sizeThe maximum sending queue size in bytes. Specifying a value of 0prevents queuing for outbound datagrams.b_teststor If this element is nonzero, the message buffer address and themessage buffer are checked for addressability during each socketcall. errno is set to EFAULT if there is an addressing exception. Ifthis element is zero, checking is not performed.b_move_data Must be set to 1.The socket calls that receive datagrams in your program (recvfrom(), recv(), read(),or recvmsg()) do not need to be changed. If you are using a queue for sendingdatagrams (by specifying a nonzero value for b_max_send_queue_size above), youshould code ibmsflush() to flush the socket at appropriate points, such as after yousend a burst of datagrams that is normally followed by a pause.SO_NONBLOCKLOCALThe option is meaningful only for sockets that have been enabled for bulk modeusing the setibmsockopt() call with SO_BULKMODE. In nonblocking mode, whenthe application-side queue is empty, the socket library returns −1 on a receive andsets errno to EWOULDBLOCK. optval should point to an integer. If optval points to1, the socket is placed in nonblocking mode. If optval points to 0, the socket isplaced in blocking mode.Before the application calls SO_NONBLOCKLOCAL, the socket is in blockingmode.Chapter 2. C Sockets Application Program Interface 73


setibmsockopt()SO_IGNOREINCOMINGPUSHThis option is meaningful only for stream sockets connections established throughan offload box. optval must point to an integer. If optval points to 1, the option isset. If optval points to 0, the option is off.The SO_IGNOREINCOMINGPUSH option causes a receive call to return when:v The requested length is reached.v The internal <strong>TCP</strong><strong>IP</strong> length is reached.v The peer application closes the connection.The amount of data returned for each call is maximized and the amount of CPUtime consumed by your program and <strong>TCP</strong><strong>IP</strong> can be reduced.This option is not appropriate for your operation if your program 9 For example,this option is appropriate for an FTP data connection, but not for a Telnetconnection.Example:#include #include #include The following is an example of the setibmsockopt() call.{ struct ibm_bulkmode_struct bulkstr;int optlen, rc;optlen = sizeof(bulkstr);rc = getibmsockopt(s, SOL_SOCKET, SO_BULKMODE, (char *), &bulkstr, &optlen);if(rc


setnetent()Related Calls:getibmsockopt(), getsockopt(), ibmsflush(), setsockopt().setnetent()int setnetent(stayopen)int stayopen;The setnetent() call has no parameters.Description: The setnetent() call opens and rewinds the HOSTS SITEINFO file. TheHOSTS SITEINFO file contains information about known networks. If the stayopenflag is nonzero, the HOSTS SITEINFO file remains open after each call tosetnetent().Note: HOSTS LOCAL, HOSTS ADDRINFO, and HOSTS SITEINFO are shown in<strong>TCP</strong>/<strong>IP</strong> Planning and Customization.Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.setprotoent()See Also: endnetent(), getnetbyaddr(), getnetbyname(), getnetent().setservent()int setprotoent(stayopen)int stayopen;The setprotoent() call has no parameters.Description: The setprotoent() call opens and rewinds the ETC PROTO file. If thestayopen flag is nonzero, the ETC PROTO file remains open after each call.Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.See Also: endprotoent(), getprotobyname(), getprotobynumber(), getprotoent().int setservent(stayopen)int stayopen;The setservent() call has no parameters.Description: The setservent() call opens and rewinds the ETC SERVICES file. Formore information about the ETC SERVICES file, see “Appendix C. Well-KnownPort Assignments” on page 413. If the stayopen flag is nonzero, the ETC SERVICESfile remains open after each call.Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.See Also: endservent(), getservbyname(), getservent().Chapter 2. C Sockets Application Program Interface 75


setsockopt()setsockopt()#include #include int setsockopt(s, level, optname, optval, optlen)int s;int level;int optname;char *optval;int optlen;|ParametersleveloptnameoptvaloptlenDescriptionSpecifies the socket descriptor.Specifies the level for which the option is set. Only SOL_SOCKETand <strong>IP</strong>PROTO_<strong>IP</strong> are supported.Specifies the name of a specified socket option.Points to option data.Indicates the length of the option data.Description: The setsockopt() call sets options associated with a socket. It can becalled only for sockets in the AF_INET domain. This call is not supported in theAF_IUCV domain. Options can exist at multiple protocol levels; they are alwayspresent at the highest socket level.|When manipulating socket options, you must specify the level at which the optionresides and the name of the option. To manipulate options at the socket level, thelevel parameter must be set to SOL_SOCKET or <strong>IP</strong>PROTO_<strong>IP</strong>, as defined inSOCKET.H. To manipulate options at any other level, such as the <strong>TCP</strong> or <strong>IP</strong> level,supply the appropriate protocol number for the protocol controlling the option.Currently, only the SOL_SOCKET and <strong>IP</strong>PROTO_<strong>IP</strong> levels are supported. Thegetprotobyname() call can be used to return the protocol number for a namedprotocol.The optval and optlen parameters are used to pass data used by the particular setcommand. The optval parameter points to a buffer containing the data needed bythe set command. The optval is optional and can be set to the NULL pointer, if datais not needed by the command. The optlen parameter must be set to the size of thedata pointed to by optval.All of the socket level options except SO_LINGER expect optval to point to aninteger and optlen to be set to the size of an integer. When the integer is nonzero,the option is enabled. When it is zero, the option is disabled. The SO_LINGERoption expects optval to point to a linger structure, as defined in SOCKET.H. Thisstructure is defined in the following example:struct linger{};int l_onoff; /* option on/off */int l_linger; /* linger time */The l_onoff field is set to zero if the SO_LINGER option is being disabled. Anonzero value enables the option. The l_linger field specifies the amount of timeto linger on close. The units of l_linger are seconds.76 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


setsockopt()||||||||||||||||||||||||||||||||||||||||||||||||||||The following options are recognized at the <strong>IP</strong> level (<strong>IP</strong>PROTO_<strong>IP</strong>):Option Description<strong>IP</strong>_MULTICAST_TTLSets the <strong>IP</strong> time-to-live of outgoing multicast datagrams. Thedefault value is 1 (multicast only to directly attached network). TheTTL value is passed in as a u_char. This option is only supportedfor sockets with an address family of AF_INET and type ofSOCK_DGRAM or SOCK_RAW.<strong>IP</strong>_MULTICAST_LOOPEnables/disables loopback of outgoing multicast datagrams. Thedefault is enable. When loopback is enabled, multicast applicationsthat have joined the outgoing multicast group can receive a copy ofthe multicast datagram destined for that address/port pair. Theloopback indicator is passed as u_char. Specify a value of 0 todisable loopback; specify a value of 1 to enable loopback. Thisoption is only supported for sockets with an address family ofAF_INET and type of SOCK_DGRAM or SOCK_RAW.<strong>IP</strong>_MULTICAST_IFSets the interface for sending outbound multicast datagrams fromthis socket application. Multicast datagrams will be transmitted ononly the specified interface. The default is INADDR_ANY whichmeans all interfaces. The <strong>IP</strong> Address of the interface is passedusing structure in_addr. An address of INADDR_ANY removes theprevious selection. This option is only supported for sockets withan address family of AF_INET and type of SOCK_DGRAM orSOCK_RAW.<strong>IP</strong>_ADD_MEMBERSH<strong>IP</strong>Joins a multicast group on a specific interface (an interface has tobe specified with this option). Only applications that want toreceive multicast datagrams need to join multicast groups.Applications that only transmit multicast datagrams do not need tojoin multicast groups. A single socket can join up to 20 groups. Themulticast <strong>IP</strong> address and the interface <strong>IP</strong> address will be passed inip_mreq structure defined in IN.H.struct ip_mreq{struct in_addr imr_multiaddr; /* <strong>IP</strong> multicast addr of group */struct in_addr imr_interface; /* local <strong>IP</strong> addr of interface */);This option is only supported for sockets with an address family ofAF_INET and type of SOCK_DGRAM or SOCK_RAW.<strong>IP</strong>_DROP_MEMBERSH<strong>IP</strong>Leaves a multicast group on a specific interface. The multicast <strong>IP</strong>address and the interface <strong>IP</strong> address will be passed in the ip_mreqstructure defined in IN.H.struct ip_mreq{struct in_addr imr_multiaddr; /* <strong>IP</strong> multicast addr of group */struct in_addr imr_interface; /* local <strong>IP</strong> addr of interface */);This option is only supported for sockets with an address family ofAF_INET and type of SOCK_DGRAM or SOCK_RAW.Chapter 2. C Sockets Application Program Interface 77


setsockopt()|The following options are recognized at the socket level:OptionDescriptionSO_KEEPALIVEToggles the <strong>TCP</strong> keep-alive mechanism for a streamsocket. When activated, the keep-alive mechanismperiodically sends a packet on an otherwise idleconnection. If the remote <strong>TCP</strong> does not respond tothe packet or to retransmissions of the packet, theconnection is terminated with the errorETIMEDOUT.SO_BROADCASTToggles the ability to broadcast messages. If thisoption is enabled, it allows the application to sendbroadcast messages over s, if the interface specifiedin the destination supports broadcasting of packets.This option has no meaning for stream sockets.SO_LINGERLingers on close if data is present. When thisoption is enabled and there is unsent data presentwhen close() is called, the calling application isblocked during the close() call until the data istransmitted or the connection has timed out. If thisoption is disabled, the <strong>TCP</strong><strong>IP</strong> virtual machine waitsto try to send the data. Although the data transferis usually successful, it cannot be guaranteed,because the <strong>TCP</strong><strong>IP</strong> virtual machine waits only afinite amount of time trying to send the data. Theclose() call returns without blocking the caller. Thisoption has meaning only for stream sockets.SO_OOBINLINEToggles the reception of out-of-band data. Whenthis option is enabled, it causes out-of-band data tobe placed in the normal data input queue as it isreceived, making it available to recv(), recvfrom(),and recvmsg() without having to specify theMSG_OOB flag in those calls. When this option isdisabled, it causes out-of-band data to be placed inthe priority data input queue as it is received,making it available to recv(), recvfrom(), andrecvmsg() only by specifying the MSG_OOB flag inthose calls. This option has meaning only forstream sockets.SO_REUSEADDRToggles local address reuse. When enabled, thisoption allows local addresses that are already inuse to be bound. This alters the normal algorithmused in the bind() call. The system checks atconnect time to be sure that no local address andport have the same foreign address and port. Theerror EADDRINUSE is returned if the associationalready exists.Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.Errno Value Description78 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


setsockopt()|||||||||||||||EADDRINUSEIndicates that the socket has already joined the multicast group onthe selected interface.EADDRNOTAVAILIndicates that the interface <strong>IP</strong> address cannot be found or does notsupport multicasting.EBADF Indicates that the s parameter is not a valid socket descriptor.EFAULT Indicates that using optval and optlen parameters would result in anattempt to access memory outside the caller’s virtual storage.E<strong>IBM</strong>IUCVERRIndicates that an IUCV error occurred.EINVAL Indicates that the multicast <strong>IP</strong> address specified is not a valid ClassD <strong>IP</strong> address (designated by the high order four bits being set toB’1110’.EOPNOTSUPPIndicates that the s parameter is not a socket desciptor thatsupports the optname parameter.ETOOMANYREFSIndicates that the socket has already joined the maximum numberof multicast groups (<strong>IP</strong>_MAX_MEMBERSH<strong>IP</strong>S=20).Examples: The following are examples of the setsockopt() call. See “getsockopt()”on page 45 for examples of how the getsockopt() options set are queried.int rc;int s;int optval;struct linger l;int setsockopt(int s, int level, int optname, char *optval, int optlen);./* I want out of band data in the normal input queue */optval = 1;rc = setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (char *) &optval, sizeof(int));./* I want to linger on close */l.l_onoff = 1;l.l_linger = 100;rc = setsockopt(s, SOL_SOCKET, SO_LINGER, (char *) &l, sizeof(l));See Also: fcntl(), getprotobyname(), getsockopt(), ioctl(), socket().sockdb_sock_debug()The sock_debug() call controls the socket library tracing facility. If enabled, allsocket calls and interrupts are traced, with output directed to the virtual console.If you include the SOCKDEBUG statement in the <strong>TCP</strong><strong>IP</strong> DATA file, tracing isactive by default. A call to sock_debug() is not required.#include #include void sock_debug(int onoff)Chapter 2. C Sockets Application Program Interface 79


sockdb_sock_debug()ParameteronoffDescriptionTRUE tracing is enabled.FALSEtracing is disabledsock_debug_bulk_perf0 ()The sock_debug_bulk_perf0() call controls the generation of a performance reportwhen any socket configured for bulk mode is closed. The report is directed to thevirtual console.If you include the SOCKDEBUGBULKPERF0 statement in the <strong>TCP</strong><strong>IP</strong> DATA file,performance reports are enabled by default. A call to sock_debug_bulk_perf0() isnot required.#include #include void sock_debug_bulk_perf0(int onoff)ParameteronoffDescriptionTRUE A performance report is generated.FALSEA performance report is not generated.If this parameter is omitted a performance report is not produced.Example: The following is an example of the sock_debug_bulk_perf0() socket()call report.Bulkmode performance for socket 3:Doing TESTSTOR (ie. testing addressability of buffers, etc.)Received 14601460 bytes,10001 datagrams, 846 IUCV’s 11.8datagrams⁄IUCV.In this example, 3 is the socket descriptor for the socket running in bulk mode.Doing TESTSTOR indicates that the library was checking for addressing errors onsocket calls, and 14,601,460 bytes of data were received in 10,001 datagrams. 846calls were done to read the datagrams on the socket for an average of 11.8datagrams for each IUCV.sock_do_bulkmode()The sock_do_bulkmode() controls the initial BULKMODE setting for datagramsockets.If you include the SOCKBULKMODE statement in the <strong>TCP</strong><strong>IP</strong> DATA file, bulkmode is enabled by default. A call to sock_do_bulkmode() is not required.For a complete description of bulk mode, see setibmsockopt().80 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


sock_do_bulkmode()#include #include void sock_do_bulkmode(int onoff)ParameteronoffDescriptionTRUEFALSEAll sockets with type SOCK_DGRAM are created with bulkmode enabled.All sockets with type SOCK_DGRAM are created with bulkmode disabled. A call to setibmsockopt() is required toenable bulk mode for a specific socket.sock_do_teststor()The sock_do_teststor() call is used to check for calls that attempt to access storageoutside the caller’s address space.If you include the statement SOCKTESTSTOR in the <strong>TCP</strong><strong>IP</strong> DATA file, addresschecking is active by default. A call to sock_do_teststor() is not necessary.#include #include void sock_do_teststor(int onoff)ParameteronoffDescriptionTRUEFALSEThe address of the message buffer and the message bufferare checked for addressability for each socket call. Theerror condition, EFAULT is set if there is an addressingproblem.Address checking is not done. If an error occurs when onoffis 0, normal runtime error handling reports the exceptioncondition.shutdown()int shutdown(s, how)int s;int how;ParametershowDescriptionSpecifies the socket descriptor.Specifies the condition of the shutdown. The values 0, 1, or 2 setthe condition.Description: The shutdown() call shuts down all or part of a duplex connection.The how parameter sets the condition for shutting down the connection to socket s.how can have a value of 0, 1, or 2, where:Chapter 2. C Sockets Application Program Interface 81


shutdown()socket()v 0 ends communication from socket s.v 1 ends communication to socket s.v 2 ends communication both to and from socket s.Return Values: The value 0 indicates success; the value −1 indicates an error. Thevalue of errno indicates the specific error.Errno Value DescriptionEBADF Indicates that s is not a valid socket descriptor.EINVALIndicates that the how parameter was not set to one of the validvalues. Valid values are 0, 1, and 2.See Also: accept(), close(), connect(), socket().#include #include int socket(domain, type, protocol)int domain;int type;int protocol;ParameterdomainDescriptionSpecifies the address domain requested. It is either AF_INET orAF_IUCV.typeSpecifies the type of socket created, either SOCK_STREAM,SOCK_DGRAM, or SOCK_RAW.protocol Specifies the protocol requested. Some possible values are 0,<strong>IP</strong>PROTO_UDP, or <strong>IP</strong>PROTO_<strong>TCP</strong>.Description: The socket() call creates an endpoint for communication and returns asocket descriptor representing the endpoint. Different types of sockets providedifferent communication services.The domain parameter specifies a communications domain within whichcommunication is to take place. This parameter selects the address family (formatof addresses within a domain) which is used. The families supported are AF_INET,which is the internet domain and AF_IUCV, which is the IUCV domain. Theseconstants are defined in the SOCKET.H header file.The type parameter specifies the type of socket created. The type is analogous withthe semantics of the communication requested. These socket type constants aredefined in the SOCKET.H header file. The types supported are:Socket TypeDescriptionSOCK_STREAMSOCK_DGRAMProvides sequenced, two-way byte streams that arereliable and connection-oriented. They support amechanism for out-of-band data. This type issupported in both the AF_INET and AF_IUCVdomains.Provides datagrams, which are connectionless82 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


socket()SOCK_RAWmessages of a fixed maximum length whosereliability is not guaranteed. Datagrams can becorrupted, received out of order, lost, or deliveredmultiple times. This type is supported in only theAF_INET domain.Provides the interface to internal protocols (such as<strong>IP</strong> and ICMP). This type is supported in only theAF_INET domain.The protocol parameter specifies a particular protocol to be used with the socket. Inmost cases, a single protocol exists to support a particular type of socket in aparticular addressing family (not true with raw sockets). If the protocol field is setto 0, the system selects the default protocol number for the domain and sockettype requested. Protocol numbers are found in the ETC PROTO file. Alternatively,the getprotobyname call can be used to get the protocol number for a protocol with aknown name. The protocol field must be set to 0, if the domain parameter is set toAF_IUCV. Currently, protocol defaults are <strong>TCP</strong> for stream sockets and UDP fordatagram sockets. There is no default for raw sockets.SOCK_STREAMStream sockets model duplex byte streams. They provide reliable, flow-controlledconnections between peer applications. Stream sockets are either active or passive.Active sockets are used by clients who initiate connection requests with connect().By default, socket() creates active sockets. Passive sockets are used by servers toaccept connection requests with the connect() call. An active socket is transformedinto a passive socket by binding a name to the socket with the bind() call and byindicating a willingness to accept connections with the listen() call. Once a socket ispassive, it cannot be used to initiate connection requests.In the AF_INET domain, the bind() call applied to a stream socket lets theapplication specify the networks from which it is willing to accept connectionrequests. The application can fully specify the network interface by setting theinternet address field in the address structure to the internet address of a networkinterface. Alternatively, the application can use a wildcard to specify that it wants toreceive connection requests from any network. This is done by setting the internetaddress field in the address structure to the constant INADDR_ANY as defined inthe SOCKET.H header file.Once a connection has been established between stream sockets, any of the datatransfer calls can be used (read(), write(), send(), recv(), readv(), writev(), sendto(),recvfrom(), sendmsg(), recvmsg()). Usually, the read-write or send-recv pairs areused for sending data on stream sockets. If out-of-band data is to be exchanged,the send-recv pair is normally used.SOCK_DGRAMDatagram sockets model datagrams. They provide connectionless messageexchange with no guarantees on reliability. Messages sent have a maximum size.Datagram sockets are not supported in the AF_IUCV domain.There is no active or passive analogy to stream sockets with datagram sockets.Servers must still call bind() to name a socket and to specify from which networkinterfaces it wishes to receive packets. Wildcard addressing, as described for streamsockets, applies for datagram sockets also. Because datagram sockets areconnectionless, the listen() call has no meaning for them and must not be usedwith them.Chapter 2. C Sockets Application Program Interface 83


socket()Once an application has received a datagram socket it can exchange datagramsusing the sendto() and recvfrom() or sendmsg() and recvmsg() calls. If theapplication goes one step further by calling connect() and fully specifying thename of the peer with which all messages will be exchanged, then the other datatransfer calls read(), write(), readv(), writev(), send(), recv() can also be used. Formore information on placing a socket into the connected state see “connect()” onpage 27 .|||Datagram sockets allow messages to be broadcast to multiple recipients. Setting thedestination address to be a broadcast address is network interface dependent(depends on class of address and whether sub-nets are being used). The constantINADDR_BROADCAST, defined in socket.h, can be used to broadcast to theprimary network if the primary network configured supports broadcast. Datagramsockets allow messages to be multicast by setting the destination address to amulticast address.SOCK_RAWRaw sockets give the application an interface to lower layer protocols, such as <strong>IP</strong>and ICMP. This interface is often used to bypass the transport layer when directaccess to lower layer protocols is needed. Raw sockets are also used to test newprotocols. Raw sockets are not supported in the AF_IUCV domain.Raw sockets are connectionless and data transfer semantics are the same as thosedescribed previously for datagram sockets. The connect call can be used similarly tospecify the peer.Outgoing packets have an <strong>IP</strong> header prefixed to them. <strong>IP</strong> options can be set andinspected using the setsockopt() and getsockopt() calls respectively. Incomingpackets are received with the <strong>IP</strong> header and options intact.Sockets are deallocated with the close() call.||Raw sockets allow messages to be multicast by setting the destination address to amulticast address.Note: When you use only AF_IUCV sockets and no AF_INET sockets, you need torun SET TIMER REAL on pre-<strong>VM</strong>/XA SP systems.The following limitations apply:v Only SOCK_STREAM sockets are supported in the AF_IUCV domain.v The setsockopt() and getsockopt() calls are not supported for sockets in theAF_IUCV domain.v The flags field in the send(), recv(), sendto(), recvfrom(), sendmsg(), recvmsg()calls is not supported in the AF_IUCV domain.Return Values: A nonnegative socket descriptor indicates success. The value −1indicates an error. The value of errno indicates the specific error.||Errno ValueE<strong>IBM</strong>IUCVERREMFILEDescriptionIndicates that an IUCV error occurred.Indicates that the socket descriptor table is alreadyfull.84 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


socket()EPROTONOSUPPORTIndicates that the protocol is not supported in thisdomain or this protocol is not supported for thissocket type.Examples:takesocket()The following are examples of the socket() call.int s;struct protoent *p;struct protoent *getprotobyname(char *name);int socket(int domain, int type, int protocol);./* Get stream socket in internet domain with default protocol */s = socket(AF_INET, SOCK_STREAM, 0);./* Get stream socket in iucv domain with default protocol */s = socket(AF_IUCV, SOCK_STREAM, 0);./* Get raw socket in internet domain for ICMP protocol */p = getprotobyname(“iucv”);s = socket(AF_INET, SOCK_RAW, p->p_proto);See Also: accept(), bind(), close() connect(), fcntl(), getprotobyname(),getsockname(), getsockopt(), ioctl(), maxdesc(), read(), readv(), recv(), recvfrom(),recvmsg(), select(), selectex(), send(), sendmsg(), sendto(), shutdown(), write(),writev().#include #include int takesocket(clientid, hisdesc)struct clientid *clientid;int hisdesc;ParameterclientidhisdescDescriptionPoints to the clientid of the application from whom you are takinga socket.Specifies the descriptor of the socket to be taken.Description: The takesocket() call acquires a socket from another program. Yourprogram obtains the other program’s client ID and socket descriptor through yourprogram’s startup parameter list. After successfully calling takesocket(), yourapplication uses an agreed-upon mechanism to signal the other application so thatit can close the socket.Typically, takesocket() is used by an agent program that handles one socket at atime, taking its sockets from a master program that obtains them by means of theaccept() call.Return Values: A nonnegative socket descriptor indicates success. The value −1indicates an error. The value of errno indicates a specific error.Errno Value DescriptionEACCESIndicates that the other application did not give the socket to yourapplication.Chapter 2. C Sockets Application Program Interface 85


takesocket()EBADFtcperror()EFAULTEINVALEMFILEENOBUFSIndicates that the hisdesc parameter does not specify a valid socketdescriptor owned by the other application. The socket has alreadybeen taken.Indicates that using the clientid parameter as specified would resultin an attempt to access storage outside the caller’s virtual storage.Indicates that the clientid parameter does not specify a valid clientidentifier.Indicates that the socket descriptor table is already full.Indicates that the operation cannot be performed because of theshortage of SCB or SKCB control blocks in the <strong>TCP</strong><strong>IP</strong> virtualmachine.EPFNOSUPPORTIndicates that the domain field of the clientid parameter is notAF_INET.See Also: getclientid(), givesocket().#include void tcperror(s)char *s;ParametersDescriptionSpecifies a NULL or NULL-terminated character string.Description: When a socket call produces an error, the call returns a negative valueand the variable errno is set to an error value found in the <strong>TCP</strong>ERRNO.H headerfile. The tcperror() call prints a short error message describing the last error thatoccurred. If s is non-NULL, tcperror() prints the string s followed by a colon,followed by a space, followed by the error message, and terminated with anew-line character. If s is NULL or points to a NULL string, just the error messageand the new-line character are output.The error messages printed by tcperror() are stored in an array of strings calledtcp_errlist. The entry tcp_errlist [errno] is the message that tcperror() prints.The tcperror() function is equivalent to the perror() function in UNIX ® .Return Values: None.Examples:The following are examples of the tcperror() call.Example 1if ((s=socket(AF_INET, SOCK_DGRAM, 0)) < 0) {tcperror(“socket()”);exit(2);}If the socket() call produces the error ENOMEM, socket() returns a negative valueand errno is set to ENOMEM. When tcperror() is called, it prints the string:socket(): not enough memory (ENOMEM)86 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


tcperror()Example 2if ((s=socket(AF_INET, SOCK_DGRAM, 0)) < 0)tcperror(NULL);If the socket() call produces the error enomem, socket() returns a negative valueand errno is set to ENOMEM. When tcperror() is called, it prints the string:Not enough memory (ENOMEM)Example 3if ((s=socket(AF_INET, SOCK_DGRAM, 0)) < 0){printf(“error creating socket s: %s\n”, tcp_errlist [errno]);exit(1);}If the socket() call produces the error ENOMEM, socket() returns a negative valueand errno is set to enomem. The program then prints:error creating socket s: not enough memory (ENOMEM)write()int write(s, buf, len)int s;char *buf;int len;ParametersbuflenDescriptionSpecifies the socket descriptor.Points to the buffer holding the data to be written.Specifies the length in bytes of the buffer pointed to by the bufparameter.Description: The write() call writes data on a socket with descriptor s. The write()call applies only to connected sockets.This call writes up to len bytes of data. If writing the number of bytes requested isnot possible, the call waits for writing to be possible. This blocks the caller, unlessthe socket is in nonblocking mode. See “ioctl()” on page 54 or “fcntl()” on page 31for a description of how to set nonblocking mode.Return Values: If successful, the number of bytes written is returned. The value −1indicates an error. The value of errno indicates the specific error.Errno ValueDescriptionEBADFIndicates that s is not a valid socket descriptor.EFAULTENOBUFSEWOULDBLOCKIndicates that using the buf and len parameterswould result in an attempt to access memoryoutside the caller’s virtual storage.Indicates that no buffer space is available to sendthe message.Indicates that s is in nonblocking mode, and nodata is available to read.Chapter 2. C Sockets Application Program Interface 87


write()writev()See Also: connect(), fcntl(), getsockopt(), ioctl(), read(), readv() recv(), recvfrom(),recvmsg(), select(), selectex(), send(), sendmsg(), sendto(), setsockopt(), socket(),writev().#include #include int writev(s, iov, iovcnt)int s;struc iovec *iov;int iovcnt;ParametersioviovcntDescriptionSpecifies the socket descriptor.Points to an array of iovec buffers.Specifies the number of buffers pointed to by the iov parameter.Description: The writev() call writes data on a socket with descriptor s. The data isgathered from the buffers specified by iov[0]...iov[iovcnt−1]. The iovec structure isdefined in uio.h and contains the following fields:Element Descriptioniov_base Points to the buffer.iov_len Specifies the length of the buffer.The writev() call applies only to connected sockets.This call writes len bytes of data. If it is not possible to write the number of bytesrequested, the writev() call waits for the ability to write. This blocks the caller,unless the socket is in nonblocking mode. See “fcntl()” on page 31 or “ioctl()” onpage 54 for a description of how to set nonblocking mode.Return Values: If successful, the number of bytes written from the buffer(s) isreturned. The value −1 indicates an error. The value of errno indicates the specificerror.Errno ValueDescriptionEBADFIndicates that s is not a valid socket descriptor.EFAULTENOBUFSEWOULDBLOCKIndicates that using the iov and iovcnt parameterswould result in an attempt to access memoryoutside the caller’s virtual storage.Indicates that no buffer space is available to sendthe message.Indicates that s is in nonblocking mode, and nodata is available to read.See Also: connect(), fcntl(), getsockopt(), ioctl(), write(), read(), readv(), recv(),recvmsg(), recvfrom(), select(), selectex(), send(), sendmsg(), sendto(), setsockopt(),socket(), write().88 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Sample C Socket ProgramsSample C Socket ProgramsC Socket <strong>TCP</strong> ClientThis section provides examples of the following programs:v C socket <strong>TCP</strong> client (see topic 89)v C socket <strong>TCP</strong> server (see topic 90)v C socket UDP server (see topic 92)v C socket UDP client (see topic 93)The following is an example of a C socket <strong>TCP</strong> client program./** Include Files.*/#define <strong>VM</strong>#include #include #include #include #include #include /** Client Main.*/main(argc, argv)int argc;char **argv;{unsigned short port; /* port client will connect to */char buf[12]; /*data buffer for sending and receiving */struct hostent *hostnm; /*server host name information */struct sockaddr_in server; /*server address */int s; /* client socket *//** Check Arguments Passed. Should be hostname and port.*/if (argc != 3){fprintf(stderr, “Usage: %shostname port\n”, argv[0]);exit(-1);}/** The host name is the first argument. Get the server address.*/hostnm = gethostbyname(argv[1]);if (hostnm == (struct hostent *) 0){fprintf(stderr, “Gethostbynamefailed\n”);exit(-1);}/** The port is the second argument.*/port = (unsigned short) atoi(argv[2]);/** Put a message into the buffer.*/strcpy(buf, “the message”);Chapter 2. C Sockets Application Program Interface 89


C Socket <strong>TCP</strong> Client/** Put the server information into the server structure.* The port must be put into network byte order.*/server.sin_family = AF_INET;server.sin_port = htons(port);server.sin_addr.s_addr = *((unsigned long *)hostnm->h_addr);/** Get a stream socket.*/if ((s = socket(AF_INET,SOCK_STREAM, 0)) < 0){tcperror(“Socket()”);exit(-1);}/** Connect to the server.*/if (connect(s, &server, sizeof(server)) < 0){tcperror(“Connect()”);exit(-1);}if (send(s, buf, sizeof(buf), 0) < 0){tcperror(“Send()”);exit(-1);}/** The server sends back the same message. Receive it into the buffer.*/if (recv(s, buf, sizeof(buf), 0) < 0){tcperror(“Recv()”);exit(-1);}/** Close the socket.*/close(s);printf(“Client Ended Successfully\n”);exit(0);C Socket <strong>TCP</strong> Server}The following is an example of a C socket <strong>TCP</strong> server program./** Include Files.*/#define <strong>VM</strong>#include #include #include #include #include /*90 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


* Server Main.*/main(argc, argv)int argc;char **argv;{unsigned short port; /*port server binds to */char buf[12]; /*buffer for sending and receiving data */struct sockaddr_in client; /*client address information */struct sockaddr_in server; /*server address information */int s; /*socket for accepting connections */int ns; /*socket connected to client */int namelen; /*length of client name *//** Check arguments. Should be onlyone: the port number to bind to.*/if (argc != 2){fprintf(stderr, “Usage:%s port\n”, argv[0]);exit(-1);}/** First argument should be the port.*/port = (unsigned short)atoi(argv[1]);/** Get a socket for accepting connections.*/if ((s = socket(AF_INET,SOCK_STREAM, 0)) < 0){tcperror(“Socket()”);exit(-1);}/** Bind the socket to the server address.*/server.sin_family = AF_INET;server.sin_port = htons(port);server.sin_addr.s_addr = INADDR_ANY;if (bind(s, &server, sizeof(server)) < 0){tcperror(“Bind()”);exit(-1);}/** Listen for connections. Specify the backlog as 1.*/if (listen(s, 1) != 0){tcperror(“Listen()”);exit(-1);}/** Accept a connection.*/namelen = sizeof(client);if ((ns = accept(s, &client,&namelen)) == -1){tcperror(“Accept()”);exit(-1);C Socket <strong>TCP</strong> ServerChapter 2. C Sockets Application Program Interface 91


C Socket <strong>TCP</strong> Server}/** Receive the message on the newly connected socket.*/if (recv(ns, buf, sizeof(buf),0) == -1){tcperror(“Recv()”);exit(-1);}/** Send the message back to the client.*/if (send(ns, buf, sizeof(buf),0) < 0){tcperror(“Send()”);exit(-1);}close(ns);close(s);}printf(“Server ended successfully\n”);exit(0);C Socket UDP ServerThe following is an example of a C socket UDP server program.#include #include #include #include #include #include main(){int s, namelen, client_address_size;struct sockaddr_in client, server;char buff[32];/** Create a datagram socket in the internet domain and use the* default protocol (UDP).*/if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0){perror("socket()");exit(1);}/** Bind my name to this socket so that clients on the network can* send me messages. (This allows the operating system to demultiplex* messages and get them to the correct server)** Set up the server name. The internet address is specified as the* wildcard INADDR_ANY so that the server can get messages from any* of the physical internet connections on this host. (Otherwise we* would limit the server to messages from only one network* interface.)*/server.sin_family = AF_INET; /* Server is in Internet Domain */server.sin_port = 0; /* Use any available port */92 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


server.sin_addr.s_addr = INADDR_ANY;/* Server’s Internet Address */if (bind(s, &server, sizeof(server)) < 0){perror("bind()");exit(2);}/* Find out what port was really assigned and print it */namelen = sizeof(server);if (getsockname(s, (struct sockaddr *) &server, &namelen) < 0){perror("getsockname()");exit(3);}printf("Port assigned is %d\n", ntohs(server.sin_port));/** Receive a message on socket s in buf of maximum size 32* from a client. Because the last two paramters* are not null, the name of the client will be placed into the* client data structure and the size of the client address will* be placed into client_address_size.*/client_address_size = sizeof(client);if(recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *) &client,&client_address_size)


C Socket UDP Clientint argc;char **argv;{int s;unsigned short port;struct sockaddr_in server;char buff[32];/* argv[1] is internet address of server argv[2] is port of server.* Convert the port from ascii to integer and then from host byte* order to network byte order.*/if(argc != 3){printf("Usage: %s \n",argv[0]);exit(1);}port = htons(atoi(argv[2]));9/* Create a datagram socket in the internet domain and use the* default protocol (UDP).*/if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0){perror("socket()");exit(1);}/* Set up the server name */server.sin_family = AF_INET; /* Internet Domain */server.sin_port = port; /* Server Port */server.sin_addr.s_addr = inet_addr(argv[1]); /* Server’s Address */strcpy(buf, "Hello");/* Send the message in buf to the server */if (sendto(s, buf, (strlen(buf)+1), 0, &server, sizeof(server)) < 0){perror("sendto()");exit(2);}}/* Deallocate the socket */close(s);94 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language)Software RequirementsThis chapter describes the Pascal language application program interface (API)provided with <strong>TCP</strong>/<strong>IP</strong> Level 320 for <strong>VM</strong>. This interface allows programmers towrite application programs that use the <strong>TCP</strong>, UDP, and <strong>IP</strong> layers of the <strong>TCP</strong>/<strong>IP</strong>protocol suite.You should have experience in Pascal language programming and be familiar withthe principles of internetwork communication to use the Pascal language API.Your program uses procedure calls to initiate communication with the <strong>TCP</strong><strong>IP</strong>virtual machine. Most of these procedure calls return with a code that indicatessuccess, or the type of failure incurred by the call. The <strong>TCP</strong><strong>IP</strong> virtual machinestarts asynchronous communication by sending you notifications.The general sequence of operations is:1. Start <strong>TCP</strong>/UDP/<strong>IP</strong> service (BeginTcpIp, StartTcpNotice).2. Specify the set of notifications that <strong>TCP</strong>/UDP/<strong>IP</strong> may send you (Handle).3. Establish a connection (TcpOpen, UdpOpen, RawIpOpen, TcpWaitOpen).If using TcpOpen, you must wait for the appropriate notification that aconnection has been established.4. Transfer data buffer to or from the <strong>TCP</strong><strong>IP</strong> virtual machine (TcpSend, TcpFSend,TcpWaitSend, TcpReceive, TcpFReceive, TcpWaitReceive, UdpSend,UdpNReceive, RawIpSend, RawIpReceive).Note: TcpWaitReceive and TcpWaitSend are synchronous calls.5. Check the status returned from the <strong>TCP</strong><strong>IP</strong> virtual machine in the form ofnotifications (GetNextNote).6. Repeat the data transfer operations (steps 4 and 5) until the data is exhausted.7. Terminate the connection (TcpClose, UdpClose, RawIpClose).If using TcpClose, you must wait for the connection to terminate.8. Terminate the communication service (EndTcpIp).Control is returned to you, in most instances, after the initiation of your request.When appropriate, some procedures have alternative wait versions that return onlyafter completion of the request. The bodies of the Pascal procedures are in the<strong>TCP</strong><strong>IP</strong> A<strong>TCP</strong>PSRC file.A sample program is supplied with the <strong>TCP</strong>/<strong>IP</strong> program, see “Sample PascalProgram” on page 143.To develop programs in Pascal that interface directly to the <strong>TCP</strong>, UDP, and <strong>IP</strong>protocol boundaries, you require the <strong>IBM</strong> VS Pascal Compiler & Library (5668-767).© Copyright <strong>IBM</strong> Corp. 1987, 2001 95


Pascal LanguageData StructuresPrograms containing Pascal language API calls must include the appropriate datastructures. The data structures are declared in the CMCOMM COPY andCMCLIEN COPY. The CMCOMM and CMCLIEN are included in the ALLMACROMACLIB shipped with <strong>TCP</strong>/<strong>IP</strong>. To include these files in your program source,enter:%include CMCOMM%include CMCLIENAdditional include statements are required in programs that use certain calls. Thefollowing list shows the members of the ALLMACRO MACLIB that need to beincluded for the various calls.v CMRESGLB for GetHostResolv CMINTER for GetHostNumber, GetHostString, IsLocalAddress, and IsLocalHost.The load modules are in the <strong>TCP</strong><strong>IP</strong> COMMTXT file. Include this file in yourGLOBAL TXTLIB command when you are creating a load module to link anapplication program.Connection StateConnectionState is the current state of the connection. For the Pascal declaration ofthe ConnectionStateType data type, see Figure 14. ConnectionStateType is used inStatusInfoType and NotificationInfoType. It defines the client program’s view ofthe state of a <strong>TCP</strong> connection, in a form more readily usable than the formal <strong>TCP</strong>connection state defined by RFC 793. For the mapping between <strong>TCP</strong> states andConnectionStateType, see Table 3 on page 97.ConnectionStateType =(CONNECTIONclosing,LISTENING,NONEXISTENT,OPEN,RECEIVINGonly,SENDINGonly,TRYINGtoOPEN);Figure 14. Pascal Declaration of Connection State TypeCONNECTIONclosingIndicates that no more data can be transmitted on this connection, becauseit is going through the <strong>TCP</strong> connection closing sequence.LISTENINGIndicates that you are waiting for a foreign site to open a connection.NONEXISTENTIndicates that a connection no longer exists.OPENIndicates that data can go either way on the connection.RECEIVINGonlyIndicates that data can be received, but cannot be sent on this connection,because the client has done a TcpClose.96 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Pascal LanguageSENDINGonlyIndicates that data can be sent out, but cannot be received on thisconnection, because the foreign application has done a TcpClose orequivalent.TRYINGtoOPENIndicates that you are trying to contact a foreign site to establish aconnection.Table 3. <strong>TCP</strong> Connection States<strong>TCP</strong> StateCLOSEDLAST-ACK, CLOSING, TIME-WAITCLOSE-WAITESTABLISHEDFIN-WAIT-1, FIN-WAIT-2LISTENSYN-SENT, SYN-RECEIVEDConnectionStateTypeNONEXISTENTIf there is incoming data that the client program hasnot received, then RECEIVINGonly, elseCONNECTIONclosing.If there is incoming data that the client program hasnot received, then OPEN, else SENDINGonly.OPENRECEIVINGonlyLISTENINGTRYINGtoOPENConnection Information RecordThe connection information record is used as a parameter in several of theprocedure calls. It enables you and the <strong>TCP</strong>/<strong>IP</strong> program to exchange informationabout the connection. The Pascal declaration is shown in Figure 15. For moreinformation about the use of each field, see “TcpOpen and TcpWaitOpen” onpage 134 and “TcpStatus” on page 137StatusInfoType =recordConnection: ConnectionType;OpenAttemptTimeout: integer;Security: SecurityType;Compartment: CompartmentType;Precedence: PrecedenceType;BytesToRead: integer;UnackedBytes: integer;ConnectionState: ConnectionStateType;LocalSocket: SocketType;ForeignSocket: SocketType;end;Figure 15. Pascal Declaration of Connection Information RecordConnectionSpecifies a number identifying the connection that is described. Thisconnection number is different from the connection number displayed bythe NETSTAT command. For more information about the NETSTATcommand, see <strong>TCP</strong>/<strong>IP</strong> User’s Guide.OpenAttemptTimeoutSpecifies the number of seconds that <strong>TCP</strong> continues to attempt to open aChapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 97


Pascal Languageconnection. You specify this number. If the limit is exceeded, <strong>TCP</strong> stopstrying to open the connection and shuts down any partially openconnection.Security, Compartment, PrecedenceSpecifies entries used only when working within a multilevel secureenvironment.BytesToReadSpecifies the number of data bytes received from the foreign host by <strong>TCP</strong>,but not yet delivered to the client. <strong>TCP</strong> maintains this value.UnackedBytesSpecifies the number of bytes sent by your program, but not yet sent to theforeign <strong>TCP</strong>, or the number of bytes sent to the foreign <strong>TCP</strong>, but not yetacknowledged.LocalSocketSpecifies the local internet address and local port. Together, these form oneend of a connection. The foreign socket forms the other end. For the Pascaldeclaration of the SocketType record, see Figure 16.ForeignSocketSpecifies the foreign, or remote, internet address and its associated port.These form one end of a connection. The local socket forms the other end.Socket RecordInternetAddressType = UnsignedIntegerType;PortType = UnsignedHalfWordType;SocketType =recordAddress: InternetAddressType;Port: PortType;end;Figure 16. Pascal Declaration of Socket TypeFieldAddressPortDescriptionSpecifies the internet address.Specifies the port.Notification RecordThe notification record is used to provide event information. You receive thisinformation by using the GetNextNote call. For more information, see“GetNextNote” on page 113. It is a variant record; the number of fields isdependent on the type of notification. For the Pascal declaration of this record. seeFigure 17 on page 99.98 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Pascal LanguageNotificationInfoType =recordConnection: ConnectionType;Protocol: ProtocolType;case NotificationTag: NotificationEnumType ofBUFFERspaceAVAILABLE:(AmountOfSpaceInBytes: integer);CONNECTIONstateCHANGED:(NewState: ConnectionStateType;Reason: CallReturnCodeType);DATAdelivered:(BytesDelivered: integer;LastUrgentByte: integer;PushFlag: Boolean);EXTERNALinterrupt:(RuptCode: integer);FRECEIVEerror:(ReceiveTurnCode: CallReturnCodeType;ReceiveRequestErr: Boolean;);FSENDresponse:(SendTurnCode: CallReturnCodeType;SendRequestErr: Boolean;);IOinterrupt:(DeviceAddress: integer;UnitStatus: UnsignedByteType;ChannelStatus: UnsignedByteType);IUCVinterrupt:(IUCVResponseBuf: IUCVBufferType);PINGresponse:(PingTurnCode: CallReturnCodeType;ElapsedTime: TimeStampType);Figure 17. Notification Record (Part 1 of 2)Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 99


Pascal LanguageRAW<strong>IP</strong>packetsDELIVERED:(RawIpDataLength: integer;RawIpFullLength: integer;);RAW<strong>IP</strong>spaceAVAILABLE:(RawIpSpaceInBytes: integer;);RESOURCESavailable: ();SMSGreceived: ();TIMERexpired:(Datum: integer;AssociatedTimer: TimerPointerType);UDPdatagramDELIVERED:(DataLength: integer;ForeignSocket: SocketType;FullLength: integer);UDPdatagramSPACEavailable: ();UDPresourcesAVAILABLE: ();URGENTpending:(BytesToRead: integer;UrgentSpan: integer);USERdefinedNOTIFICATION:(UserData: UserNotificationDataType);end;Figure 17. Notification Record (Part 2 of 2)ConnectionIndicates the client’s connection number to which the notification applies.In the case of USERdefinedNOTIFICATION, this field is as supplied by theuser in the AddUserNote call.ProtocolIn the case of USERdefinedNOTIFICATION, this field is as supplied by theuser in the AddUserNote call. For all other notifications, this field isreserved.NotificationTagIs the type of notification being sent, and a set of fields dependent on thevalue of the tag. Possible tag values relevant to the <strong>TCP</strong>/UDP/<strong>IP</strong> interfaceand the corresponding fields are:BUFFERspaceAVAILABLENotification given when space becomes available on a connectionfor which TcpSend previously returned NObufferSPACE. For moreinformation about these procedures, see “TcpFSend, TcpSend, andTcpWaitSend” on page 131.AmountOfSpaceInBytesIndicates the minimum number of bytes that the <strong>TCP</strong>/<strong>IP</strong>service has available for buffer space for this connection.The actual amount of buffer space might be more than thisnumber.100 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Pascal LanguageCONNECTIONstateCHANGEDIndicates that a <strong>TCP</strong> connection has changed state.NewStateIndicates the new state for this connection.ReasonIndicates the reason for the state change. This field ismeaningful only if the NewState field has a value ofNONEXISTENT.Notes:1. The following is the sequence of state notifications for aconnection.For active open:– OPEN– RECEIVINGonly or SENDINGonly– CONNECTIONclosing– NONEXISTENT.For passive open:– TRYINGtoOPEN– OPEN– RECEIVINGonly or SENDINGonly– CONNECTIONclosing– NONEXISTENT.Your program should be prepared for any intermediate step orsteps to be skipped.2. The normal <strong>TCP</strong> connection closing sequence can lead to aconnection staying in CONNECTIONclosing state for up to twominutes, corresponding to the <strong>TCP</strong> state TIME-WAIT.3. Possible Reason codes giving the reason for a connectionchanging to NONEXISTENT are:v OK (means normal closing)v UNREACHABLEnetworkv TIMEOUTopenv OPENrejectedv REMOTEresetv WRONGsecORprcv UNEXPECTEDsynv FATALerrorv KILLEDbyCLIENTv TIMEOUTconnectionv <strong>TCP</strong>ipSHUTDOWNv DROPPEDbyOPERATOR.DATAdeliveredNotification given when your buffer (named in an earlierTcpReceive or TcpFReceive request) contains data.Note: The data delivered should be treated as part of abyte-stream, not as a message. There is no guarantee that thedata sent in one TcpSend (or equivalent) call on the foreignhost is delivered in a single DATAdelivered notification,even if the PushFlag is set.Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 101


Pascal LanguageBytesDeliveredIndicates the number of bytes of data delivered toyou.LastUrgentByteIndicates the number of bytes of urgent dataremaining, including data just delivered.PushFlagTRUE if the last byte of data was received with thepush bit set.EXTERNALinterruptNotification given when a simulated external interrupt occurs inyour virtual machine. The Connection and Protocol fields are notapplicable.RuptCodeThe interrupt type.FRECEIVEerrorNotification given in place of DATAdelivered when a TcpFReceivethat initially returned OK has terminated without delivering data.ReceiveTurnCodeSpecifies the reason the TcpFReceive has failed or wascanceled. If ReceiveRequestErr is set to FALSE,ReceiveTurnCode contains the same reason as the Reasonfield in the CONNECTIONstateCHANGED with NewStateset to NONEXISTENT notification for this connection (see2 on page 101). ReceiveTurnCode could be OK, if theconnection closed normally.ReceiveRequestErrIf TRUE, the TcpFReceive was rejected during initialprocessing. If FALSE, the TcpFReceive was initiallyaccepted, but was terminated because of connectionclosing.Note: Normally, you do not need to take any action upon receiptof this notification with ReceiveRequestErr set to FALSE,because your program receives aCONNECTIONstateCHANGED notification informing it thatthe connection has been terminated.FSENDresponseNotification given when a TcpFSend request is completed,successfully or unsuccessfully.SendTurnCodeIndicates the status of the send operation.SendRequestErrIf TRUE, the TcpFSend was rejected during initial processingor during retry after buffer space became available. IfFALSE, the TcpFSend was canceled because of connectionclosing.102 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Pascal LanguageIOinterruptNotification given when a simulated I/O interrupt occurs in yourvirtual machine. The Connection and Protocol fields are notapplicable.DeviceAddressThis address corresponds to the DEVICE statement.UnitStatusSpecifies the status returned by the device.ChannelStatusSpecifies the status returned by the channel.IUCVinterruptNotification given when a simulated IUCV interrupt occurs in yourvirtual machine. The Connection and Protocol fields are notapplicable.IUCVResponseBufContains the information returned from the application.PINGresponseNotification given when a PINGresponse is received.PingTurnCodeSpecifies the status of the ping operation.ElapsedTimeIndicates the time elapsed between the sending of arequest and the reception of a response. This time does notinclude the time spent in the simulated Virtual MachineCommunication Facility (<strong>VM</strong>CF) communication betweenyour program and the <strong>TCP</strong><strong>IP</strong> virtual machine. This field isvalid only if PingTurnCode has a value of OK.RAW<strong>IP</strong>packetsDELIVEREDNotification given when your buffer (indicated in an earlierRawIpReceive request) contains a datagram. Only one datagram isdelivered on each notification. Your buffer contains the entire <strong>IP</strong>header, plus as much of the datagram as fits in your buffer.RawIpDataLengthSpecifies the actual data length delivered to your buffer. Ifthis is less than RawIpFullLength, the datagram wastruncated.RawIpFullLengthSpecifies the length of the packet, from the TotalLengthfield of the <strong>IP</strong> header.RAW<strong>IP</strong>spaceAVAILABLEWhen space becomes available after a client does a RawIpSend andreceives a NObufferSPACE return code, the client receives thisnotification to indicate that space is now available.RawIpSpaceInBytesSpecifies the amount of space available always equals themaximum size <strong>IP</strong> datagram.RESOURCESavailableNotice given when resources needed for a TcpOpen orChapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 103


Pascal LanguageTcpWaitOpen are available. This notification is sent only if aprevious TcpOpen or TcpWaitOpen returned ZEROresources.SMSGreceivedNotification given when one or more Special Messages (Smsgs)arrive. The GetSmsg call is used to retrieve queued Smsgs. Forinformation on the SMSG command, see <strong>TCP</strong>/<strong>IP</strong> User’s Guide.TIMERexpiredNotification given when a timer set through SetTimer expires.DatumIndicates the data specified when SetTimer was called.AssociatedTimerSpecifies the address of the timer that expired.UDPdatagramDELIVEREDNotification given when your buffer, indicated in an earlierUdpNReceive or UdpReceive request, contains a datagram. Yourbuffer contains the datagram excluding the UDP header.Note: If UdpReceive was used, your buffer contains the entiredatagram excluding the header, with the length indicated byDataLength. If UdpNReceive was used, and DataLength isless than FullLength, your buffer contains a truncateddatagram. The reason is that the length of your buffer wastoo small to contain the entire datagram.DataLengthSpecifies the length of the data delivered to yourbuffer.ForeignSocketSpecifies the source of the datagram.FullLengthSpecifies the length of the entire datagram,excluding the UDP header. This field is set only ifUdpNReceive was used.UDPdatagramSPACEavailableNotification given when buffer space becomes available for adatagram for which UdpSend previously returned NObufferSPACEbecause of insufficient resources.UDPresourcesAVAILABLENotice given when resources needed for a UdpOpen are available.This notification is sent only if a previous UdpOpen returnedUDPzeroRESOURCES.URGENTpendingNotification given when there is urgent data pending on a <strong>TCP</strong>connection.BytesToReadIndicates the number of incoming bytes not yet deliveredto the client.104 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


UrgentSpanIndicates the number of undelivered bytes to the lastknown urgent pointer. No urgent data is pending if this isnegative.USERdefinedNOTIFICATIONNotice generated from data passed to AddUserNote by yourprogram.UserDataA 40-byte field supplied by your program throughAddUserNote. The Connection and Protocol fields are alsoset from the values supplied to AddUserNote.File Specification RecordThe file specification record is used to fully specify a file. The Pascal declaration isshown in Figure 18.SpecOfFileType =recordOwner: DirectoryNameType;Case SpecOfSystemType of<strong>VM</strong>:(VirtualAddress:VirtualAddressType;NewVirtualAddress:VirtualAddressType;DiskPassword: DirectoryNameType;Filename: DirectoryNameType;Filetype: DirectoryNameType;Filemode: FilemodeType);MVS:((* The MVS declaration is listed here. *));end;Pascal LanguageUsing Procedure CallsFigure 18. Pascal Declaration of File Specification RecordYour program uses procedure calls to initiate communication with the <strong>TCP</strong><strong>IP</strong>virtual machine. Most of these procedure calls return with a code, which indicatessuccess or the type of failure incurred by the call. For an explanation of the returncodes, see Table 86 on page 405.Before invoking any of the other interface procedures, use BeginTcpIp orStartTcpNotice to start up the <strong>TCP</strong>/UDP/<strong>IP</strong> service. Once the <strong>TCP</strong>/UDP/<strong>IP</strong>service has begun, use the Handle procedure to specify a set of notifications thatthe <strong>TCP</strong>/UDP/<strong>IP</strong> service can send you. To terminate the <strong>TCP</strong>/UDP/<strong>IP</strong> service, usethe EndTcpIp procedure.NotificationsThe <strong>TCP</strong><strong>IP</strong> virtual machine sends you notifications to inform you of asynchronousevents. Also, some notifications are generated in your virtual machine by the <strong>TCP</strong>interface. Notifications can be received only after BeginTcp or StartTcpNotice.Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 105


Pascal LanguageThe notifications are received by the <strong>TCP</strong> interface and kept in a queue. UseGetNextNote to get the next notification. The notifications are in Pascal variantrecord form. For more information, see Figure 17 on page 99.The following table provides a short description of the Notification procedure callsand gives the page number where each call’s detailed description is located.Table 4. Pascal Language Interface Summary—NotificationsProcedure Call Description PageGetNextNote Retrieves the next notification. 113HandleSpecifies the types of notifications that your program 114can process.NotifyIoRequests that an IOinterrupt notification be sent to youwhen an I/O interrupt occurs on a given virtualaddress.118UnhandleUnNotifyIoSpecifies notification types that your program can nolonger process.Indicates that you no longer wish to be sent anotification when an I/O interrupt occurs on a givenvirtual address.142142<strong>TCP</strong>/UDP Initialization ProceduresThe UDP initialization procedures affect all present and future connections. Usethese procedures to initialize the <strong>TCP</strong>/<strong>IP</strong> environment for your program.The following table provides a short description of the <strong>TCP</strong>/UDP Initializationprocedure calls and gives the page number where each call’s detailed description islocated.Table 5. Pascal Language Interface Summary—<strong>TCP</strong>/UDP InitializationProcedure Call Description PageTcpNameChangeIdentifies the name of the virtual machine running the<strong>TCP</strong>/<strong>IP</strong> program when the virtual machine has a nameother than <strong>TCP</strong><strong>IP</strong>.133BeginTcpIp Establishes communication with the <strong>TCP</strong>/<strong>IP</strong> services. 110StartTcpNotice Establishes communication with the <strong>TCP</strong>/<strong>IP</strong> services. 126<strong>TCP</strong>/UDP Termination ProcedureThe Pascal API has one termination procedure call. You should use the EndTcpIpcall when you have finished with the <strong>TCP</strong>/<strong>IP</strong> services.The following table provides a short description of the <strong>TCP</strong>/UDP Terminationprocedure call and gives the page number where the call’s detailed description islocated.Table 6. Pascal Language Interface Summary—<strong>TCP</strong>/UDP TerminationProcedure Call Description PageEndTcpIp Terminates communication with the <strong>TCP</strong>/<strong>IP</strong> services. 111106 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Handling External InterruptsThe handling external interrupts procedures allow you to pass simulated externalinterrupts to the <strong>TCP</strong> interface. You must call the StartTcpNotice initializationroutine before you can begin using the external interrupt calls.The following table provides a short description of the Handling ExternalInterrupts and gives the page number where each call’s detailed description islocated.Table 7. Pascal Language Interface Summary—Handling External InterruptsProcedure Call Description PageTcpExtRuptNotifies the <strong>TCP</strong> interface of the arrival of a simulated 128external interrupt.RTcpExtRupt A version of TcpExtRupt. 123TcpVmcfRuptNotifies the <strong>TCP</strong> interface of the arrival of a simulated 138external <strong>VM</strong>CF interrupt.RTcpVmcfRupt A version of TcpVmcfRupt. 123Pascal Language<strong>TCP</strong> Communication ProceduresThe <strong>TCP</strong> communication procedures apply to a particular client connection. Usethese procedures to establish a connection and to communicate. You must calleither the BeginTcpIp or the StartTcpNotice initialization routine before you canbegin using <strong>TCP</strong> communication procedures.The following table provides a short description of the <strong>TCP</strong> communicationprocedures and gives the page number where each call’s detailed description islocated.Table 8. Pascal Language Interface Summary—<strong>TCP</strong> Communication ProceduresProcedure Call Description PageTcpOpen Initiates a <strong>TCP</strong> connection. 134TcpWaitOpenInitiates a <strong>TCP</strong> connection and waits for the134establishment of the connection.TcpFSend Sends <strong>TCP</strong> data. 131TcpSend Sends <strong>TCP</strong> data. 131TcpWaitSend Sends <strong>TCP</strong> data and waits until <strong>TCP</strong><strong>IP</strong> accepts it. 131TcpFReceive Establishes a buffer to receive <strong>TCP</strong> data. 128TcpReceive Establishes a buffer to receive <strong>TCP</strong> data. 128TcpWaitReceiveEstablishes a buffer to receive <strong>TCP</strong> data and waits for 128the reception of the data.TcpClose Begins the <strong>TCP</strong> one-way closing sequence. 127TcpAbort Shuts down a <strong>TCP</strong> connection immediately. 127TcpStatus Obtains the current status of a <strong>TCP</strong> connection. 137Ping InterfaceThe Ping interface lets a client send an ICMP echo request to a foreign host. Youmust call either the BeginTcpIp or the StartTcpNotice initialization routine beforeyou can begin using the Ping Interface.Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 107


Pascal LanguageThe following table provides a short description of the Ping interface proceduresand gives the page number where each call’s detailed description is located.Table 9. Pascal Language Interface Summary—Ping InterfaceProcedure Call Description PagePingRequestSends an Internet Control Message Protocol (ICMP) echo 119request.Monitor ProceduresTwo monitor procedures, MonCommand and MonQuery, provide a mechanism forquerying and controlling the <strong>TCP</strong><strong>IP</strong> virtual machine.The following table provides a short description of the Monitor procedures andgives the page number where each call’s detailed description is located.Table 10. Pascal Language Interface Summary—Monitor ProceduresProcedure Call Description PageMonCommandInstructs <strong>TCP</strong> to read a specific file and execute the 116commands that it contains.MonQueryPerforms control functions and retrieves internal <strong>TCP</strong><strong>IP</strong>control blocks.117UDP Communication ProceduresThe UDP communication procedures describe the programming interface for theUser Datagram Protocol (UDP) provided in the <strong>TCP</strong>/<strong>IP</strong> product.The following table provides a short description of the UDP communicationprocedures and gives the page number where each call’s detailed description islocated.Table 11. Pascal Language Interface Summary—UDP Communication ProceduresProcedure Call Description PageUdpOpenRequests communication with UDP on a specified 139socket.UdpSend Sends a UDP datagram to a specified foreign socket. 141UdpNReceiveNotifies the <strong>TCP</strong><strong>IP</strong> virtual machine that you are willing 139to receive UDP datagram data.UdpReceiveNotifies the <strong>TCP</strong><strong>IP</strong> virtual machine that you are willing 140to receive UDP datagram data.UdpClose Terminates use of a UDP socket. 138Raw <strong>IP</strong> InterfaceThe Raw <strong>IP</strong> interface lets a client program send and receive arbitrary <strong>IP</strong> packets onany <strong>IP</strong> protocol except <strong>TCP</strong> and UDP. Only one client can use any given protocolat one time. Only clients in the obey list can use the Raw <strong>IP</strong> interface. For furtherinformation about the obey list, see <strong>TCP</strong>/<strong>IP</strong> Planning and Customization.The following table provides a short description of the Raw <strong>IP</strong> interface proceduresand gives the page number where each call’s detailed description is located.108 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Pascal LanguageTable 12. Pascal Language Interface Summary—Raw <strong>IP</strong> InterfaceProcedure Call Description PageRawIpOpenInforms the <strong>TCP</strong><strong>IP</strong> virtual machine that the client wants 120to send and receive <strong>IP</strong> packets of a specified protocol.RawIpReceiveSpecifies a buffer to receive raw <strong>IP</strong> packets of a specified 120protocol.RawIpSend Sends raw <strong>IP</strong> packets of a specified protocol. 121RawIpCloseInforms the <strong>TCP</strong><strong>IP</strong> virtual machine that the client nolonger handles the protocol.119Timer RoutinesThe timer routines are used with the <strong>TCP</strong>/UDP/<strong>IP</strong> interface. You must call eitherthe BeginTcpIp or the StartTcpNotice initialization routine before you can beginusing the timer routines.The following table provides a short description of the Timer routines and givesthe page number where each call’s detailed description is located.Table 13. Pascal Language Interface Summary—Timer RoutinesProcedure Call Description PageCreateTimer Allocates a timer. 111ClearTimer Resets a timer. 111SetTimer Sets a timer to expire after a specified interval. 126DestroyTimer Deallocates a timer. 111Host Lookup RoutinesThe host lookup routines (with the exception of GetHostResol ) are declared in theCMINTER member of the ALLMACRO MACLIB. The host lookup routineGetHostResol is declared in the CMRESGLB member of the ALLMACRO MACLIB.Any program using these procedures must include CMINTER or CMRESGLB afterthe include statements for CMCOMM and CMCLIEN.The following table provides a short description of the host lookup routines andgives the page number where each call’s detailed description is located.Table 14. Pascal Language Interface Summary—Host Lookup RoutinesProcedure Call Description PageGetHostNumberConverts a host name to an internet address using static 112tables.GetHostResolConverts a host name to an internet address using a 112domain name resolver.GetHostStringConverts an internet address to a host name using static 113tables.GetIdentity Returns environment information. 113IsLocalAddress Determines if an internet address is local. 115IsLocalHostDetermines if a host name is local, remote, loopback, orunknown.115Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 109


Pascal LanguageAddUserNoteThe AddUserNote procedure can be called to add a USERdefinedNOTIFICATIONnotification to the note queue and wake up GetNextNote if it is waiting for anotification. For more information, see “RTcpExtRupt” on page 123 and“RTcpVmcfRupt” on page 123.Other RoutinesThe following table provides a short description of these procedure calls and givesthe page number where the detailed description is located.Table 15. Pascal Language Interface Summary—Other RoutinesProcedure Call Description PageGetSmsg Retrieves one queued special message (Smsg). 114ReadXlateTable Reads a binary translation table file. 122SayCalRe Converts a return code into a descriptive message. 124SayConSt Converts a connection state into a descriptive message. 124SayIntAdConverts an internet address into a name or124dotted-decimal form.SayIntNumConverts an internet address into its dotted-decimal 125form.SayNotEnConverts a notification enumeration type into a 125descriptive message.SayPorTyConverts a port number into a descriptive message or 125into EBCDIC.SayProTyConverts the protocol type into a descriptive message or 125into EBCDIC.AddUserNoteAdds a USERdefinedNOTIFICATION notification to thenote queue.110Procedure CallsThis section provides the syntax, parameters, and other appropriate information foreach Pascal procedure call supported by <strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong>.BeginTcpIpThe BeginTcpIp procedures inform the <strong>TCP</strong><strong>IP</strong> virtual machine that you want tostart using its services. If your program handles simulated external interrupts itself,use StartTcpNotice rather than BeginTcpIp. For information about simulatedexternal interrupt support, see “Chapter 4. Virtual Machine Communication FacilityInterface” on page 147.procedure BeginTcpIp(var ReturnCode: integer);external;ParameterReturnCodeDescriptionIndicates success or failure of call. Possible return values are:v OKv ABNORMALcondition110 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


BeginTcpIpvvvvfatalerrorNOtcp<strong>IP</strong>service<strong>TCP</strong>ipshutdownVIRTUALmemoryTOOsmallFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.ClearTimerThe ClearTimer procedure resets the timer to prevent it from timing out.procedure ClearTimer(T: TimerPointerType);external;ParameterTDescriptionSpecifies a timer pointer, as returned by a previous CreateTimercall.CreateTimerThe CreateTimer procedure allocates a timer. The timer is not set in any way. Forthe procedure to activate the timer, see “SetTimer” on page 126.procedure CreateTimer(var T: TimerPointerType);external;ParameterTDescriptionSets to a timer pointer that can be used in subsequent SetTimer,ClearTimer, and DestroyTimer calls.DestroyTimerThe DestroyTimer procedure deallocates or frees a timer that you created.procedure DestroyTimer(var T: TimerPointerType);external;ParameterTDescriptionSpecifies a timer pointer, as returned by a previous CreateTimercall.EndTcpIpThe EndTcpIp procedure releases ports and protocols in use that are notpermanently reserved. It causes <strong>TCP</strong> to clean up any data structures it hasassociated with you. Use EndTcpIp when you have finished with the <strong>TCP</strong>/<strong>IP</strong>services.Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 111


GetHostNumberprocedure EndTcpIp;external;The EndTcpIp procedure has no parameters.GetHostNumberThe GetHostNumber procedure resolves a host name into an internet address.GetHostNumber uses a table lookup to convert the name of a host to an internetaddress, and returns this address to the HostNumber field. When the name is adotted-decimal number, GetHostNumber returns the integer represented by thatdotted-decimal. The dotted-decimal representation of a 32-bit number has onedecimal integer for each of the 4 bytes, separated by dots. For example, 14.0.0.7for X'0E000007'. For information about how to create host lookup tables, see <strong>TCP</strong>/<strong>IP</strong>Planning and Customization.The HostNumber field is set to NOhost if the host is not found.procedure GetHostNumber(const Name: string;var HostNumber: InternetAddressType);external;ParameterNameHostNumberDescriptionSpecifies the name or dotted-decimal number to be converted.Set to the converted address, or NOhost if conversion fails.GetHostResolThe GetHostResol procedure resolves a host name into an internet address byusing a name server.GetHostResol passes the query to the remote name server through the resolver.The name server converts the name of a host to an internet address, and returnsthis address in the HostNumber field. If the name server does not respond or doesnot find the name, the host name is converted to a host number by table lookup.When the name is a dotted-decimal number, the integer represented by thatdotted-decimal is returned. The dotted-decimal representation of a 32-bit numberhas one decimal integer for each of the 4 bytes, separated by dots. For example,14.0.0.7 for X'0E000007'.The HostNumber field is set to NOhost if the host is not found.procedure GetHostResol(const Name: string;var HostNumber: InternetAddressType);external;ParameterNameHostNumberDescriptionSpecifies the name or dotted-decimal number to be converted.Set to the converted address, or NOhost if conversion fails.112 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


GetHostStringThe GetHostString procedure uses a table lookup to convert an internet address toa host name, and returns this string in the Name field. The first host name foundin the lookup is returned. If no host name is found, a gateway or network name isreturned. If no gateway or network name is found, a null string is returned.procedure GetHostString(Address: InternetAddressType;varName: SiteNameType);external;GetHostStringParameterAddressNameDescriptionSpecifies the address to be converted.Set to the corresponding host, gateway, or network name, or tonull string if no match found.GetIdentityThe GetIdentity procedure returns the following information:v The user ID of the <strong>VM</strong> userv The host machine namev The network domain namev The user ID of the <strong>TCP</strong><strong>IP</strong> virtual machine.The host machine name and domain name are extracted from the HOSTNAMEand DOMAINORIGIN statements, respectively, in the user_id DATA file. If theuser_id DATA file does not exist, the <strong>TCP</strong><strong>IP</strong> DATA file is used. If a HOSTNAMEstatement is not specified, then the default host machine name is the namespecified by the <strong>TCP</strong>/<strong>IP</strong> installer during installation. See <strong>TCP</strong>/<strong>IP</strong> Planning andCustomization. The <strong>TCP</strong><strong>IP</strong> virtual machine user ID is extracted from the<strong>TCP</strong><strong>IP</strong>USERID statement in the user_id DATA file; if the statement is not specified,the default is <strong>TCP</strong><strong>IP</strong>.procedure GetIdentity(var UserId: DirectoryNameType;var HostName, DomainName: String;var TcpIpServiceName: DirectoryNameType;varResult: integer);external;ParameterUserIdHostNameDomainNameTcpIpServiceNameDescriptionSpecifies the user ID of the <strong>VM</strong> user or the jobname of a batch job that has invoked GetIdentity.Specifies the host machine name.Specifies the network domain name.Specifies the user ID of the <strong>TCP</strong><strong>IP</strong> virtual machine.GetNextNoteThe GetNextNote procedure retrieves notifications from the queue. This procedurereturns the next notification queued for you.Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 113


GetNextNoteprocedure GetNextNote(var Note: NotificationInfoType;ShouldWait: Boolean;var ReturnCode: integer);external;ParameterNoteShouldWaitReturnCodeDescriptionIndicates that the next notification is stored here when ReturnCodeis OK.Sets ShouldWait to TRUE if you want GetNextNote to wait until anotification becomes available. Set ShouldWait to FALSE if you wantGetNextNote to return immediately. When ShouldWait is set toFALSE, ReturnCode is set to NOoutstandingNOTIFICATIONS if nonotification is currently queued.Indicates the success or failure of the call. Possible return valuesare:v OKv NOoutstandingNOTIFICATIONSv NOTyetBEGUNFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.GetSmsgThe GetSmsg procedure is called by your program after receiving anSMSGreceived notification. Each call to GetSmsg retrieves one queued Smsg. Yourprogram should exhaust all queued Smsgs, by calling GetSmsg repeatedly until theSuccess field returns with a value of FALSE. After a value of FALSE is returned, donot call GetSmsg again until you receive another SMSGreceived notification.For information about the SMSG command, see <strong>TCP</strong>/<strong>IP</strong> User’s Guideprocedure GetSMsg(var Smsg: SmsgType;var Success: Boolean;);external;ParameterSmsgSuccessDescriptionSet to the returned Smsg if Success is set to TRUE.TRUE if Smsg returned, otherwise FALSE.HandleThe Handle procedure specifies that you want to receive notifications in the givenset. You must always use it after calling the BeginTcpIp procedure and beforeaccessing the <strong>TCP</strong>/<strong>IP</strong> services. This Pascal set can contain any of theNotificationEnumType values shown in Figure 17 on page 99.114 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Handleprocedure Handle(Notifications: NotificationSetType;varReturnCode: integer);external;ParameterNotificationsReturnCodeDescriptionSpecifies the set of notification types to be handled.Indicates the success or failure of the call. Possible return valuesare:v OKv NOTyetBEGUNv <strong>TCP</strong>ipSHUTDOWNv ABNORMALconditionv FATALerrorFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.LocalAddressThe IsLocalAddress procedure queries the <strong>TCP</strong><strong>IP</strong> virtual machine to determinewhether the HostAddress is one of the addresses recognized for this host. If theaddress is local, it returns OK. If the address is not local, it returnsNONlocalADDRESS.procedure IsLocalAddress(HostAddress: InternetAddressType;varReturnCode: integer);external;ParameterHostAddressReturnCodeDescriptionSpecifies the host address to be tested.Indicates whether the host address is local, or may indicate anerror. Possible return values are:v OKv NONlocalADDRESSv <strong>TCP</strong>ipSHUTDOWNv ABNORMALconditionv FATALerrorFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.IsLocalHostThe IsLocalHost procedure returns the correct host class for Name, which may be ahost name or a dotted-decimal address.The host classes are:Host Class DescriptionHOSTlocal Specifies an internet address for the local host.Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 115


IsLocalHostHOSTloopbackSpecifies one of the dummy internet addresses used to designatevarious levels of loopback testing.HOSTremote Specifies a known host name for some remote host.HOSTunknownSpecifies an unknown host name (or other error).procedure IsLocalHost(const Name: string;var Class: HostClassType);external;ParameterNameClassDescriptionSpecifies the host name.Specifies the host class.MonCommandThe MonCommand procedure instructs the <strong>TCP</strong><strong>IP</strong> virtual machine to read aspecific file and execute the commands found there. This procedure updates <strong>TCP</strong><strong>IP</strong>internal tables and parameters while the <strong>TCP</strong><strong>IP</strong> virtual machine is running. Forexample, the type and destination of run-time tracing can be modified dynamicallyusing MonCommand. This procedure is used by the OBEYFILE command. Formore information about the OBEYFILE command, see <strong>TCP</strong>/<strong>IP</strong> Planning andCustomization. You must be in the <strong>TCP</strong><strong>IP</strong> obey list to use the MonCommandprocedure.procedure MonCommand(const FileSpec: SpecOfFileType;var ReturnCode: integer);external;ParameterFileSpecReturnCodeDescriptionSpecifies a file in a manner that allows access to that file. The<strong>TCP</strong><strong>IP</strong> virtual machine must be authorized to access the file.The SpecOfFileType record is listed in Figure 18 on page 105.Indicates the success or failure of the call. Possible return valuesare:v OKv ABNORMALconditionv ERRORinPROFILEv HASnoPASSWORDv INCORRECTpasswordv INVALIDuserIDv INVALIDvirtualADDRESSv MINIDISKinUSEv MINIDISKnotAVAILABLEv NOTyetBEGUNv PROFILEnotFOUNDv SOFTWAREerrorv <strong>TCP</strong>ipSHUTDOWN116 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


MonCommandvvUNAUTHORIZEDuserUNIMPLEMENTEDrequestFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.MonQueryThe MonQuery procedure obtains status information, or requests <strong>TCP</strong><strong>IP</strong> to performcertain actions. This procedure is used by the NETSTAT command. For moreinformation about the NETSTAT command, see <strong>TCP</strong>/<strong>IP</strong> User’s Guide.procedure MonQuery(QueryRecord: MonQueryRecordType;Buffer: integer;BufSize: integer;varvarReturnCode: integer;Length: integer);external;ParameterBufferBufSizeReturnCodeLengthQueryRecordDescriptionSpecifies the address of the buffer to receive data.Specifies the size of the buffer.Indicates the success or failure of the call.Specifies the length of the data returned in the buffer.Sets up a QueryRecord to specify the type of status information tobe retrieved. The MonQueryRecordType is shown in Figure 19.MonQueryRecordType =recordcase QueryType: MonQueryType ofQUERYhome, QUERYgateways, QUERYcontrolBLOCKS,QUERYstartTIME, QUERYtelnetSTATUS,QUERYdevicesANDlinks,QUERYhomeONLY: ();QUERYudpPORTowner:(QueryPort: PortType);COMMANDcpCMD:(CpCmd: WordType);COMMANDdropCONNECTION:(Connection: ConnectionType);end; { MonQueryRecordType }Figure 19. Monitor Query RecordThe only QueryType values available for your use are:QUERYhomeONLYUsed to obtain a list of the home internet addresses recognized by your<strong>TCP</strong><strong>IP</strong> virtual machine. Your program sets the Buffer to the address of avariable of type HomeOnlyListType, and the BufSize to its length. WhenChapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 117


MonQueryMonQuery returns, Length is set to the length of the Buffer that was used,if ReturnCode is OK. Divide the Length by size of (InternetAddressType)to get the number of the home addresses that are returned.COMMANDdropCONNECTIONUsed to instruct the <strong>TCP</strong><strong>IP</strong> virtual machine to drop a <strong>TCP</strong> connection. Theconnection is reset, and the client process owning the connection is sent aNONEXISTENT notification with the Reason field set toDROPPEDbyOPERATOR. Your program sets the Connection field to thenumber of the connection to be dropped. The connection number is thenumber displayed by the NETSTAT CONN or the NETSTAT TELNETcommand, and is not the same number used to refer to the connection bythe client program that owns the connection. For information about theNETSTAT command, see <strong>TCP</strong>/<strong>IP</strong> User’s Guide. The virtual machine runningyour program that uses COMMANDdropCONNECTION must be in the<strong>TCP</strong><strong>IP</strong> virtual machine.ReturnCodeIndicates the success or failure of the call. Possible return values are:v OKv ABNORMALconditionv FATALerrorv NOTyetBEGUNv <strong>TCP</strong>ipSHUTDOWNv UNAUTHORIZEDuserv UNIMPLEMENTEDrequestFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.NotifyIoThe NotifyIo procedure is used to request that an IOinterrupt notification be sentto you when an I/O interrupt occurs on a given virtual address. You can specifythat you wish notifications on up to 10 different virtual device addresses (bymeans of individual NotifyIo calls). This notification is intended for unsolicitedinterrupts, not for interrupts showing the completion of a channel program.procedure NotifyIo(DeviceAddress: integer;var ReturnCode: integer;);external;Parameter DescriptionDeviceAddressSpecifies the address of the device for which IOinterruptnotifications are to be generated.ReturnCode Indicates success or failure of the call. Possible return values are:v OKv TOOmanyOPENSv SOFTWAREerrorFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.118 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


PingRequestThe PingRequest procedure sends an ICMP echo request to a foreign host. When aresponse is received or the time-out limit is reached, you receive a PingResponsenotification.The PingRequest procedure is used by the PING user command. For moreinformation about the PING command, see <strong>TCP</strong>/<strong>IP</strong> Planning and Customizationprocedure PingRequest(ForeignAddress: InternetAddressType;Length: integer;Timeout: integer;varReturnCode: integer);external;Parameter DescriptionForeignAddressSpecifies the address of the foreign host to be pinged.Length Specifies the length of the ping packet, excluding the <strong>IP</strong> header.The range of values for this field are 8 to 512 bytes.Timeout Specifies how long to wait for a response, in seconds.ReturnCode Indicates the success or failure of the call. Possible return valuesare:v OKv ABNORMALconditionv BADlengthARGUMENTv CONNECTIONalreadyEXISTSv NObufferSPACEv NOTyetBEGUNFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.Note: CONNECTIONalreadyEXISTS, in this context, means a ping request isalready outstanding.RawIpCloseThe RawIpClose procedure tells the <strong>TCP</strong><strong>IP</strong> virtual machine that the client does nothandle the protocol any longer. Any queued incoming packets are discarded.When the client is not handling the protocol, a return code ofNOsuchCONNECTION is received.procedure RawIpClose(ProtocolNo: integer;varReturnCode: integer);external;PingRequestParameterProtocolNoDescriptionSpecifies the number of the <strong>IP</strong> protocol.Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 119


RawIpCloseReturnCodeIndicates the success or failure of the call. Possible return valuesare:v OKv NOsuchCONNECTIONv NOTyetBEGUNv SOFTWAREerrorv <strong>TCP</strong>ipSHUTDOWNv UNAUTHORIZEDuserFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.RawIpOpenThe RawIpOpen procedure tells the <strong>TCP</strong><strong>IP</strong> virtual machine that the client wants tosend and receive packets of the specified protocol.You cannot use protocols 6 and 17. They specify the <strong>TCP</strong> (6) and UDP (17)protocols. When you specify 6, 17, or a protocol that has been opened by anothervirtual machine, you receive the LOCALportNOTavailable return code.procedure RawIpOpen(ProtocolNo: integer;varReturnCode: integer);external;ParameterProtocolNoReturnCodeDescriptionSpecifies the number of the <strong>IP</strong> protocol.Indicates the success or failure of the call. Possible return valuesare:v OKv LOCALportNOTavailablev NOTyetBEGUNv SOFTWAREerrorv <strong>TCP</strong>ipSHUTDOWNv UNAUTHORIZEDuserFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.Note: You can open the ICMP protocol, but your program receives only thoseICMP packets that are not interpreted by the <strong>TCP</strong><strong>IP</strong> virtual machine.RawIpReceiveThe RawIpReceive procedure specifies a buffer to receive Raw <strong>IP</strong> packets of thespecified protocol. You get the notification RAW<strong>IP</strong>packetsDELIVERED when apacket is put in the buffer.120 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


RawIpReceiveprocedure RawIpReceive(ProtocolNo: integer;Buffer: Address31Type;BufferLength: integer;varReturnCode: integer);external;ParameterProtocolNoBufferBufferLengthReturnCodeDescriptionSpecifies the number of the <strong>IP</strong> protocol.Specifies the address of your buffer.Specifies the length of your buffer. If you specify a length greaterthan 8492 bytes, only the first 8492 bytes are used.Indicates the success or failure of the call. Possible return valuesare:v OKv NOsuchCONNECTIONv NOTyetBEGUNv SOFTWAREerrorv <strong>TCP</strong>ipSHUTDOWNv UNAUTHORIZEDuserFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.RawIpSendThe RawIpSend procedure sends <strong>IP</strong> packets of the given protocol number. Theentire packet, including the <strong>IP</strong> header, must be in the buffer. The <strong>TCP</strong><strong>IP</strong> virtualmachine uses the total length field of the <strong>IP</strong> header to determine where eachpacket ends. Subsequent packets begin at the next doubleword (8-byte) boundarywithin the buffer.The packets in your buffer are transmitted as is with the following exceptions.v They can be fragmented. The fragment offset and flag fields in the header arefilled.v The version field in the header is filled.v The checksum field in the header is filled.v The source address field in the header is filled.You get the return code NOsuchCONNECTION if the client is not handling theprotocol, or if a packet in the buffer has another protocol. The return codeBADlengthARGUMENT is received when:v The DataLength is less than 40 bytes or more than 8K bytes.v NumPackets is 0.v A packet is greater than 2048 bytes.v All packets do not fit into DataLength.A ReturnCode value of NObufferSPACE indicates that the data is rejected because<strong>TCP</strong><strong>IP</strong> is out of buffers. When buffer space is available, the notificationRAW<strong>IP</strong>spaceAVAILABLE is sent to the client.Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 121


RawIpSendprocedure RawIpSend(ProtocolNo: integer;Buffer: Address31Type;DataLength: integer;NumPackets: integers;varReturnCode: integer);external;ParameterProtocolNoBufferDataLengthNumPacketsReturnCodeDescriptionSpecifies the number of the <strong>IP</strong> protocol.Specifies the address of your buffer containing packets to send.Specifies the total length of data in your buffer.Specifies the number of packets in your buffer.Indicates the success or failure of the call. Possible return valuesare:v OKv BADlengthARGUMENTv NObufferSPACEv NOsuchCONNECTIONv NOTyetBEGUNv SOFTWAREerrorv <strong>TCP</strong>ipSHUTDOWNv UNAUTHORIZEDuserFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.Note: If your buffer contains multiple packets to send, some of the packets mayhave been sent even if ReturnCode is not OK.ReadXlateTableThe ReadXlateTable procedure reads the binary translation table file specified byTableName, and fills in the AtoETable and EtoATable translation tables.procedure ReadXlateTable(var TableName: DirectoryNameType;var AtoETable: AtoEType;var EtoATable: EtoAType;var TranslateTableSpec: SpecOfFileType;var ReturnCode: integer);external;ParameterTableNameDescriptionSpecifies the name of the translate table.ReadXlateTable tries to read TableName<strong>TCP</strong>XLBIN. If that file exists but it has a badformat, ReadXlateTable returns with a ReturnCodeFILEformatINVALID. If user_id <strong>TCP</strong>XLBIN doesnot exist, ReadXlateTable tries to read <strong>TCP</strong><strong>IP</strong><strong>TCP</strong>XLBIN. ReturnCode reflects the status ofreading that file.122 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


ReadXlateTableAtoETableEtoATableTranslateTableSpecReturnCodeContains an ASCII-to-EBCDIC table if the returncode is OK.Contains an EBCDIC-to-ASCII table if the returncode is OK.If ReturnCode is OK, TranslateTableSpec containsthe complete specification of the file thatReadXlateTable used. If the ReturnCode is not OK,TranslateTableSpec contains the completespecification of the last file that ReadXlateTabletried to use.Indicates the success or failure of the call. Possiblereturn values are:v OKv ERRORopeningORreadingFILEv FILEformatINVALIDRTcpExtRuptThe RTcpExtRupt procedure is a version of the TcpExtRupt Pascal procedure andcan be called directly from an assembler interrupt handler.Note: The content of this section is Internal Product Information and must not beused as programming interface information.The following is a sample of the assembler calling sequence.The RTcpExtRupt procedure has no parameters.RTcpVmcfRuptLALALBALRR13,PASCSAVER1,EXTPARMR15,=V(R<strong>TCP</strong>EXTR)R14,R15..RUPTCODE DS H Store interrupt code here before calling X<strong>TCP</strong>EXTRPASCSAVE DS 18F Register save areaENV DC F’0’ Zero initially. It will be filled withEXTPARM DC A(ENV)DC A(RUPTCODE)an environment address. Pass it unchangedin subsequent calls to R<strong>TCP</strong>EXTR.The RTcpVmcfRupt procedure is a version of the TcpVmcfRupt Pascal procedureand can be called directly from an assembler interrupt handler.Note: The content of this section is Internal Product Information and must not beused as programming interface information.The following is a sample assembler calling sequence.Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 123


SayCalReLA R13,PASCSAVELA R1,<strong>VM</strong>CFPARML R15,=V(R<strong>TCP</strong><strong>VM</strong>CF)BALR R14,R15..PASCSAVE DS 18F Register save areaENV DC F’0’ Zero initially. It will be filled withan environment address. Pass it unchangedin subsequent calls to R<strong>TCP</strong><strong>VM</strong>CF.<strong>VM</strong>CFPARM DC A(ENV)DC A(<strong>VM</strong>CFBUF) Address of your <strong>VM</strong>CF interrupt buffer.The RTcpVmcfRupt procedure has no parameters.SayCalReThe SayCalRe function returns a printable string describing the return code passedin CallReturn.function SayCalRe)CallReturn: integer):WordType;external;ParameterCallReturnDescriptionSpecifies the return code to be described.SayConStThe SayConSt function returns a printable string describing the connection statepassed in State. For example, if SayConSt is invoked with the type identifierRECEIVINGonly, it returns the message Receiving only.function SayConSt(State: ConnectionStateType):Wordtype;external;ParameterStateDescriptionSpecifies the connection state to be described.SayIntAdThe SayIntAd function converts the internet address specified by InternetAddressto a printable string. The address is looked up in HOSTS ADDRINFO file, and thename is returned if found. If it is not found, the dotted-decimal format of theaddress is returned.124 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>function SayIntAd(InternetAddress: InternetAddressType):WordType;external;Parameter DescriptionInternetAddressSpecifies the internet address to be converted.


SayIntNumThe SayIntNum function converts the internet address specified byInternetAddress to a printable string, in dotted-decimal form.SayIntNumfunction SayIntNum(InternetAddress: InternetAddressType):Wordtype;external;Parameter DescriptionInternetAddressSpecifies the internet address to be converted.SayNotEnThe SayNotEn function returns a printable string describing the notificationenumeration type passed in Notification. For example, if SayNotEn is invoked withthe type identifier EXTERNALinterrupt, it returns the message, Other externalInterrupt received.function SayNotEn(Notification: NotificationEnumType);Wordtype;external;ParameterNotificationDescriptionSpecifies the notification enumeration type to be described.SayPorTyThe SayPorTy function returns a printable string describing the port numberpassed in Port, if it is a well-known port number such as the Telnet port.Otherwise, the EBCDIC representation of the number is returned.function SayPorTy(Port: PortType):WordType;external;ParameterPortDescriptionSpecifies the port number to be described.SayProTyThe SayProTy function converts the protocol type specified by Protocol to aprintable string, if it is a well-known protocol number such as 6 (<strong>TCP</strong>). Otherwise,the EBCDIC representation of the number is returned.function SayProTy(Protocol: ProtocolType):WordType;external;Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 125


SayProTyParameterProtocolDescriptionSpecifies the number of the protocol to be described.SetTimerThe SetTimer procedure sets a timer to expire after a specified time interval.Specify the amount of time in seconds. When it times out, you receive theTIMERexpired notification, which contains the data and the timer pointer.Note: This procedure resets any previous time interval set on this timer.procedure SetTimer(T: TimerPointerType;AmountOfTime: integer;Data: integer);external;ParameterTAmountOfTimeDataDescriptionSpecifies a timer pointer, as returned by aprevious CreateTimer call.Specifies the time interval in seconds.Specifies an integer value to be returnedwith the TIMERexpired notification.StartTcpNoticeThe StartTcpNotice procedure establishes your own external interrupt handler. Usethis procedure rather than BeginTcpIp when you want to handle simulated externalinterrupts yourself.If your program does not use simulated <strong>VM</strong>CF, set the ClientDoesVmcf parameterto FALSE. For more information about the simulated Virtual MachineCommunication Facility interface, see “Chapter 4. Virtual Machine CommunicationFacility Interface” on page 147. Later, when your program receives a simulatedexternal interrupt that it does not handle, including a <strong>VM</strong>CF interrupt, inform the<strong>TCP</strong> interface by calling TcpExtRupt. The <strong>TCP</strong> interface then processes theinterrupt.If your program uses simulated <strong>VM</strong>CF itself, set the ClientDoesVmcf parameter toTRUE. Your program must use the <strong>VM</strong>CF AUTHORIZE function to establish a<strong>VM</strong>CF interrupt buffer. Later, when your program receives a <strong>VM</strong>CF interrupt thatit does not handle, inform the <strong>TCP</strong> interface by calling TcpVmcfRupt with theaddress of your <strong>VM</strong>CF interrupt buffer. When your program receives a non-<strong>VM</strong>CFsimulated external interrupt that it does not handle, call TcpExtRupt, as explainedpreviously.procedure StartTcpNotice(ClientDoesVmcf: Boolean;varReturnCode: integer);external;ParameterDescription126 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


StartTcpNoticeClientDoesVmcfReturnCodeSet to FALSE if your program does not usesimulated <strong>VM</strong>CF. Otherwise, set to TRUE.Indicates the success or failure of the call. Possiblereturn values are:v OKv ABNORMALconditionv ALREADYclosingv NOtcp<strong>IP</strong>servicev VIRTUALmemoryTOOsmallv FATALerrorFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.TcpAbortThe TcpAbort procedure shuts down a specific connection immediately. Data sentby your application on the aborted connection can be lost. <strong>TCP</strong> sends a resetpacket to notify the foreign host that you have aborted the connection, but there isno guarantee that the reset will be received by the foreign host.procedure TcpAbort(Connection: ConnectionType;varReturnCode: integer);external;ParameterConnectionReturnCodeDescriptionSpecifies the connection number, as returned by TcpOpen orTcpWaitOpen in the Connection field of the StatusInfoType record.Indicates the success or failure of the call. Possible return valuesare:v OKv ABNORMALconditionv FATALerrorv NOsuchCONNECTIONv NOTyetBEGUNv <strong>TCP</strong>ipSHUTDOWNThe connection is fully terminated when you receive thenotification CONNECTIONstateCHANGED with the NewStatefield set to NONEXISTENT.For a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.TcpCloseThe TcpClose procedure begins the <strong>TCP</strong> one-way closing sequence. During thisclosing sequence, you, the local client, cannot send any more data. Data can bedelivered to you until the foreign application also closes. TcpClose also causes alldata sent on that connection by your application, and buffered by <strong>TCP</strong><strong>IP</strong>, to be sentto the foreign application immediately.Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 127


TcpCloseprocedure TcpClose(Connection: ConnectionType;varReturnCode: integer);external;ParameterConnectionReturnCodeDescriptionSpecifies the connection number, as returned by TcpOpen orTcpWaitOpen in the Connection field of the StatusInfoType record.Indicates the success or failure of the call. Possible return valuesare:v OKv ABNORMALconditionv ALREADYclosingv NOsuchCONNECTIONv NOTyetBEGUNv <strong>TCP</strong>ipSHUTDOWNFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.Notes:1. If you receive the notification CONNECTIONstateCHANGED with a NewStateof SENDINGonly, the remote application has done TcpClose (or equivalentfunction) and is receiving only. Respond with TcpClose when you have finishedsending data on the connection.2. The connection is fully closed when you receive the notificationCONNECTIONstateCHANGED, with a NewState field set to NONEXISTENT.TcpExtRuptUse the TcpExtRupt procedure when:1. You initiated the <strong>TCP</strong>/<strong>IP</strong> service by calling StartTcpNotice withClientDoesVmcf set to TRUE, and your external interrupt handler receives anon-<strong>VM</strong>CF interrupt not handled by your program. For the handling of <strong>VM</strong>CFinterrupts, see “TcpVmcfRupt” on page 138.2. You initiated the <strong>TCP</strong>/<strong>IP</strong> service by calling StartTcpNotice withClientDoesVmcf set to FALSE, and your external interrupt handler receives anyinterrupt not handled by your program.RTcpExtRupt is a version of TcpExtRupt. For more information, see “RTcpExtRupt”on page 123 and “RTcpVmcfRupt” on page 123.procedure TcpExtRupt(const RuptCode: integer);external;ParameterRuptCodeDescriptionSpecifies the external interrupt code you received.TcpFReceive, TcpReceive, and TcpWaitReceiveTcpFReceive and TcpReceive are the asynchronous ways of specifying a buffer toreceive data for a given connection. Both procedures return to your program128 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


immediately. A return code of OK means that the request has been accepted. Whenreceived data has been placed in your buffer, your program receives aDATAdelivered notification. If your program uses TcpFReceive, it can receive anFRECEIVEerror notification rather than DATAdelivered, indicating that the receiverequest was rejected, or that it was initially accepted but was later canceledbecause of connection closing.TcpWaitReceive is the synchronous interface for receiving data from a <strong>TCP</strong>connection. TcpWaitReceive does not return to your program until data has beenreceived into your buffer, or until an error occurs. Therefore, it is not necessarythat TcpWaitReceive receive a notification when data is delivered. The BytesReadparameter is set to the number of bytes received by the data delivery, but if thenumber is less than zero, the parameter indicates an error.TcpReceive uses a complete <strong>VM</strong>CF transaction (SEND by your virtual machinefollowed by REJECT by the <strong>TCP</strong><strong>IP</strong> virtual machine) to tell the <strong>TCP</strong><strong>IP</strong> virtualmachine that your program is ready to receive, and another complete <strong>VM</strong>CFtransaction (SEND by <strong>TCP</strong><strong>IP</strong> virtual machine followed by RECEIVE by yourvirtual machine) to deliver the received data. In contrast, the entire TcpFReceivecycle is completed in one <strong>VM</strong>CF transaction. The <strong>TCP</strong> interface does a <strong>VM</strong>CFSEND/RECEIVE to inform <strong>TCP</strong><strong>IP</strong> that your program is ready to receive. Thistransaction remains uncompleted until data is ready to be placed in your buffer. Atthat time the <strong>TCP</strong><strong>IP</strong> virtual machine does a <strong>VM</strong>CF REPLY, completing thetransaction.TcpFReceive requires fewer <strong>VM</strong>CF transactions to receive data, thus increasingefficiency. The disadvantage is that each outstanding TcpFReceive means anoutstanding <strong>VM</strong>CF transaction. You are limited to 50 outstanding <strong>VM</strong>CFtransactions (for each virtual machine), thus 50 outstanding TcpFReceives.With TcpReceive, you are not subject to the limit of 50 outstanding receives (foreach virtual machine). The disadvantage is that there are twice as many <strong>VM</strong>CFtransactions involved in receiving data, thus more overhead.The only programming difference between TcpFReceive and TcpReceive is thegeneration of FRECEIVEerror notifications for TcpFReceive.procedure TcpFReceive(Connection: ConnectionType;Buffer: Address31Type;BytesToRead: integer;var ReturnCode: integer);external;procedure TcpReceive(Connection: ConnectionType;Buffer: Address31Type;BytesToRead: integer;varReturnCode: integer);external;TcpFReceive, TcpReceive, and TcpWaitReceiveChapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 129


TcpFReceive, TcpReceive, and TcpWaitReceiveprocedure TcpWaitReceive(Connection: ConnectionType;Buffer: Address31Type;BytesToRead: integer;varBytesRead: integer);external;ParameterConnectionBufferBytesToReadBytesReadReturnCode:DescriptionSpecifies the connection number, as returned by TcpOpen orTcpWaitOpen in the Connection field of the StatusInfoType record.Specifies the address of the buffer to contain the received data.Specifies the size of the buffer. <strong>TCP</strong><strong>IP</strong> usually buffers the incomingdata until this many bytes are received. Data is delivered sooner ifthe sender specified the PushFlag, or if the sender does a TcpCloseor equivalent. The largest usable buffer is 8192 bytes. SpecifyingBytesToRead of more than 8192 bytes may not cause an errorreturn, but only 8192 bytes of the buffer are used.Note: The order of TcpFReceive or TcpReceive calls on multipleconnections, and the order of DATAdelivered notificationsamong the connections, are not necessarily related.Indicates a value when TcpWaitReceive returns. If it is greater thanZERO, it indicates the number of bytes received into your buffer. Ifit is less than or equal to ZERO, it indicates an error.Possible BytesRead values are:v OK+v ABNORMALconditionv FATALerrorv TIMEOUTopen+v UNREACHABLEnetwork+v BADlengthARGUMENTv NOsuchCONNECTIONv NOTyetBEGUNv NOTyetOPENv OPENrejected+v RECEIVEstillPENDINGv REMOTEreset+v UNEXPECTEDsyn+v WRONGsecORprc+v DROPPEDbyOPERATOR+v FATALerror+v KILLEDbyCLIENT+v <strong>TCP</strong>ipSHUTDOWN+v TIMEOUTconnection+v REMOTEcloseIndicates the success or failure of the call. Possible return valuesare:v OKv ABNORMALconditionv BEGUNlengthARGUMENTv fatalerrorv NOsuchCONNECTION130 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


TcpFReceive, TcpReceive, and TcpWaitReceivevvvvvNOTyetBEGUNNOTyetOPENRECEIVEstillPENDINGREMOTEclose<strong>TCP</strong>ipSHUTDOWNFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.Notes:1. For BytesRead OK, the function was initiated, but the connection is no longerreceiving for an unspecified reason. Your program does not have to issueTcpClose, but the connection is not completely terminated until aNONEXISTENT notification is received for the connection.2. For BytesRead REMOTEclose, the foreign host has closed the connection. Yourprogram should respond with TcpClose.3. If you receive any of the codes marked with +, the function was initiated butthe connection has now been terminated (see 2 on page 101). Your programshould not issue TcpClose, but the connection is not completely terminateduntil NONEXISTENT notification is received for the connection.4. TcpWaitReceive is intended to be used by programs that manage a single <strong>TCP</strong>connection. It is not suitable for use by multiconnection servers.5. A return code of <strong>TCP</strong>ipSHUTDOWN can be returned either because theconnection initiation has failed, or because the connection has been terminated,because of shutdown. In either case, your program should not issue any more<strong>TCP</strong>/<strong>IP</strong> calls.TcpFSend, TcpSend, and TcpWaitSendTcpFSend and TcpSend are the asynchronous ways of sending data on a <strong>TCP</strong>connection. Both procedures return to your program immediately (do not waitunder any circumstance).TcpWaitSend is a simple synchronous method of sending data on a <strong>TCP</strong>connection. It does not return immediately if the <strong>TCP</strong><strong>IP</strong> virtual machine hasinsufficient space to accept the data being sent.TcpFSend and TcpSend differ in the way that they handle <strong>VM</strong>CF when the <strong>TCP</strong><strong>IP</strong>virtual machine has insufficient buffer space to accept the data being sent. Bothstart by issuing a <strong>VM</strong>CF SEND function to transfer your data. Normally, the <strong>TCP</strong><strong>IP</strong>virtual machine issues a <strong>VM</strong>CF RECEIVE, thus completing the <strong>VM</strong>CF transaction.In the case of insufficient buffer space, <strong>TCP</strong><strong>IP</strong> responds to TcpSend with a <strong>VM</strong>CFREJECT, completing the <strong>VM</strong>CF transaction (unsuccessfully). When space becomesavailable, another complete <strong>VM</strong>CF transaction is performed to send aBUFFERspaceAVAILABLE notification.In the case of a TcpFSend with insufficient buffer space, <strong>TCP</strong><strong>IP</strong> does not respond tothe <strong>VM</strong>CF SEND until buffer space becomes available, at which time thetransaction is completed with a <strong>VM</strong>CF RECEIVE.TcpSend returns to your program after the <strong>VM</strong>CF response from <strong>TCP</strong><strong>IP</strong> is received.In contrast, because the <strong>VM</strong>CF response from TcpFSend may be delayed, TcpFSendreturns before the <strong>VM</strong>CF response is received. An OK return code from TcpFSendindicates only the successful initiation of the <strong>VM</strong>CF transaction.Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 131


TcpFSend, TcpSend, and TcpWaitSendThe advantage of TcpFSend is that the <strong>VM</strong>CF transactions necessary to send dataare reduced in the case where a program can send data faster than the <strong>TCP</strong>connection can carry it. Its disadvantages are that it is limited to 50 outstanding<strong>VM</strong>CF sends and therefore 50 TcpFSends, and is slightly more complicated to use,because you have to wait for an FSENDresponse notification (generated internallyby the <strong>TCP</strong> interface) between successive TcpFSends.The advantage of TcpSend is that it does not involve an outstanding <strong>VM</strong>CFtransaction. Thus, there is no imposed <strong>VM</strong>CF-related limit. Also, TcpSend issimpler to use because you can issue successive TcpSends without waiting for anotification. The disadvantage of TcpSend is that it is less efficient than TcpFSend ifyour program can send data faster than the <strong>TCP</strong> connection can carry it.Your program can issue successive TcpWaitSend calls. Buffer shortage conditionsare handled transparently. Any errors that occur are likely to be nonrecoverableerrors, or are caused by a connection that has terminated.If you receive any of the codes listed for Reason in theCONNECTIONstateCHANGED notification, except for OK, the connection wasterminated for the indicated reason. Your program should not issue a TcpClose, butthe connection is not completely terminated until your program receives aNONEXISTENT notification for the connection.procedure TcpFSend(Connection: ConnectionType;Buffer: Address31Type;BufferLength: integer;PushFlag: Boolean;UrgentFlag: Boolean;varReturnCode: integer);external;procedure TcpSend(Connection: ConnectionType;Buffer: Address31Type;BufferLength: integer;PushFlag: Boolean;UrgentFlag: Boolean;varReturnCode: integer);external;procedure TcpWaitSend(Connection: ConnectionType;Buffer: Address31Type;BufferLength: integer;PushFlag: Boolean;UrgentFlag: Boolean;varReturnCode: integer);external;ParameterConnectionBufferDescriptionSpecifies the connection number, as returned by TcpOpen orTcpWaitOpen in the Connection field of the StatusInfoType record.Specifies the address of the buffer containing the data to send.132 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


TcpFSend, TcpSend, and TcpWaitSendBufferLength Specifies the length of data in the buffer. Maximum is 8192.PushFlag Forces the data, and previously queued data, to be sentimmediately to the foreign application.UrgentFlag Marks the data as urgent. The semantics of urgent data isdependent on your application.ReturnCodeNote: Use urgent data with caution. If the foreign applicationfollows the Telnet-style use of urgent data, it may flush allurgent data until a special character sequence isencountered.Indicates the success or failure of the call. Possible return valuesare:v OKv ABNORMALconditionv BADlengthARGUMENTv CANNOTsendDATAv FATALerrorv FSENDstillpendingv NObufferSPACE ( TcpSend only)v NOsuchCONNECTIONv NOTyetBEGUNv NOTyetOPENv <strong>TCP</strong>ipSHUTDOWNFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.Notes:1. A successful TcpFSend, TcpSend, and TcpWaitSend means that <strong>TCP</strong> hasreceived the data to be sent and stored it in its internal buffers. <strong>TCP</strong> then putsthe data in packets and transmits it when the conditions permit.2. Data sent in a TcpFSend, TcpSend, or TcpWaitSend request may be split up intonumerous packets by <strong>TCP</strong>, or the data may wait in <strong>TCP</strong>’s buffer space andshare a packet with other TcpFSend, TcpSend, or TcpWaitSend, requests.3. The PushFlag gives the user the ability to affect when <strong>TCP</strong> sends the data.Setting the PushFlag to FALSE allows <strong>TCP</strong> to buffer the data and wait until ithas enough data to transmit so as to utilize the transmission line moreefficiently. There can be some delay before the foreign host receives the data.Setting the PushFlag to TRUE instructs <strong>TCP</strong> to packetize and transmit anybuffered data from previous Send requests along with the data in the currentTcpFSend, TcpSend, or TcpWaitSend request without delay or consideration oftransmission line efficiency. A successful send does not imply that the foreignapplication has actually received the data, only that the data will be sent assoon as possible.4. TcpWaitSend is intended for programs that manage a single <strong>TCP</strong> connection. Itis not suitable for use by multiconnection servers.TcpNameChangeThe TcpNameChange procedure is used if the virtual machine running the <strong>TCP</strong>/<strong>IP</strong>program is not using the default name, <strong>TCP</strong><strong>IP</strong>, and is not the same as specified inthe <strong>TCP</strong><strong>IP</strong>USERID statement of the <strong>TCP</strong><strong>IP</strong> DATA file. For more information, see<strong>TCP</strong>/<strong>IP</strong> Planning and Customization.Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 133


TcpNameChangeIf required, this procedure must be called before the BeginTcpIp or theStartTcpNotice procedure.procedure TcpNameChange(NewNameOfTcp: DirectoryNameType);external;ParameterNewNameOfTcpDescriptionSpecifies the name of the virtual machine running<strong>TCP</strong>/<strong>IP</strong>.TcpOpen and TcpWaitOpenThe TcpOpen or TcpWaitOpen procedures initiate a <strong>TCP</strong> connection. TcpOpenreturns immediately, and connection establishment proceeds asynchronously withyour program’s other operations. The connection is fully established when yourprogram receives a CONNECTIONstateCHANGED notification with NewState setto OPEN. TcpWaitOpen does not return until the connection is established, or untilan error occurs.There are two types of TcpOpen calls: passive open and active open. A passiveopen call sets the connection state to LISTENING. An active open call sets theconnection state to TRYINGtoOPEN.If a TcpOpen or TcpWaitOpen call returns ZEROresources, and your applicationhandles RESOURCESavailable notifications, you receive a RESOURCESavailablenotification when sufficient resources are available to process an open call. The firstopen your program issues after a RESOURCESavailable notification is guaranteednot to get the ZEROresources return code.procedure TcpOpen(var ConnectionInfo: StatusInfoType;var ReturnCode: integer);external;procedure TcpWaitOpen(var ConnectionInfo: StatusInfoType;var ReturnCode: integer);external;Parameter DescriptionConnectionInfoSpecifies a connection information record.ConnectionSet this field to UNSPECIFIEDconnection. When the callreturns, the field contains the number of the newconnection if ReturnCode is OK.ConnectionStateFor active open, set this field to TRYINGtoOPEN. Forpassive open, set this field to LISTENING.134 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


TcpOpen and TcpWaitOpenReturnCodeOpenAttemptTimeoutSet this field to specify how long, in seconds, <strong>TCP</strong> is tocontinue attempting to open the connection. If theconnection is not fully established during that time, <strong>TCP</strong>reports the error to you. If you used TcpOpen, you receivea notification. The type of notification that you receive isCONNECTIONstateCHANGED. It has a new state ofNONEXISTENT and a reason of TIMEOUTopen. If youused TcpWaitOpen, it returns with ReturnCode set toTIMEOUTopen.SecurityThis field is reserved. Set it to DEFAULTsecurity.CompartmentThis field is reserved. Set it to DEFAULTcompartment.PrecedenceThis field is reserved. Set it to DEFAULTprecedence.LocalSocketActive Open: You can use an address ofUNSPECIFIEDaddress (the <strong>TCP</strong><strong>IP</strong> virtual machine uses thehome address corresponding to the network interface usedto route to the foreign address) and a port ofUNSPECIFIEDport (the <strong>TCP</strong><strong>IP</strong> virtual machine assigns aport number, in the range of 1000 to 65 534). You canspecify the address, the port, or both if particular valuesare required by your application. The address must be avalid home address for your node, and the port must beavailable (not reserved, and not in use by anotherapplication).Passive Open: You usually specify a predetermined portnumber, which is known by another program, which cando an active open to connect to your program.Alternatively, you can use UNSPECIFIEDport to let the<strong>TCP</strong><strong>IP</strong> virtual machine assign a port number, obtain theport number through TcpStatus, and transmit it to theother program through an existing <strong>TCP</strong> connection ormanually. You generally specify an address ofUNSPECIFIEDaddress, so that the active open to your portsucceeds, regardless of the home addresses to which it wassent.ForeignSocketActive Open: The address and port must both be specified,because the <strong>TCP</strong><strong>IP</strong> virtual machine cannot actively initiatea connection without knowing the destination address andport.Passive Open: If your program is offering a service toanyone who wants it, specify an address ofUNSPECIFIEDaddress and a port of UNSPECIFIEDport.You can specify a particular address and port if you wantto accept an active open only from a certain foreignapplication.Indicates the success or failure of the call. Possible return valuesare:Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 135


TcpOpen and TcpWaitOpenvvvvvvvvvvvvvvvvvvvvvvvvOKABNORMALconditionFATALerrorCONNECTIONalreadyEXISTSDROPPEDbyOPERATOR ( TcpWaitOpen only)LOCALportNOTavailableNOsuchCONNECTIONNOTyetBEGUNOPENrejected ( TcpWaitOpen only)PARAMlocalADDRESSPARAMstatePARAMtimeoutPARAMunspecADDRESSPARAMunspecPORTREMOTEreset ( TcpWaitOpen only)SOFTWAREerror<strong>TCP</strong>ipSHUTDOWNTIMEOUTconnection ( TcpWaitOpen only)TIMEOUTopen ( TcpWaitOpen only)TOOmanyOPENSUNEXPECTEDsyn ( TcpWaitOpen only)UNREACHABLEnetwork ( TcpWaitOpen only)WRONGsecORprc ( TcpWaitOpen only)ZEROresourcesFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.TcpOptionThe TcpOption procedure sets an option for a <strong>TCP</strong> connection.procedure TcpOption(Connection: ConnectionTypeOptionName: integer;OptionValue: integer;varReturnCode: integer);external;ParameterConnectionOptionNameOptionValueDescriptionSpecifies the connection number, as returned by TcpOpen orTcpWaitOpen in the Connection field of the StatusInfoType record.Specifies the code for the option.OPTIONtcpKEEPALIVEIf OptionValue is zero, the keep-alive mechanism isdeactivated for the connection. If OptionValue is nonzero,the keep-alive mechanism is activated for the connection.This mechanism sends a packet on an otherwise idleconnection. If the remote <strong>TCP</strong> does not respond to thepacket, the connection state will be changed toNONEXISTENT with TIMEOUTconnection as the reason.Specifies the value for the option.136 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


TcpOptionReturnCodeIndicates the success or failure of the call. Possible return valuesare:v OKv NOsuchCONNECTIONv NOTyetBEGUNv <strong>TCP</strong>ipSHUTDOWNv INVALIDrequestFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.TcpStatusThe TcpStatus procedure obtains the current status of a <strong>TCP</strong> connection. Yourprogram sets the Connection field of the ConnectionInfo record to the number ofthe connection whose status you want.procedure TcpStatus(var ConnectionInfo: StatusInfoType;var ReturnCode: integer);external;Parameter DescriptionConnectionInfoIf ReturnCode is OK, the following fields are returned.Field DescriptionOpenAttemptTimeoutIf the connection is in the process of being opened(including a passive open), this field is set to thenumber of seconds remaining before the open isterminated if it has not completed. Otherwise, it isset to WAITforever.BytesToRead Specifies the number of bytes of incoming dataqueued for your program (waiting for TcpReceive,TcpFReceive, or TcpWaitReceive).UnackedBytes Specifies the number of bytes sent by yourprogram but not yet sent to the foreign <strong>TCP</strong>, or thenumber of bytes sent to the foreign <strong>TCP</strong>, but notyet acknowledged.ConnectionStateSpecifies the current connection state.LocalSocket Specifies the local socket, consisting of a localaddress and a local port.ForeignSocket Specifies the foreign socket, consisting of a foreignaddress and a foreign port.ReturnCode Indicates the success or failure of the call. Possible return valuesare:v OKv ABNORMALconditionv NOsuchCONNECTIONv NOTyetBEGUNChapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 137


TcpStatusv<strong>TCP</strong>ipSHUTDOWNFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.Note: Your program cannot monitor connection state changes exclusively throughpolling with TcpStatus. It must receive CONNECTIONstateCHANGEDnotifications through GetNextNote, for the <strong>TCP</strong> interface to work properly.TcpVmcfRuptThe TcpVmcfRupt procedure is used when you initiate the <strong>TCP</strong>/<strong>IP</strong> service bycalling StartTcpNotice with ClientDoesVmcf set to TRUE, and your externalinterrupt handler receives a <strong>VM</strong>CF interrupt not handled by your program.RTcpVmcfRupt is a version of TcpVmcfRupt that can be called directly from anassembler interrupt handler. For more information, see “RTcpExtRupt” on page 123and “RTcpVmcfRupt” on page 123.procedure TcpVmcfRupt(VmcfHeaderAddress: integer);external;ParameterVmcfHeaderAddressDescriptionIndicates the address of your <strong>VM</strong>CF interruptbuffer as specified in the <strong>VM</strong>CF AUTHORIZEfunction that your program issued at initialization.UdpCloseThe UdpClose procedure closes the UDP socket specified in the ConnIndex field.All incoming datagrams on this connection are discarded.procedure UdpClose(ConnIndex: ConnectionIndexType;varReturnCode: CallReturnCodeType);external;ParameterConnIndexReturnCodeDescriptionSpecifies the ConnIndex value returned from UdpOpen.Indicates the success or failure of the call. Possible return valuesare:v OKv ABNORMALconditionv FATALerrorv NOsuchCONNECTIONv NOTyetBEGUNv SOFTWAREerrorv <strong>TCP</strong>ipSHUTDOWNFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.138 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


UdpNReceiveThe UdpNReceive procedure notifies the <strong>TCP</strong><strong>IP</strong> virtual machine that you canreceive UDP datagram data. This call returns immediately. The data buffer is notvalid until you receive a UDPdatagramDELIVERED notification.procedure UdpNReceive(ConnIndex: ConnectionIndexType;BufferAddress: integer;BufferLength: integer;varReturnCode: CallReturnCodeType);external;Parameter DescriptionConnIndex Specifies the ConnIndex value returned from UdpOpen.BufferAddressSpecifies the address of your buffer that will be filled with a UDPdatagram.BufferLength Specifies the length of your buffer. If you specify a length largerthan 8192 bytes, only the first 8192 bytes are used.ReturnCode Indicates the success or failure of the call. Possible return valuesare:v OKv ABNORMALconditionv FATALerrorv NOsuchCONNECTIONv NOTyetBEGUNv RECEIVEstillPENDINGv <strong>TCP</strong>ipSHUTDOWNFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.UdpOpenThe UdpOpen procedure requests acceptance of UDP datagrams on the specifiedsocket and allows datagrams to be sent from the specified socket. When the socketport is unspecified, UDP selects a port and returns it to the socket port field. Whenthe socket address is unspecified, UDP uses the default local address. If specified,the address must be a valid home address for your node.Note: When the local address is specified, only the UDP datagrams addressed to itare delivered.If the ReturnCode indicates the open was successful, use the returned ConnIndexvalue on any further actions pertaining to this UDP socket.procedure UdpOpen(var LocalSocket: SocketType;var ConnIndex: ConnectionIndexType;var ReturnCode: CallReturnCodeType);external;UdpNReceiveChapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 139


UdpOpenParameterLocalSocketConnIndexReturnCodeDescriptionSpecifies the local socket (address and port pair).Specifies the ConnIndex value returned from UdpOpen.Indicates the success or failure of the call. Possible return valuesare:v OKv ABNORMALconditionv FATALerrorv LOCALportNOTavailablev NOTyetBEGUNv SOFTWAREerrorv <strong>TCP</strong>ipSHUTDOWNv UDPlocalADDRESSv UDPzeroRESOURCESFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.Note: If a UdpOpen call returns UDPzeroRESOURCES, and your applicationhandles UDPresourcesAVAILABLE notifications, you receive aUDPresourcesAVAILABLE notification when sufficient resources areavailable to process a UdpOpen call. The first UdpOpen your programissues after a UDPresourcesAVAILABLE notification is guaranteed not to getthe UDPzeroRESOURCES return code.UdpReceiveThe UdpReceive procedure notifies the <strong>TCP</strong><strong>IP</strong> virtual machine that you are willingto receive UDP datagram data.UdpReceive is for compatibility with old programs only. New programs shoulduse the UdpNReceive procedure, which allows you to specify the size of yourbuffer.If you use UdpReceive, <strong>TCP</strong><strong>IP</strong> can put a datagram of up to 2012 bytes in yourbuffer. If a larger datagram is sent to your port when UdpReceive is pending, thedatagram is discarded without notification.Note: No data is transferred from the <strong>TCP</strong><strong>IP</strong> virtual machine in this call. It onlytells <strong>TCP</strong><strong>IP</strong> that you are waiting for a datagram. Data has been transferredwhen a UDPdatagramDELIVERED notification is received.procedure UdpReceive(ConnIndex: ConnectionIndexType;DatagramAddress: integer;varReturnCode: CallReturnCodeType);external;Parameter DescriptionConnIndex Specifies the ConnIndex value returned from UdpOpen.DatagramAddressSpecifies the address of your buffer that will be filled with aUDP datagram.140 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


UdpReceiveReturnCodeIndicates the success or failure of the call. Possible returnvalues are:v OKv ABNORMALconditionv FATALerrorv NOsuchCONNECTIONv NOTyetBEGUNv SOFTWAREerrorv <strong>TCP</strong>ipSHUTDOWNFor a description of Pascal ReturnCodes, see “Appendix A. Pascal ReturnCodes” on page 405.UdpSendThe UdpSend procedure sends a UDP datagram to the specified foreign socket.The source socket is the local socket selected in the UdpOpen that returned theConnIndex value that was used. The buffer does not include the UDP header. Thisheader is supplied by the <strong>TCP</strong><strong>IP</strong> virtual machine.When there is no buffer space to process the data, an error is returned. In this case,wait for a subsequent UDPdatagramSPACEavailable notification.procedure UdpSend(ConnIndex: ConnectionIndexType;ForeignSocket: SocketType;BufferAddress: integer;Length: integer;varReturnCode: CallReturnCodeType);external;Parameter DescriptionConnIndex Specifies the ConnIndex value returned from UdpOpen.ForeignSocket Specifies the foreign socket (address and port) to whom thedatagram is to be sent.BufferAddressSpecifies the address of your buffer containing the UDP datagramto be sent, excluding UDP header.Length Specifies the length of the datagram to be sent, excluding UDPheader. Maximum is 8192 bytes.ReturnCode Indicates the success or failure of the call. Possible return valuesare:v OKv BADlengthARGUMENTv NObufferSPACEv NOsuchCONNECTIONv NOTyetBEGUNv SOFTWAREerrorv <strong>TCP</strong>ipSHUTDOWNv UDPunspecADDRESSv UDPunspecPORTChapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 141


UdpSendFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.UnhandleThe Unhandle procedure specifies that you no longer want to receive notificationsin the given set.If you request to unhandle the DATAdelivered notification, the Unhandleprocedure returns with a code of INVALIDrequest.procedure Unhandle(Notifications: NotificationSetType;varReturnCode: integer);external;ParameterNotificationsReturnCodeDescriptionSpecifies the set of notifications that you no longer want to receive.Indicates the success or failure of the call. Possible return valuesare:v OKv ABNORMALconditionv FATALerrorv INVALIDrequestv NOTyetBEGUNv <strong>TCP</strong>ipSHUTDOWNFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.UnNotifyIoThe UnNotifyIo routine is used to indicate that you no longer wish to be sent anotification when an I/O interrupt occurs on the specified virtual address.procedure UnNotifyIo(DeviceAddress: integer;varReturnCode: integer);external;Parameter DescriptionDeviceAddressSpecifies the address of the device for which IOinterruptnotifications are no longer to be generated.ReturnCode Indicates the success or failure of the call. Possible return valuesare:v OKv NOsuchCONNECTIONv SOFTWAREerrorFor a description of Pascal ReturnCodes, see “Appendix A. Pascal Return Codes”on page 405.142 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Sample Pascal Program{**********************************************************************}{* *}{* Memory-to-memory Data Transfer Rate Measurement *}{* *}{* Pseudocode: Establish access to <strong>TCP</strong>/<strong>IP</strong> Services *}{* Prompt user for operation parameters *}{* Open a connection (Sender:passive, Receiver:active) *}{* If Sender: *}{* Send 5M of data using TcpFSend *}{* Use GetNextNote to know when Send is complete *}{* Print transfer rate after every 1M of data *}{* else Receiver: *}{* Receive 5M of data using TcpFReceive *}{* Use GetNextNote to know when data is delivered *}{* Print transfer rate after every 1M of data *}{* Close connection *}{* Use GetNextNote to wait until connection is closed *}{* *}{**********************************************************************}program SAMPLE;%include CMALLCL%include CMINTER%include CMRESGLBSample Pascal ProgramconstBUFFERlength = 8192;PORTnumber = 999;CLOCKunitsPERthousandth = ’3E8000’x;varBuffer : packed array (.1..BUFFERlength.) of char;BufferAddress : Address31Type;ConnectionInfo : StatusInfoType;Count: integer;DataRate : real;Difference : TimeStampType;Error: boolean;HostAddress : InternetAddressType;IbmSeconds : integer;Ignored : integer;Line: string(80);Note: NotificationInfoType;NumBytes : integer;RealRate : real;ReturnCode : integer;SendFlag : boolean;StartingTime : TimeStampType;Thousandths : integer;TotalBytes : integer;{**********************************************************}{* Print message, release resources and reset environment *}{**********************************************************}procedure Restore ( const Message: string;const ReturnCode: integer );beginWrite (Message);if ReturnCode OK thenWrite (SayCalRe(ReturnCode));WriteLn (’’);EndTcpIp;Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 143


Sample Pascal ProgramDropEmulation;Close (Input);Close (Output);end;beginTermOut (Output);TermIn (Input);{ Enable program to run with ECMODE OFF. It has no effect if }{ ECMODE ON. There is, however, additional overhead and }{ possible performance impact when running with ECMODE OFF. }InitEmulation (Error);if Error then beginWriteLn (’InitEmulation failed’);return;end;{ Establish access to <strong>TCP</strong>/<strong>IP</strong> services }BeginTcpIp (ReturnCode);if ReturnCode OK then beginWriteLn (’BeginTcpip: ’, SayCalRe(ReturnCode));return;end;{ Inform <strong>TCP</strong><strong>IP</strong> which notifications will be handled by the program }Handle ((.DATAdelivered, BUFFERspaceAVAILABLE,CONNECTIONstateCHANGED.), ReturnCode);if ReturnCode OK then beginRestore (’Handle: ’, ReturnCode);return;end;{ Prompt user for operation parameters }WriteLn (’Transfer mode: (Send or Receive)’);ReadLn (Line);if (Substr(Line,1,1) = ’s’) or (Substr(Line,1,1) = ’S’) thenSendFlag := TRUEelseSendFlag := FALSE;WriteLn (’Host Name or Internet Address :’);ReadLn (Line);GetHostResol (Line, HostAddress);if HostAddress = NOhost then beginRestore (’GetHostResol failed’, OK);return;end;{ Open a <strong>TCP</strong> connection: active for Send and passive for Receive }with ConnectionInfo do beginConnection := UNSPECIFIEDconnection;OpenAttemptTimeout := WAITforever;Security:= DEFAULTsecurity;Compartment := DEFAULTcompartment;Precedence := DEFAULTprecedence;if SendFlag then beginConnectionState := TRYINGtoOPEN;LocalSocket.Address := UNSPECIFIEDaddress;LocalSocket.Port := UNSPECIFIEDport;ForeignSocket.Address := HostAddress;ForeignSocket.Port := PORTnumber;endelse beginConnectionState := LISTENING;LocalSocket.Address := HostAddress;144 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Sample Pascal ProgramLocalSocket.Port := PORTnumber;ForeignSocket.Address := UNSPECIFIEDaddress;ForeignSocket.Port := UNSPECIFIEDport;end;end;TcpWaitOpen (ConnectionInfo, ReturnCode);if ReturnCode OK then beginRestore (’TcpWaitOpen: ’, ReturnCode);return;end;{ Initialization }BufferAddress := AddressOfChar(Buffer(.1.));NumBytes := BUFFERlength;StartingTime := ClockTime;TotalBytes := 0;Count := 0;{ Repeat until 5M bytes of data have been transferred }while (Count < 5) do begin{ Transfer data and wait until operation is completed }if SendFlag thenTcpWaitSend (ConnectionInfo.Connection, BufferAddress,BUFFERlength, FALSE, FALSE, ReturnCode)else beginTcpWaitReceive (ConnectionInfo.Connection, BufferAddress,BUFFERlength, NumBytes);if NumBytes < 0 thenReturnCode := NumBytes;end;if ReturnCode OK then beginWriteLn (’TcpSend/Receive: ’, SayCalRe(ReturnCode));leave;end;TotalBytes := TotalBytes + NumBytes;if TotalBytes < 1048576 thencontinue;{ Print transfer rate after every 1M bytes of data transferred }DoubleSubtract (ClockTime, StartingTime, Difference);DoubleDivide (Difference, CLOCKunitsPERthousandth, Thousandths,Ignored);RealRate := (TotalBytes/Thousandths) * 1000.0;WriteLn (’Transfer rate ’, RealRate:1:0, ’ Bytes/sec.’);StartingTime := ClockTime;TotalBytes := 0;Count := Count + 1;end;{ Close <strong>TCP</strong> connection and wait till partner also drops connection }TcpClose (ConnectionInfo.Connection, ReturnCode);if ReturnCode OK then beginRestore (’TcpClose: ’, ReturnCode);return;end;repeatGetNextNote (Note, True, ReturnCode);if ReturnCode OK then beginRestore (’GetNextNote: ’, ReturnCode);return;end;until (Note.NotificationTag = CONNECTIONstateCHANGED) &Chapter 3. <strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal Language) 145


Sample Pascal Program(Note.NewState = NONEXISTENT);Restore (’Program terminated successfully’, OK);end.146 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Chapter 4. Virtual Machine Communication Facility InterfaceGeneral InformationThe Virtual Machine Communication Facility (<strong>VM</strong>CF) is part of the ControlProgram (CP) of <strong>VM</strong>. <strong>VM</strong>CF enables virtual machines to send data to and receivedata from any other virtual machine.You can communicate directly with the <strong>TCP</strong><strong>IP</strong> virtual machine using <strong>VM</strong>CF calls,rather than Pascal API or C socket calls. You can use <strong>VM</strong>CF calls when:v You want to write your program in assembler.vYou add <strong>TCP</strong>/<strong>IP</strong> communication to an existing complex program, and it can bedifficult or impossible for your program to monitor <strong>TCP</strong>/<strong>IP</strong> events through thePascal GetNextNote interface.If your program drives the <strong>VM</strong>CF interface directly, do not link any of the <strong>TCP</strong>interface library modules with your program. Consequently, you cannot use any ofthe auxiliary routines, such as the Say functions and timer routines. (You must use<strong>VM</strong> timer support, or support provided by your existing program). <strong>VM</strong>CF consistsof data transfer functions, control functions, a special external interrupt forpending messages, and an external interrupt message header to pass controlinformation and data to another virtual machine.For more information about the <strong>VM</strong>CF interface, see the <strong>VM</strong>/ESA: CP ProgrammingServices book.The following section describes the data structure of the <strong>VM</strong>CF interrupt headerused by <strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong>. The section also lists the <strong>VM</strong>CF functions available with<strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong>. Tables summarizing the CALLCODE for making <strong>VM</strong>CF requestsand receiving notifications from <strong>TCP</strong><strong>IP</strong> virtual machine are provided. Theremainder of the chapter describes these CALLCODE calls in details.Data Structures<strong>VM</strong>CF is implemented with functions invoked using DIAGNOSE X'68' and aspecial 40-byte parameter list. A <strong>VM</strong>CF function is requested by a particularfunction subcode in the FUNC field in the parameter list.Your program uses the standard 40-byte <strong>VM</strong>CF parameter list to submit <strong>VM</strong>CFrequests to the <strong>TCP</strong><strong>IP</strong> virtual machine. The <strong>TCP</strong><strong>IP</strong> virtual machine returns <strong>VM</strong>CFinterrupts results in the similar 40-byte <strong>VM</strong>CF parameter list. The parameter list isthe interrupt header being stored in your virtual machine. In this chapter, fields inthe parameter list and interrupt header are referred to using the data structureheader names in Figure 20 on page 148.© Copyright <strong>IBM</strong> Corp. 1987, 2001 147


<strong>VM</strong>CF InterfaceV1 DS XV2 DS XFUNC DS HMSGID DS FJOBNAME DS CL8VADA DS ALENA DS FVADB DS ALENB DS F* User-doubleword field is divided into the following fields:ANINTEGR DS FCONN DS HCALLCODE DS XRETCODE DS XFigure 20. Assembler Format of the <strong>VM</strong>CF Parameter List Fields<strong>VM</strong>CF Parameter List FieldsThe following describes the <strong>VM</strong>CF parameter list fields.V1 Used for security and data integrity. You can enable your virtual machinefor <strong>VM</strong>CF communication to the <strong>TCP</strong><strong>IP</strong> virtual machine by executing theAUTHORIZE control function. The AUTHORIZE control function is set byissuing a DIAGNOSE Code X'68' Subcode X'0000' assembler call. If you donot set the AUTHORIZE function in V1, check the JOBNAME field whenprocessing each interrupt to ensure that interrupts from other virtualmachines are not misinterpreted as coming from <strong>TCP</strong><strong>IP</strong>. V1 must be zerofor all <strong>VM</strong>CF functions other than AUTHORIZE. To terminate <strong>VM</strong>CFactivities for a virtual machine, issue the UNAUTHORIZE control function.The UNAUTHORIZE control function is set by issuing a DIAGNOSE CodeX'68' Subcode X'0001' assembler call.FUNC The IUCV operation.V2 Reserved for <strong>IBM</strong> use, and should be X’00’ initially.MSGIDContains a unique message identifier associated with a transaction. Youmust use a unique, even number for each outstanding transaction. Asimple method is to use consecutive, even numbers for each transaction.JOBNAMESpecifies the user ID of the virtual machine making <strong>VM</strong>CF requests. Youmust set this field to the user ID of the <strong>TCP</strong><strong>IP</strong> virtual machine.VADA Contains the address of the source or destination address depending onthe <strong>VM</strong>CF function requested.LENA Contains the length of the data sent by a user, the length of a RECEIVEbuffer, or the length of an external interrupt buffer, whichever is specifiedin the VADA field.VADB Contains the address of a source virtual machine’s REPLY buffer for <strong>VM</strong>CFrequest.LENB Specifies the length of the source virtual machine’s REPLY buffer.The use of each field is described individually for each <strong>TCP</strong>/<strong>IP</strong> function.<strong>VM</strong>CF Interrupt Header FieldsThe following describes the <strong>VM</strong>CF parameter list fields for the interrupt header.V1 Sets the <strong>VM</strong>CMRESP flag, which is the interrupt in response to a148 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


transaction initiated by your virtual machine. If the <strong>TCP</strong><strong>IP</strong> virtual machineresponds using the REJECT function, the <strong>VM</strong>CMRJCT flag is also set. Thisflag by itself does not usually indicate that the transaction wasunsuccessful. Your program should check the completion status code in theRETCODE field, as described for each function.ANINTEGRChecks the status of <strong>VM</strong>CF transactions. It is a field, of fullword length(four bytes), used to check the status of <strong>VM</strong>CF transactions. The field isdescribed for each function.CONNEstablishes a <strong>TCP</strong> connection. If a connection between your virtualmachine and <strong>TCP</strong><strong>IP</strong> virtual machine was established successfully and theRETCODE field indicates OK, the connection number of the newconnection is stored in this field.CALLCODECalls instructions to be passed by your program when initiating a <strong>VM</strong>CFfunction to interface with <strong>TCP</strong><strong>IP</strong> virtual machine. If the interrupt is inresponse to a transaction initiated by your virtual machine (<strong>VM</strong>CMRESPflag set in V1), the CALLCODE value is the same as the value set by yourprogram when it initiated the transaction.RETCODEContains the completion status codes of a transaction. Return codesreported in this field are taken from the same set used by Pascal programs(see “Appendix A. Pascal Return Codes” on page 405). Further informationis given in the description of each function.<strong>VM</strong>CF FunctionsTable 16 lists the available <strong>VM</strong>CF functions, with descriptions, to communicatewith the <strong>TCP</strong><strong>IP</strong> virtual machine.Table 16. Available <strong>VM</strong>CF Functions<strong>VM</strong>CF InterfaceFunction Code DescriptionAUTHORIZE Control Initializes <strong>VM</strong>CF for a given virtual machine. OnceAUTHORIZE is executed, the virtual machine can executeother <strong>VM</strong>CF functions and receive messages or requestsfrom other users.UNAUTHORIZE Control Terminates <strong>VM</strong>CF activity.SEND Data Directs a message or block of data to another virtualmachine.SEND/RECV Data Directs a message or block of data to another virtualmachine, and requests a reply.RECEIVE Data Allows you to accept selective messages or data sent usingthe SEND or SEND/RECV functions.REPLY Data Allows you to direct data back to the originator of aSEND/RECV function, simulating duplex communication.REJECT Data Allows you to reject specific SEND or SEND/RECVrequests pending for your virtual machine.Chapter 4. Virtual Machine Communication Facility Interface 149


<strong>VM</strong>CF InterfaceTable 16. Available <strong>VM</strong>CF Functions (continued)Function Code DescriptionNote:Data Indicates a data transferControlIndicates a <strong>VM</strong>CF control function<strong>VM</strong>CF <strong>TCP</strong><strong>IP</strong> Communication CALLCODE RequestsTable 17 lists the equate values and available calls for initiating a <strong>VM</strong>CF <strong>TCP</strong><strong>IP</strong>request; it also includes a description of each CALLCODE request.Table 17. <strong>VM</strong>CF <strong>TCP</strong><strong>IP</strong> CALLCODE RequestsCall Code Equates DescriptionCONNECTIONclosing 00 Data may no longer be transmitted on thisconnection since the <strong>TCP</strong>/<strong>IP</strong> service is in the processof closing down the process.LISTENING 01 Waiting for a foreign site to open a connection.NONEXISTENT 02 The connection no longer exists.OPEN 03 Data can go either way on the connection.RECEIVINGonly 04 Data can be received but not sent on this connection,because the client has done a one-way close.SENDINGonly 05 Data can be sent out but not received on thisconnection. This means that the foreign site hasdone a one way close.TRYINGtoOPEN 06 Trying to contact a foreign site to establish aconnection.ABORTtcp 100 Terminates a <strong>TCP</strong> connection.BEGINtcp<strong>IP</strong>service 101 Initializes a <strong>TCP</strong>/<strong>IP</strong> connection between yourprogram and the <strong>TCP</strong><strong>IP</strong> virtual machine.CLOSEtcp 102 Initiates the closing of a <strong>TCP</strong> connection.CLOSEudp 103 Initiates the closing of a UDP connection.ENDtcp<strong>IP</strong>service 104 Terminates the use of <strong>TCP</strong><strong>IP</strong> services. All existing<strong>TCP</strong> connections are reset, all open UDP ports arecanceled, and all <strong>IP</strong> protocols are released.HANDLEnotice 105 Specifies the types of notifications to be receivedfrom <strong>TCP</strong><strong>IP</strong>.IShostLOCAL 106 Determines whether a given internet address is oneof your host’s local addresses.MONITORcommand 107 Instructs <strong>TCP</strong><strong>IP</strong> to obey a file of commands.MONITORquery 108 Obtains status information from the <strong>TCP</strong><strong>IP</strong> virtualmachine or requests that it performs certainfunctions.OPENtcp 110 Initiates a <strong>TCP</strong> connection.OPENudp 111 Initiates a UDP connection.OPTIONtcp 112 Sets an option for a <strong>TCP</strong> connection.RECEIVEtcp 113 Tells <strong>TCP</strong><strong>IP</strong> that you are ready to receive data on aspecified <strong>TCP</strong> connection.150 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Table 17. <strong>VM</strong>CF <strong>TCP</strong><strong>IP</strong> CALLCODE Requests (continued)<strong>VM</strong>CF InterfaceCall Code Equates DescriptionNRECEIVEudp 115 Tells <strong>TCP</strong><strong>IP</strong> that your program is ready to receive aUDP datagram on a particular port.SENDtcp 118 Sends data on a <strong>TCP</strong> connection. The SENDtcptransaction is unsuccessful if the receiving <strong>TCP</strong><strong>IP</strong>virtual machine has insufficient buffer space toreceive the data.SENDudp 119 Sends a UDP datagram.STATUStcp 120 Obtains a Connection Information Record giving thecurrent status of a <strong>TCP</strong> connection.FRECEIVEtcp 121 Tells <strong>TCP</strong><strong>IP</strong> virtual machine that you are ready toreceive data on a specified <strong>TCP</strong> connection. <strong>TCP</strong><strong>IP</strong>does not respond or send a notification until thedata has been placed in the receiving buffer or theconnection has been closed.FSENDtcp 122 Sends data to a <strong>TCP</strong> connection. FSENDtcp waits foravailable receiving buffer space in the <strong>TCP</strong><strong>IP</strong> virtualmachine before completing the <strong>VM</strong>CF transaction.CLOSEraw<strong>IP</strong> 123 Tells <strong>TCP</strong><strong>IP</strong> that your program does not handle theprotocol any longer. Any queued incoming packetsare discarded.OPENraw<strong>IP</strong> 124 Initiates a connection and tells <strong>TCP</strong><strong>IP</strong> virtualmachine that your program is ready to send andreceive packets of a specified <strong>IP</strong> protocol.RECEIVEraw<strong>IP</strong> 125 Tells <strong>TCP</strong><strong>IP</strong> that your program is ready to receiveraw <strong>IP</strong> packets of a given protocol. Your programreceives a RAW<strong>IP</strong>packetsDELIVERED notification whena packet arrives.SENDraw<strong>IP</strong> 126 Tells <strong>TCP</strong><strong>IP</strong> virtual machine to send raw <strong>IP</strong> packetsof a given protocol number.PINGreq 127 Sends an ICMP echo request to a specified host andwait a specified time for a response.<strong>VM</strong>CF <strong>TCP</strong><strong>IP</strong> Communication CALLCODE NotificationsTable 18 lists the equate values for the CALLCODE field when <strong>VM</strong>CF <strong>TCP</strong><strong>IP</strong> sendsa notification to your program. The table includes a description of eachCALLCODE response.Table 18. <strong>VM</strong>CF <strong>TCP</strong><strong>IP</strong> CALLCODE NotificationsNotification Code Equates DescriptionBUFFERspaceAVAILABLE 10 Notification that there is space available tosend data on this connection. The space iscurrently set to 8192 bytes of buffer space.CONNECTIONstateCHANGED 11 Notification that the state of the connectionbetween the <strong>TCP</strong><strong>IP</strong> virtual machine andyour program has changed.DATAdelivered 12 Notification that the <strong>TCP</strong><strong>IP</strong> virtual machinedata was delivered to your program, afterissuing a RECEIVEtcp or FRECEIVEtcp call.Chapter 4. Virtual Machine Communication Facility Interface 151


<strong>VM</strong>CF InterfaceTable 18. <strong>VM</strong>CF <strong>TCP</strong><strong>IP</strong> CALLCODE Notifications (continued)Notification Code Equates DescriptionURGENTpending 15 Notification that there is queued data on a<strong>TCP</strong> connection not yet received by yourprogram.UDPdatagramDELIVERED 16 Notification that UDP datagram has beendelivered to your program after issuing aNRECEIVEudp call to the <strong>TCP</strong><strong>IP</strong> virtualmachine.UDPdatagramSPACEavailable 17 Notification that buffer space is available toprocess the data, after an error occurredperforming a SENDudp call.RAW<strong>IP</strong>packetsDELIVERED 24 Notification that your buffer has receivedthe raw <strong>IP</strong> packets.RAW<strong>IP</strong>spaceAVAILABLE 25 Notification that buffer space is available toprocess the data. This notification is sentafter the SENDrawip call was rejected by<strong>TCP</strong><strong>IP</strong> virtual machine.RESOURCESavailable 28 Notification that the resources needed toinitiate a <strong>TCP</strong> connection are now available.This notification is sent only if a previousOPENtcp call received a ZEROresources returncode.UDPresourcesAVAILABLE 29 Notification that the resources needed toinitiate a UDP connection are now available.This notification is sent only if a previousOPENudp call received a UDPzeroRESOURCESreturn code.PINGresponse 30 Notification that your ping request from thePINGreq call has been received or that thetime-out limit or your request has beenreached.DUMMYprobe 31 Notification that the <strong>TCP</strong><strong>IP</strong> virtual machineis monitoring your machineACTIVEprobe 32 Notification that the <strong>TCP</strong><strong>IP</strong> virtual machineis monitoring your machine forresponsiveness<strong>TCP</strong>/UDP/<strong>IP</strong> Initialization and Termination ProceduresThis section contains information about procedures for initializing and terminating<strong>TCP</strong>/UDP/<strong>IP</strong> connections.BEGINtcp<strong>IP</strong>serviceYour program performs the BEGINtcp<strong>IP</strong>service call after doing a <strong>VM</strong>CFAUTHORIZE function, but before performing any other <strong>TCP</strong>/<strong>IP</strong> functions. TheBEGINtcp<strong>IP</strong>service call informs <strong>TCP</strong><strong>IP</strong> that your virtual machine uses <strong>TCP</strong><strong>IP</strong>services. An ENDtcp<strong>IP</strong>service call is logically performed first, in the case whereyour virtual machine already has <strong>TCP</strong><strong>IP</strong> resources allocated.152 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


FUNC: SENDVADA: 0LENA: 1VADB: 0 or, if your application supports probe messages (see thedescriptions of the DUMMYprobe and ACTIVEprobe CALLCODEnotifications), X’80000000’LENB: 0CALLCODE: BEGINtcp<strong>IP</strong>serviceThe <strong>TCP</strong><strong>IP</strong> virtual machine responds using the <strong>VM</strong>CF REJECT function. The<strong>VM</strong>CF interrupt header, stored in your virtual machine by the response interrupt,contains a return code in the RETCODE field. The return code can be any of thoselisted for the BeginTcpIp Pascal procedure (page 110).HANDLEnoticeYour program performs the HANDLEnotice call to specify the types of notificationsto be received from <strong>TCP</strong><strong>IP</strong>. The VADB field in the <strong>VM</strong>CF parameter list contains anotification mask, with 1 bit set for each notification you want to handle. The bit tobe set for each notification type is shown in Figure 21.Figure 21 shows the equates used for notification mask in the HANDLEnotice call.MaskBUFFERspaceAVAILABLE EQU X’00000001’MaskCONNECTIONstateCHANGED EQU X’00000002’MaskDATAdelivered EQU X’00000004’MaskURGENTpending EQU X’00000020’MaskUDPdatagramDELIVERED EQU X’00000040’MaskUDPdatagramSPACEavailable EQU X’00000080’MaskRAW<strong>IP</strong>packetsDELIVERED EQU X’00004000’MaskRAW<strong>IP</strong>spaceAVAILABLE EQU X’00008000’MaskRESOURCESavailable EQU X’00040000’MaskUDPresourcesAVAILABLE EQU X’00080000’MaskPINGresponse EQU X’00100000’<strong>VM</strong>CF InterfaceFigure 21. Equates for Notification Mask in the HANDLEnotice CallEach HANDLEnotice call must specify all the notification types to be handled.Notification types specified in previous HANDLEnotice calls are not stored.FUNC: SENDVADA: 0LENA: 1VADB: Note maskLENB: 0CALLCODE: HANDLEnoticeThe <strong>TCP</strong><strong>IP</strong> virtual machine responds using the <strong>VM</strong>CF REJECT function. The<strong>VM</strong>CF interrupt header contains a return code in the RETCODE field. The returncode can be any of those listed for the Handle Pascal procedure (see “Handle” onpage 114).ENDtcp<strong>IP</strong>serviceYour program performs the ENDtcp<strong>IP</strong>service call when it has finished using <strong>TCP</strong><strong>IP</strong>services. All existing <strong>TCP</strong> connections are reset (aborted), all open UDP port opensare canceled, and all <strong>IP</strong> protocols are released.Chapter 4. Virtual Machine Communication Facility Interface 153


<strong>VM</strong>CF InterfaceFUNC: SENDVADA: 0LENA: 1VADB: 0LENB: 0CALLCODE: ENDtcp<strong>IP</strong>service<strong>TCP</strong> CALLCODE RequestsThe <strong>TCP</strong><strong>IP</strong> virtual machine responds using the <strong>VM</strong>CF REJECT function. The<strong>VM</strong>CF interrupt header indicates a return code of OK in the RETCODE field.The following sections describe the <strong>VM</strong>CF interrupt headers that are stored in yourvirtual machine for CALLCODE calls used to make <strong>TCP</strong> requests.OPENtcpThe OPENtcp call initiates a <strong>TCP</strong> connection. Your program sends a ConnectionInformation Record to <strong>TCP</strong><strong>IP</strong>. Figure 22 gives the assembler format of the record.Figure 23 gives the equates for the assorted constants used to set up the record. Formore information about the usage of the fields of the Connection InformationRecord, see “TcpOpen and TcpWaitOpen” on page 134.Connection DS HOpenAttemptTimeout DS FSecurity DS HCompartment DS HPrecedence DS XBytesToRead DS FUnackedBytes DS FConnectionState DS XLocalSocket.Address DS FLocalSocket.Port DS HForeignSocket.Address DS FForeignSocket.Port DS HFigure 22. Assembler Format of the Connection Information Record for <strong>VM</strong>UNSPECIFIEDconnection EQU -48DEFAULTsecurity EQU 0DEFAULTcompartment EQU 0DEFAULTprecedence EQU 0UNSPECIFIEDaddress EQU 0UNSPECIFIEDport EQU X’FFFF’ANintegerFLAGrequestERR EQU X’80000000’Figure 23. Miscellaneous Assembler ConstantsFUNC: SEND/RECVVADA: Address of Connection Information Record initialized byyour programLENA: Length of Connection Information RecordVADB: Address of Connection Information Record to be filled inwith <strong>TCP</strong><strong>IP</strong> replyLENB: Length of Connection Information RecordCONN: UNSPECIFIEDconnectionCALLCODE: OPENtcp154 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


If the open attempt cannot be initiated, the <strong>TCP</strong><strong>IP</strong> virtual machine responds usingthe <strong>VM</strong>CF REJECT function. The <strong>VM</strong>CF interrupt header, contains a return code inthe RETCODE field. The return code can be any of those listed for the TcpOpenPascal procedure.If the OPENtcp call was rejected because not enough <strong>TCP</strong><strong>IP</strong> resources wereavailable, a ZEROresources code is returned. When the <strong>TCP</strong><strong>IP</strong> resources areavailable, a notice of RESOURCESavailable is sent to your program.If the open attempt is not immediately rejected, the <strong>TCP</strong><strong>IP</strong> virtual machine uses the<strong>VM</strong>CF RECEIVE function to receive the Connection Information Record describingthe connection to be opened. If the connection then cannot be initiated, <strong>TCP</strong><strong>IP</strong>responds using the <strong>VM</strong>CF REJECT function. The RETCODE field in the <strong>VM</strong>CFinterrupt header is set as described in the previous paragraph.If the open was successfully initiated, the <strong>TCP</strong><strong>IP</strong> virtual machine responds usingthe <strong>VM</strong>CF REPLY function to send back the updated Connection InformationRecord. The Connection field of the Connection Information Record contains theconnection number of the new connection. The RETCODE field in the <strong>VM</strong>CFinterrupt header indicates OK, and the CONN field also contains the connectionnumber of the new connection. The connection is not yet open; your programreceives notification(s) during the opening sequence. For more information aboutNotificationInfoType, see the section on the Pascal under “Notification Record” onpage 98 and see also “CALLCODE Notifications” on page 163.SENDtcp and FSENDtcpThe SENDtcp or FSENDtcp calls send data on a <strong>TCP</strong> connection. For the advantagesand disadvantages of using each function, and for information about sending <strong>TCP</strong>data, see “TcpFSend, TcpSend, and TcpWaitSend” on page 131.FUNC: SENDVADA: Address of dataLENA: Length of dataVADB: 1 if push desired, else 0LENB: 1 if urgent data, else 0CONN: Connection number from openCALLCODE: SENDtcp or FSENDtcp<strong>VM</strong>CF InterfaceIf <strong>TCP</strong><strong>IP</strong> can successfully queue the data for sending, it responds with the <strong>VM</strong>CFRECEIVE function. The <strong>VM</strong>CF interrupt header indicates a RETCODE of OK.If <strong>TCP</strong><strong>IP</strong> cannot queue the data for sending, it responds with the <strong>VM</strong>CF REJECTfunction. The RETCODE field indicates the type of error. The return code can beany of those listed for the TcpSend Pascal procedure. For a list of the return codes,see “TcpFSend, TcpSend, and TcpWaitSend” on page 131.If the SENDtcp transaction is unsuccessful, because of insufficient space in the bufferof the receiving <strong>TCP</strong><strong>IP</strong> virtual machine, a return code of NObufferSPACE is placedin the RETCODE field. A notification of BUFFERspaceAVAILABLE is sent, on thisconnection, when the space is available to process data.TcpFSend is the same as FSENDtcp. If <strong>TCP</strong><strong>IP</strong> cannot accept the data, because of abuffer shortage, it does not respond immediately. Instead, it waits until space isavailable, and then uses <strong>VM</strong>CF RECEIVE to receive the data. While it is waiting, ifthe connection is reset, it responds with <strong>VM</strong>CF REJECT, with a return code asdescribed previously. In summary, <strong>TCP</strong><strong>IP</strong> may not respond immediately toFSENDtcp, and the response, after waiting, may indicate either success or failure. IfChapter 4. Virtual Machine Communication Facility Interface 155


<strong>VM</strong>CF Interface<strong>TCP</strong><strong>IP</strong> responds with REJECT, your program can check theANintegerFLAGrequestERR bit in the ANINTEGR field to determine if the requestwas rejected during initial or retry processing (bit on) or because of connectionclosing (bit off).Your program does not need to wait for a response from SENDtcp or FSENDtcp<strong>VM</strong>CF transaction. It can issue functions involving other connections, beforereceiving a response from making a SENDtcp or FSENDtcp <strong>VM</strong>CF transaction.There is a limit of 50 outstanding <strong>VM</strong>CF transactions for each virtual machine;therefore, your program can have FSENDtcp functions outstanding on only 50connections at a time. If your application needs more outstanding sends, use theSENDtcp function.FRECEIVEtcpThe FRECEIVEtcp call tells <strong>TCP</strong><strong>IP</strong> that you are ready to receive data on a specified<strong>TCP</strong> connection. <strong>TCP</strong><strong>IP</strong> does not respond or send a notification notice until data isreceived or the connection is closed. Consequently, each outstanding FRECEIVEtcpfunction results in an outstanding <strong>VM</strong>CF transaction. There is a limit of 50outstanding <strong>VM</strong>CF transactions for each virtual machine; you can therefore haveFRECEIVEtcp functions outstanding on only 50 connections at one time. If yourapplication needs more outstanding receives, use the RECEIVEtcp function.Your program does not need to wait for a response from FRECEIVEtcp. It can issuefunctions involving other connections, before receiving a response fromFRECEIVEtcp.For general information about receiving <strong>TCP</strong> data, see the TcpFReceive Pascalprocedure under “TcpFReceive, TcpReceive, and TcpWaitReceive” on page 128.FUNC: SEND/RECVVADA: 0LENA: 1VADB: Address of buffer to receive dataLENB: Length of buffer to receive dataCONN: Connection number from openCALLCODE: FRECEIVEtcpIf <strong>TCP</strong><strong>IP</strong> accepts the request, your program receives no response until <strong>TCP</strong><strong>IP</strong> isready to deliver data to your buffer, or until the request is canceled, because theconnection has closed without delivering data.When <strong>TCP</strong><strong>IP</strong> is ready to deliver data for this connection, it issues a <strong>VM</strong>CF REPLYfunction. Significant fields in the <strong>VM</strong>CF interrupt header are:LENB Indicates the residual count. Subtract this from the size of your buffer(LENB value in parameter list) to determine the number of bytes actuallydelivered.ANINTEGRContains a value where the high-order byte is nonzero if data was pushed;otherwise, it is zero. The low-order three bytes are interpreted as a 24-bitinteger, indicating the offset of the byte following the last byte of urgentdata, measured from the first byte of data delivered to your buffer. If it iszero or a negative number, then there is no urgent data pending.CONNSpecifies the connection number.156 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


<strong>VM</strong>CF InterfaceRETCODEOKIf <strong>TCP</strong><strong>IP</strong> responds with the <strong>VM</strong>CF REJECT function (<strong>VM</strong>CFRJCT flag set in the<strong>VM</strong>CF interrupt header), then one of the following occurred:vv<strong>TCP</strong><strong>IP</strong> did not accept the request, in which case the ANintegerFLAGrequestERRbit in ANINTEGR is on.<strong>TCP</strong><strong>IP</strong> accepted the request initially, but the connection closed before data wasdelivered. ANintegerFLAGrequestERR bit in ANINTEGR is off. In this case, theRETCODE field indicates one of the reason codes listed forCONNECTIONstateCHANGED with the NewState field set to NONEXISTENT.For more information, see 2 on page 101.Note: Your program does not have to take any special action in this case,because it receives one or more CONNECTIONstateCHANGEDnotifications indicating that the connection is closing.RECEIVEtcpThe RECEIVEtcp call tells <strong>TCP</strong><strong>IP</strong> that you are ready to receive data on a specified<strong>TCP</strong> connection. Unlike FRECEIVEtcp, <strong>TCP</strong><strong>IP</strong> responds immediately to RECEIVEtcp.You can have more than 50 receive requests pending using RECEIVEtcp withoutexceeding the limit of 50 outstanding <strong>VM</strong>CF transactions.For more information about receiving <strong>TCP</strong> data, see the TcpReceive Pascalprocedure under “TcpFReceive, TcpReceive, and TcpWaitReceive” on page 128.FUNC: SENDVADA: 0LENA: 1VADB: 0LENB: Length of buffer to receive dataCONN: Connection number from openCALLCODE: RECEIVEtcp<strong>TCP</strong><strong>IP</strong> responds with the <strong>VM</strong>CF REJECT function. The RETCODE field of the<strong>VM</strong>CF interrupt buffer indicates whether the request was successful. If the requestwas successful, with a RETCODE of OK, the data is delivered to your buffer and anotification of DATAdelivered is sent to your program. If the request was notsuccessful, then the return code is one of those listed for the TcpReceive Pascalprocedure.CLOSEtcpThe CLOSEtcp call initiates the closing of a <strong>TCP</strong> connection. For more informationabout the close connection call, see the Pascal procedure, “TcpClose” on page 127.FUNC: SENDVADA: 0LENA: 1VADB: 0LENB: 0CONN: Connection number from openCALLCODE: CLOSEtcp<strong>TCP</strong><strong>IP</strong> responds with the <strong>VM</strong>CF REJECT function. The RETCODE field of the<strong>VM</strong>CF interrupt buffer contains the return code. The return code is one of thoselisted for the TcpClose Pascal procedure on page 127.Chapter 4. Virtual Machine Communication Facility Interface 157


<strong>VM</strong>CF InterfaceABORTtcpThe ABORTtcp call terminates a <strong>TCP</strong> connection. For more information about theabort connection call, see the Pascal procedure, “TcpAbort” on page 127.<strong>TCP</strong><strong>IP</strong> responds with the <strong>VM</strong>CF REJECT function. The RETCODE field of the<strong>VM</strong>CF interrupt buffer contains the return code. It is one of those listed for theTcpAbort Pascal procedure.STATUStcpThe STATUStcp call obtains a Connection Information Record giving the currentstatus of a <strong>TCP</strong> connection. For the assembler format of the ConnectionInformation Record, see Figure 22 on page 154. For more information about theconnection status call, see the Pascal procedure, “TcpStatus” on page 137.<strong>TCP</strong><strong>IP</strong> responds with the <strong>VM</strong>CF REPLY function, filling in the record whoseaddress you supplied in LENB. The record is valid only if the return code, in theRETCODE field of the <strong>VM</strong>CF interrupt header, returns OK. Otherwise, the returncode is one of those listed for the TcpStatus Pascal procedure.OPTIONtcpThe OPTIONtcp call sets an option for a <strong>TCP</strong> connection. For more informationabout the connection options, see the Pascal procedure “TcpOption” on page 136.UDP CALLCODE RequestsFUNC: SENDVADA: 0LENA: 1VADB: 0LENB: 0CONN: Connection number from openCALLCODE: ABORTtcpFUNC: SEND/RECVVADA: 0LENA: 1VADB: Address of Connection Information Record to fill inLENB: Length of Connection Information Record to fill inCONN: Connection number from openCALLCODE: STATUStcpFUNC: SENDVADA: 0LENA: 1VADB: Option nameLENB: Option valueCONN: Connection number from openCALLCODE: OPTIONtcp<strong>TCP</strong><strong>IP</strong> responds with the <strong>VM</strong>CF REJECT function. The RETCODE field of the<strong>VM</strong>CF interrupt buffer contains the return code. The return code is one of thoselisted for the Pascal TcpOption procedure.The following sections describe the <strong>VM</strong>CF interrupt headers, which are stored inyour virtual machine, for CALLCODE calls used to make UDP requests.158 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


OPENudpThe OPENudp call opens a UDP port. For more information about the UDP openfunction, see the Pascal procedure, “UdpOpen” on page 139.FUNC: SENDVADA: 0LENA: 1VADB: Local port number or UNSPECIFIEDportLENB: Local addressCONN: Connection number: An arbitrary number, which your programuses in subsequent actions involving this port.CALLCODE: OPENudp<strong>TCP</strong><strong>IP</strong> responds with the <strong>VM</strong>CF REJECT function. The RETCODE field in the<strong>VM</strong>CF interrupt header can be any of the return codes listed for the UdpOpenPascal procedure. If the OPENudp call was rejected, because not enough <strong>TCP</strong><strong>IP</strong>resources were available, a UDPzeroRESOURCES code is returned. When the<strong>TCP</strong><strong>IP</strong> resources are available, a notice of UDPresourcesAVAILABLE is sent to yourprogram.SENDudpThe SENDudp call sends a UDP datagram. For more information about the UDPsend function, see the Pascal procedure, “UdpSend” on page 141.FUNC: SENDVADA: Address of datagram dataLENA: Length of datagram data (up to 8492 bytes)VADB: Destination port numberLENB: Destination addressCONN: Connection numberCALLCODE: SENDudpIf <strong>TCP</strong><strong>IP</strong> can send the datagram, it responds with the <strong>VM</strong>CF RECEIVE function.The RETCODE field in the <strong>VM</strong>CF interrupt header contains a return code of OK. If<strong>TCP</strong><strong>IP</strong> cannot send the datagram, it responds with the <strong>VM</strong>CF REJECT function.The RETCODE field contains one of the return codes listed for the UdpSend Pascalprocedure. When the buffer space is not available to process the data, an error isreturned. The notification message of UDPdatagramSPACEavailable is sent to yourprogram when the buffer space is available to process data.NRECEIVEudpThe NRECEIVEudp call tells <strong>TCP</strong><strong>IP</strong> that your program is ready to receive a UDPdatagram on a particular port. <strong>TCP</strong><strong>IP</strong> responds immediately to inform you whetherit accepted the request. If <strong>TCP</strong><strong>IP</strong> has accepted your request, your program receivesa UDPdatagramDELIVERED notification when a datagram arrives. For moreinformation about receiving UDP datagrams, see the Pascal procedure,“UdpNReceive” on page 139.FUNC: SENDVADA: 0LENA: 1VADB: 0LENB: Size of your buffer to receive datagramCONN: Connection numberCALLCODE: NRECEIVEudp<strong>VM</strong>CF InterfaceChapter 4. Virtual Machine Communication Facility Interface 159


<strong>VM</strong>CF Interface<strong>TCP</strong><strong>IP</strong> responds with the <strong>VM</strong>CF REJECT function. The RETCODE field of the<strong>VM</strong>CF interrupt header contains one of the return codes listed for theUdpNReceive Pascal procedure.CLOSEudpThe CLOSEudp call closes a UDP port. For more information about the CLOSEudp call,see the Pascal procedure, “UdpClose” on page 138.FUNC: SENDVADA: 0LENA: 1VADB: 0LENB: 0CONN: Connection numberCALLCODE: CLOSEudp<strong>IP</strong> CALLCODE Requests<strong>TCP</strong><strong>IP</strong> responds with the <strong>VM</strong>CF REJECT function. The RETCODE field in the<strong>VM</strong>CF interrupt header can be any of the return codes listed for the UdpClosePascal procedure. If the return code is OK, and your program specifiedUNSPECIFIEDport as the port number, the actual port number assigned is encodedin the CONN field of the interrupt header. Add the value of 32 768 to the value inthe CONN field, using unsigned arithmetic, to compute the port number.The following sections describe the <strong>VM</strong>CF interrupt headers, which are stored inyour virtual machine, for CALLCODE calls used to make <strong>IP</strong> requests.OPENrawipThe OPENrawip call tells <strong>TCP</strong><strong>IP</strong> that your program is ready to send and receivepackets of a specified <strong>IP</strong> protocol. For more information, see the Pascal procedure,“RawIpOpen” on page 120.FUNC: SEND/RECVVADA: 0LENA: 1VADB: 0LENB: 0CONN: Protocol numberCALLCODE: OPENrawip<strong>TCP</strong><strong>IP</strong> uses the <strong>VM</strong>CF REJECT function to respond to the request. The RETCODEfield of the <strong>VM</strong>CF interrupt header contains one of the return codes listed for theRawIpOpen Pascal procedure.SENDrawipThe SENDrawip call sends raw <strong>IP</strong> packets of a given protocol number. For moreinformation, see the Pascal procedure, “RawIpSend” on page 121.FUNC: SEND/RECVVADA: Address of buffer containing packets to sendLENA: Length of bufferVADB: 0LENB: 0CONN: (Number of packets shifted left 8 bits) + protocol numberCALLCODE: SENDrawip160 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


If <strong>TCP</strong><strong>IP</strong> immediately determines that the request cannot be fulfilled, It respondswith the <strong>VM</strong>CF REJECT function. Otherwise, it uses the <strong>VM</strong>CF RECEIVE functionto receive your data, followed by <strong>VM</strong>CF REJECT. The RETCODE field of the<strong>VM</strong>CF interrupt header contains one of the return codes listed for the RawIpSendPascal procedure. If <strong>TCP</strong><strong>IP</strong> virtual machine is out of buffers, the data is rejectedand a return code of NObufferSPACE is returned. When buffer space is available,the notification of RAW<strong>IP</strong>spaceAVAILABLE is sent to your program.RECEIVErawipThe RECEIVErawip call tells <strong>TCP</strong><strong>IP</strong> that your program is ready to receive raw <strong>IP</strong>packets of a given protocol. Your program receives a RAW<strong>IP</strong>packetsDELIVEREDnotification when a packet arrives. For information about theRAW<strong>IP</strong>packetsDELIVERED notification record, see the Pascal procedure,“RawIpReceive” on page 120, and the section on the Pascal NotificationInfoTypeunder “Notification Record” on page 98.FUNC: SEND/RECVVADA: 0LENA: 1VADB: 0LENB: Length of your bufferCONN: Protocol numberCALLCODE: RECEIVErawip<strong>TCP</strong><strong>IP</strong> responds with the <strong>VM</strong>CF REJECT function. The RETCODE field of the<strong>VM</strong>CF interrupt header contains one of the return codes listed for theRawIpReceive Pascal procedure.CLOSErawipThe CLOSErawip call tells <strong>TCP</strong><strong>IP</strong> that your program is ready to cease sending andreceiving packets of a specified <strong>IP</strong> protocol. For more information, see the Pascalprocedure, “RawIpClose” on page 119.FUNC: SEND/RECVVADA: 0LENA: 1VADB: 0LENB: 0CONN: Protocol numberCALLCODE: CLOSErawipCALLCODE System Queries<strong>VM</strong>CF Interface<strong>TCP</strong><strong>IP</strong> uses the <strong>VM</strong>CF REJECT function to respond to the request. The RETCODEfield of the <strong>VM</strong>CF interrupt header contains one of the return codes listed for theRawIpClose Pascal procedure.The following sections describe the <strong>VM</strong>CF interrupt headers, which are stored inyour virtual machine, for CALLCODE calls used to make system queries.IShostLOCALThe IShostLOCAL call determines whether a given internet address is one of yourhost’s local addresses. For more information about this procedure, see the Pascalprocedure “LocalAddress” on page 115.Chapter 4. Virtual Machine Communication Facility Interface 161


<strong>VM</strong>CF InterfaceFUNC: SENDVADA: 0LENA: 1VADB: Internet address to be testedLENB: 0CONN: UNSPECIFIEDconnectionCALLCODE: IShostLOCAL<strong>TCP</strong><strong>IP</strong> responds with the <strong>VM</strong>CF REJECT function. The RETCODE field of the<strong>VM</strong>CF interrupt header contains the return code, as described in theIsLocalAddress Pascal procedure section.MONITORcommandThe MONITORcommand call instructs <strong>TCP</strong><strong>IP</strong> to obey a file of commands. For moreinformation, see the Pascal procedure, “MonCommand” on page 116, and for moreinformation about the OBEYFILE command, which uses the MonCommandprocedure, see <strong>TCP</strong>/<strong>IP</strong> Planning and Customization.Owner DS CL8DatasetPassword DS CL8FullDatasetName DS CL44MemberName DS CL8DDName DS CL8Figure 24. Assembler Format of the SpecOfFileType Record for <strong>VM</strong>FUNC: SEND/RECVVADA: Address of SpecOfFile recordLENA: Length of SpecOfFile recordVADB: 0LENB: 0CONN: UNSPECIFIEDconnectionCALLCODE: MONITORcommandIf <strong>TCP</strong><strong>IP</strong> cannot process the request, it responds immediately with the <strong>VM</strong>CFREJECT function. Otherwise, it uses the <strong>VM</strong>CF RECEIVE function to receive theSpecOfFile record provided by your program. It then attempts to process the file,and uses the <strong>VM</strong>CF REJECT function to report the return code. In either case, thereturn code is one of those specified for the MonCommand Pascal procedure.MONITORqueryThe MONITORquery call obtains status information from the <strong>TCP</strong><strong>IP</strong> virtual machineor to request that it performs certain functions. For more information, see thePascal procedure, “MonQuery” on page 117. Assembler formats of constants andrecords used with MONITORquery are:COMMANDcpCMD EQU 6COMMANDdropCONNECTION EQU 8QUERYhomeONLY EQU 9Figure 25. Equates for MonQueryRecordType used in the MONITORquery Call162 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


<strong>VM</strong>CF InterfaceQueryType DS X* For QueryType = QUERYhomeONLY: No other fields* For QueryType = COMMANDcpCMD:CpCmd DS H Length of commandDS 100C Command* For QueryType = COMMANDdropCONNECTION:ORG CpCmdConnection DS HThe Pascal type HomeOnlyListType is an array of 64 InternetAddressTypeelements found in the COMMMAC MACLIB file. The size of InternetAddressTypeis a fullword.If <strong>TCP</strong><strong>IP</strong> cannot process the request, it responds immediately with the <strong>VM</strong>CFREJECT function. Otherwise, it uses the <strong>VM</strong>CF RECEIVE function to receive theMonQueryRecord describing your request, followed by either a <strong>VM</strong>CF REPLY tosend the response to your return buffer (not applicable toCOMMANDdropCONNECTION), or a <strong>VM</strong>CF REJECT to send a return code butno return data. For information about the return codes and the data returned (ifany), see the Pascal procedure, “MonQuery” on page 117.PINGreqThe PINGreq call sends an ICMP echo request (PING request) to a specified hostand wait a specified time for a response. For more information, see the Pascalprocedure “PingRequest” on page 119.CALLCODE NotificationsFigure 26. Assembler Format of the MonQueryRecordTypefor <strong>VM</strong>FUNC: SEND/RECVVADA: Address of MonQueryRecord describing requestLENA: Length of MonQueryRecordVADB: Address of return bufferLENB: Length of return bufferCONN: UNSPECIFIEDconnectionCALLCODE: MONITORqueryFUNC: SENDVADA: 0LENA: 1VADB: Internet address of foreign hostLENB: Length of ping packetANINTEGR: TimeoutCALLCODE: PINGreq<strong>TCP</strong><strong>IP</strong> uses the <strong>VM</strong>CF REJECT function to respond to the request. The RETCODEfield of the <strong>VM</strong>CF interrupt header contains one of the return codes listed for thePingRequest Pascal procedure. If the return code is OK, your program receives aPINGresponse notification later.The following sections describe the <strong>VM</strong>CF interrupt headers that are stored in yourvirtual machine for the various types of notifications. The action that your programshould take is also indicated.For more information about the various notification types, see the PascalNotificationInfoType record under “Notification Record” on page 98.Chapter 4. Virtual Machine Communication Facility Interface 163


<strong>VM</strong>CF InterfaceThe <strong>VM</strong>CF transaction for a notification must be completed before <strong>TCP</strong><strong>IP</strong> sendsyour program another notification. You must ensure that your program takes the<strong>VM</strong>CF actions in the following sections, or <strong>TCP</strong><strong>IP</strong> cannot communicate furtherwith your program.BUFFERspaceAVAILABLEThis interrupt header notifies you that there is space available to send data on thisconnection. The space is currently set to 8192 bytes of buffer space. The notificationis sent after making a SENDtcp call and receiving an unsuccessful return code ofNObufferSPACE in the RETCODE field.FUNC:JOBNAME:VADB:SENDName of the <strong>TCP</strong><strong>IP</strong> virtual machineSpace available to send on this connection, in bytes.Currently always 8192Connection numberCONN:CALLCODE: BUFFERspaceAVAILABLERETCODE: OKYour program should issue the <strong>VM</strong>CF REJECT function, with <strong>VM</strong>CF parmlist copied from the interrupt header, with the following fields changed:V1: 0V2: 0FUNC: REJECTCONNECTIONstateCHANGEDThis interrupt header notifies you that the state of the connection between the<strong>TCP</strong><strong>IP</strong> virtual machine and your program has changed.FUNC: SENDJOBNAME: Name of the <strong>TCP</strong><strong>IP</strong> virtual machineVADB: New connection stateLENB: Reason for state change, if new state is NONEXISTENTCONN: Connection numberCALLCODE: CONNECTIONstateCHANGEDRETCODE: OKYour program should issue the <strong>VM</strong>CF REJECT function, with <strong>VM</strong>CF parmlist copied from the interrupt header, with the following fields changed:V1: 0V2: 0FUNC: REJECTDATAdeliveredThis interrupt header notifies you that the <strong>TCP</strong><strong>IP</strong> virtual machine data wasdelivered to your program, after issuing a RECEIVEtcp or FRECEIVEtcp call.164 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


FUNC:JOBNAME:LENA:VADB:LENB:SENDName of the <strong>TCP</strong><strong>IP</strong> virtual machineLength of data being deliveredNon-zero if data was pushed, else zero.The offset of the byte following the last byte of urgentdata, measured from the first byte of data delivered to yourbuffer. If zero or negative then there is no urgent datapending.Connection numberCONN:CALLCODE: DATAdeliveredRETCODE: OKYour program should issue the <strong>VM</strong>CF RECEIVE function, with <strong>VM</strong>CF parmlist copied from the interrupt header, with the following fields changed:V1: 0V2: 0FUNC: RECEIVEVADA: Address of your buffer to receive data. Buffer should beat least as long as indicated by LENA. LENA is nolarger than the buffer length you specified using theRECEIVEtcp function.URGENTpendingThis interrupt header notifies you that there is queued incoming data on a <strong>TCP</strong>connection not yet received by your program.FUNC:JOBNAME:VADB:LENB:SENDName of the <strong>TCP</strong><strong>IP</strong> virtual machineNumber of bytes of queued incoming data not yet receivedby your program.Subtract 1 from LENB to get the offset of the byte followingthe last byte of urgent data, measured from the first byte notyet received by your program. If this quantity is zero ornegative then there is no urgent data pending.Connection numberCONN:CALLCODE: URGENTpendingRETCODE: OKYour program should issue the <strong>VM</strong>CF REJECT function, with <strong>VM</strong>CF parmlist copied from the interrupt header, with the following fields changed:V1: 0V2: 0FUNC: REJECT<strong>VM</strong>CF InterfaceUDPdatagramDELIVEREDThis interrupt header notifies you that the UDP datagram has been delivered toyour program after issuing a NRECEIVEudp call to the <strong>TCP</strong><strong>IP</strong> virtual machine.Chapter 4. Virtual Machine Communication Facility Interface 165


<strong>VM</strong>CF InterfaceFUNC: SENDJOBNAME: Name of the <strong>TCP</strong><strong>IP</strong> virtual machineLENA: Length of data being delivered.VADB: Source portLENB: Source addressANINTEGR: Length of entire datagram excluding UDP header. If largerthan LENA then thedatagram was too large to fit into the buffer size specifiedin NRECEIVEudp call, and has been truncated.CONN: Connection numberCALLCODE: UDPdatagramDELIVEREDRETCODE: OKYour program should issue the <strong>VM</strong>CF RECEIVE function, with <strong>VM</strong>CF parmlist copied from the interrupt header, with the following fields changed:V1: 0V2: 0FUNC: RECEIVEVADA: Address of your buffer to receive data. Buffer should beat least as long as indicated by LENA.UDPdatagramSPACEavailableThis interrupt header notifies you that buffer space is available to process the data,after an error occurred performing a SENDudp call.FUNC: SENDJOBNAME: Name of the <strong>TCP</strong><strong>IP</strong> virtual machineCONN: Connection numberCALLCODE: UDPdatagramSPACEavailableRETCODE: OKYour program should issue the <strong>VM</strong>CF REJECT function, with <strong>VM</strong>CF parmlist copied from the interrupt header, with the following fields changed:V1: 0V2: 0FUNC: REJECTRAW<strong>IP</strong>packetsDELIVEREDThis interrupt header notifies you that your buffer has received the raw <strong>IP</strong> packets.FUNC: SENDJOBNAME: Name of the <strong>TCP</strong><strong>IP</strong> virtual machineANINTEGR: Total length of datagram being delivered (including <strong>IP</strong> header)LENA: Length of data (including <strong>IP</strong> header) that <strong>TCP</strong><strong>IP</strong>delivers to you.CONN: Low-order byte is protocol number, 3 high order bytesis number of packets, currently always 1.CALLCODE: RAW<strong>IP</strong>packetsDELIVEREDRETCODE: OKYour program should issue the <strong>VM</strong>CF RECEIVE function, with <strong>VM</strong>CF parmlist copied from the interrupt header, with the following fields changed:V1: 0V2: 0FUNC: RECEIVEVADA: Address of your buffer to receive data. Buffer should beat least as long as indicated by LENA.166 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


RAW<strong>IP</strong>spaceAVAILABLEThis interrupt header notifies you that buffer space is available to process the data.This notification is sent after the SENDrawip call was rejected by <strong>TCP</strong><strong>IP</strong> virtualmachine because of insufficient buffer space.FUNC: SENDJOBNAME: Name of the <strong>TCP</strong><strong>IP</strong> virtual machineLENB: Space available. Always equals maximum <strong>IP</strong> datagram size.CONN: Protocol numberCALLCODE: RAW<strong>IP</strong>spaceAVAILABLERETCODE: OKYour program should issue the <strong>VM</strong>CF REJECT function, with <strong>VM</strong>CF parmlist copied from the interrupt header, with the following fields changed:V1: 0V2: 0FUNC: REJECTRESOURCESavailableThis interrupt header notifies you that the resources needed to initiate a <strong>TCP</strong>connection are now available. This notification is sent only if a previous OPENtcpcall received a ZEROresources return code.FUNC: SENDJOBNAME: Name of the <strong>TCP</strong><strong>IP</strong> virtual machineCALLCODE: RESOURCESavailableRETCODE: OKYour program should issue the <strong>VM</strong>CF REJECT function, with <strong>VM</strong>CF parmlist copied from the interrupt header, with the following fields changed:V1: 0V2: 0FUNC: REJECTUDPresourcesAVAILABLEThis interrupt header notifies you that the resources needed to initiate a UDPconnection are now available. This notification is sent only if a previous OPENudpcall received a UDPzeroRESOURCES return code.FUNC: SENDJOBNAME: Name of the <strong>TCP</strong><strong>IP</strong> virtual machineCALLCODE: UDPresourcesAVAILABLERETCODE: OKYour program should issue the <strong>VM</strong>CF REJECT function, with <strong>VM</strong>CF parmlist copied from the interrupt header, with the following fieldschanged:V1: 0V2: 0FUNC: REJECT<strong>VM</strong>CF InterfacePINGresponseThis interrupt header notifies you that your ping request from the PINGreq call hasbeen received or that the time-out limit or your request has been reached.Chapter 4. Virtual Machine Communication Facility Interface 167


<strong>VM</strong>CF InterfaceFUNC: SENDJOBNAME: Name of the <strong>TCP</strong><strong>IP</strong> virtual machineVADB: High order word of elapsed time, in TOD clock formatValid only if ANINTEGR is zeroLENB: Low order word of elapsed time, in TOD clock formatValid only if ANINTEGR is zeroANINTEGR: Return code from ping operationCALLCODE: PINGresponseRETCODE: OKYour program should issue the <strong>VM</strong>CF REJECT function, with <strong>VM</strong>CF parmlist copied from the interrupt header, with the following fields changed:V1: 0V2: 0FUNC: REJECTDUMMYprobeThis interrupt header notifies you that the <strong>TCP</strong><strong>IP</strong> virtual machine is monitoringyour machine so it can determine if it logs off or resets unexpectedly.FUNC: SENDJOBNAME: Name of the <strong>TCP</strong><strong>IP</strong> virtual machineCALLCODE: DUMMYprobeRETCODE: OKYour program should leave this message pending.ACTIVEprobeThis interrupt header notifies you that the <strong>TCP</strong><strong>IP</strong> virtual machine is monitoringyour machine so it can determine if it is still responsive.FUNC: SENDJOBNAME: Name of the <strong>TCP</strong><strong>IP</strong> virtual machineCALLCODE: ACTIVEprobeRETCODE: OKYour program should issue the <strong>VM</strong>CF REJECT function, with the <strong>VM</strong>CFparameter list copied from the interrupt header and with thefollowing fields changed:V1: 0V2: 0FUNC: REJECTThe response to this message must be made within one minute after theassociated interrupt is received.168 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Chapter 5. Inter-User Communication Vehicle SocketsPrerequisite KnowledgeAvailable FunctionsThe Inter-User Communication Vehicle (IUCV) socket API is an assemblerlanguage application programming interface that can be used with <strong>TCP</strong>/<strong>IP</strong>. Whilenot every C socket library function is provided, all of the basic operationsnecessary to communicate with other socket programs are present.This chapter assumes you have a working knowledge of IUCV, as documented in<strong>VM</strong>/ESA CP Programming Services.You must also know how and when to use the CMS CMSIUCV macro or the GCSIUCVCOM macro, depending on the execution environment, as documented in<strong>VM</strong>/ESA CMS Application Development <strong>Reference</strong> for Assembler or <strong>VM</strong>/ESA GroupControl System, respectively.You should also have a working knowledge of <strong>TCP</strong>/<strong>IP</strong> sockets.Only these functions are available when you use the IUCV socket interface:Table 19. Socket functions available using IUCVACCEPTREADBINDREADVCLOSERECVCONNECTRECVFROMFCNTLREC<strong>VM</strong>SGGETCLIENTIDSELECTGETHOSTIDSELECTEXGETHOSTNAMESENDGETPEERNAMESENDMSGGETSOCKNAMESENDTOGETSOCKOPTSETSOCKOPTGIVESOCKETSHUTDOWNIOCTLSOCKET (AF_INET sockets only)LISTENTAKESOCKETMAXDESCWRITEWRITEV© Copyright <strong>IBM</strong> Corp. 1987, 2001 169


IUCV SocketsSocket Programming with IUCV<strong>TCP</strong>/<strong>IP</strong> sockets are manipulated by using the following assembler macros:Macro Library DescriptionIUCV HCPGPI Provides the mechanisms for setting values in theIUCV input parameter list and for executing theIUCV instruction<strong>IP</strong>ARML HCPGPI Mapping macro for the IUCV parameter list and theexternal interrupt buffer.HNDIUCV DMSGPI Informs CMS that your program wishes to handleIUCV or APPC/<strong>VM</strong> interrupts. Only those interruptsoccurring on IUCV paths that your applicationcreated will be routed to your program.CMSIUCV DMSGPI Used to perform IUCV CONNECT and SEVERfunctions. It enables multiple IUCV or APPC/<strong>VM</strong>applications to run at the same without interference.IUCVINI GCTGPI Similar to HNDIUCV, but for the GCS executionenvironment.IUCVCOM GCTGPI Similar to CMSIUCV, but for the GCS executionenvironment. In addition to providing multipleapplication support, it provides a way for GCSprograms running in problem state to use IUCVservices.A typical socket application uses only four IUCV operations: CONNECT, SEND(with reply), PURGE, and SEVER. CONNECT establishes the IUCV connectionwith the <strong>TCP</strong>/<strong>IP</strong> virtual machine, SEND performs initialization and socketoperations, PURGE cancels an outstanding socket operation, and SEVER deletesthe IUCV connection.If an IUCV operation completes with condition code 0, the requested operationwas successfully started. An IUCV interrupt will be received when the operationcompletes. When your interrupt routine receives control, it receives a pointer to theexternal interrupt buffer which contains information about the IUCV function thatcompleted. The <strong>IP</strong>TYPE field of the external interrupt buffer (mapped by <strong>IP</strong>ARML)identifies the interrupt:<strong>IP</strong>TYPE Interrupt Name DescriptionX'02' Connection Complete Acknowledgement that <strong>TCP</strong>/<strong>IP</strong> has acceptedyour request to establish an IUCV connection(IUCV CONNECT)X'03' Connection Severed Your IUCV connection has been deleted by<strong>TCP</strong>/<strong>IP</strong>X'07' Message complete The requested socket function has completedNote: <strong>IP</strong>TYPE is byte 3 of the external interrupt buffer.While there are other types of IUCV interrupts, they are not normally seen on<strong>TCP</strong>/<strong>IP</strong> IUCV socket paths. <strong>VM</strong>/ESA CP Programming Services has a completedescription of each interrupt type.170 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


If an IUCV operation completes with condition code 1, the requested functioncould not be performed. The exact cause of the error is stored in byte 3 of theIUCV parameter list (<strong>IP</strong>RCODE). See the description of each IUCV function in<strong>VM</strong>/ESA CP Programming Services for the possible return codes.Note: CMSIUCV and IUCVCOM use return codes in general register 15 to indicatethe success or failure of the operation. Refer to <strong>VM</strong>/ESA CMS ApplicationDevelopment <strong>Reference</strong> for Assembler or <strong>VM</strong>/ESA Group Control System fordetails on these system services.If an IUCV PURGE operation completes with condition code 2, it means that<strong>TCP</strong>/<strong>IP</strong> has already finished processing the socket request.Preparing to use the IUCV Socket APIIUCV SocketsBefore the socket functions can be used, an IUCV socket API environment must beestablished. This is done in two steps:1. Establish an IUCV connection to the <strong>TCP</strong>/<strong>IP</strong> service virtual machine.2. Send an initialization message to <strong>TCP</strong>/<strong>IP</strong>, identifying your application anddefining how the IUCV connection will be used.Establishing an IUCV connection to <strong>TCP</strong>/<strong>IP</strong>To create an IUCV connection to the <strong>TCP</strong>/<strong>IP</strong> service virtual machine, issue IUCVCONNECT with the following parameters:KeywordUSERIDPRTYPRMDATAQUIESCEMSGLIMUSERDTACONTROLValueThe user ID of the <strong>TCP</strong>/<strong>IP</strong> virtual machine.NOYESNOIf this IUCV connection may have more than one outstandingsocket function on it at the same time, set MSGLIM to themaximum number of socket calls that may be outstandingsimultaneously on this path. Otherwise, set it to zero.Binary zerosNOIf IUCV CONNECT returns condition code 0, you subsequently receive either aConnection Complete external interrupt or a Connection Severed external interrupt.If you receive a Connection Severed interrupt now or later, see “Severing the IUCVConnection” on page 173 for more information.To ensure that your program does not interfere with other IUCV or APPC/<strong>VM</strong>applications, your program should use the HNDIUCV and CMSIUCV macros inCMS, or the IUCVINI and IUCVCOM macros in GCS.Initializing the IUCV ConnectionIf you receive a Connection Complete interrupt in response to IUCV CONNECT,then <strong>TCP</strong>/<strong>IP</strong> has accepted the connection request.Chapter 5. Inter-User Communication Vehicle Sockets 171


IUCV SocketsYour program responds by sending an initialization message using IUCV SEND to<strong>TCP</strong>/<strong>IP</strong>, identifying your application and the way that it will use the IUCV socketinterface.When the IUCV SEND completes, then, if the <strong>IP</strong>AUDIT field shows no error, thereply buffer has been filled. The maxsock field indicates that maximum number ofsockets you can open on this IUCV path at the same time.Your program can now issue any supported socket call. See “Issuing Socket Calls”on page 174.The initialization message is sent using an IUCV SEND with the followingparameters:Keyword ValueTRGCLS 0DATA BUFFERBUFLEN 20TYPE 2WAYANSLEN 8PRTY NOBUFFER Points to a buffer in the following format:Offset Name Length Comments0 8 Constant ’IUCVAPI ’. The trailing blank is required.8 2 Halfword integer. Maximum number of sockets thatcan be established on this IUCV connection.minimum: 50, Default: 50.10 apitype 2 X'0002'-. Provided for compatibility with priorimplementations of <strong>TCP</strong>/<strong>IP</strong>. Use X'0003' instead.X'0003'- Any number of socket requests may beoutstanding. on this IUCV connection at the sametimeFor more information, see “Overlapping SocketRequests” on page 174.12 subtaskname 8 Eight printable characters. The combination of youruser ID and subtaskname uniquely identifies the<strong>TCP</strong>/<strong>IP</strong> client using this path. This value is displayedby the NETSTAT CLIENT command.ANSBUFPoints to a buffer to contain the reply from <strong>TCP</strong>/<strong>IP</strong>:Offset Name Length Comments0 4 Reserved4 maxsock 4 The maximum socket number that your applicationcan use on this path. The minimum socket number isalways 0. Your application chooses a socket numberfor the accept, socket, and takesocket calls.172 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Note: A single virtual machine can establish more than one IUCV path to <strong>TCP</strong>/<strong>IP</strong>,but a different subtaskname must be specified on each IUCV path. If the samesubtaskname is specified for more than one IUCV path, <strong>TCP</strong>/<strong>IP</strong> severs theexisting path with that subtaskname.Severing the IUCV ConnectionAn IUCV connection to <strong>TCP</strong>/<strong>IP</strong> can be severed (deleted) by your application or by<strong>TCP</strong>/<strong>IP</strong> at any time.Sever by the ApplicationYour application can sever a socket API IUCV path at any time by calling IUCVSEVER with USERDTA specified as 16 bytes of binary zeros. <strong>TCP</strong>/<strong>IP</strong> cleans up allsockets associated with the IUCV path.Clean-Up of Stream SocketsThe <strong>TCP</strong> connection corresponding to each stream socket associated with the IUCVpath is reset. In the case of a listening socket, all connections in the process ofopening, or already open and in the accept queue, are reset.If your program closed a stream socket earlier, the corresponding <strong>TCP</strong> connectionmight still be in the process of closing. Such connections, which are no longerassociated with any socket, are not reset when your program severs the IUCVpath.Sever by <strong>TCP</strong>/<strong>IP</strong><strong>TCP</strong>/<strong>IP</strong> severs a socket API IUCV path only in case of shutdown or an unexpectederror. The 16-byte <strong>IP</strong>USER field in the SEVER external interrupt indicates thereason for the sever. The reason is coded in EBCDIC. The following are possiblereason codes and explanations:Reason CodeIUCVCHECKRCSHUTTINGDOWNBAD PATH IDNULL SAVED NAMEBAD INIT MSG LENREQUIREDCONSTANTBAD API TYPERESTRICTEDExplanationIUCV SocketsIUCV error detected. This code is used only beforeor during processing of the initialization message.<strong>TCP</strong>/<strong>IP</strong> service is being shut down. This code isused only in response to the Pending Connectioninterrupt.An attempt was made to exceed the maximumnumber of IUCV connections support by the target<strong>TCP</strong><strong>IP</strong> virtual machine.A software error occurred in <strong>TCP</strong>/<strong>IP</strong>. This code isused only before or during processing of theinitialization message.Your program sent an initialization message thatwas not of the expected length.The first 8 bytes of your initialization messagewere not "IUCVAPI ".The apitype field in your initialization messagecontained an incorrect value.Your virtual machine is not permitted to use<strong>TCP</strong>/<strong>IP</strong>.Chapter 5. Inter-User Communication Vehicle Sockets 173


IUCV SocketsNO MORE CCBSNO CCB!!!!Your IUCV path cannot be accepted because thereare no more client control blocks available in the<strong>TCP</strong><strong>IP</strong> virtual machine.A software error occurred in <strong>TCP</strong>/<strong>IP</strong>. Contact yoursystem support personnel or the <strong>IBM</strong> SupportCenter.Issuing Socket CallsThe following section describes how to issue an IUCV socket call.All socket calls are invoked by issuing an IUCV SEND with the followingparameters:KeywordTRGCLSDATABUFLISTBUFFERBUFLENPRMMSGTYPEANSLISTANSBUFANSLENPRTYSYNCValueThe high-order halfword specifies the socket call. For most calls,the low-order halfword specifies the socket descriptor.BUFFER or PRMMSG, depending on callIf DATA=BUFFER, then either YES or NO as desired. IfDATA=PRMMSG, not applicable.If DATA=BUFFER, points to the buffer (or buffer list) in the formatrequired by the call. If DATA=PRMMSG, not applicable.If DATA=BUFFER, length of buffer. If DATA=PRMMSG, notapplicable.If DATA=PRMMSG, data as required by the call. DATA=PRMMSGis not allowed when ANSLIST=YES. If DATA=BUFFER, notapplicable.2WAYEither YES or NO as desired. DATA=PRMMSG is not allowedwhen ANSLIST=YES.Points to a buffer to contain the reply from <strong>TCP</strong>/<strong>IP</strong>.Length of the reply bufferNOYES or NO as desired. Applications that need to serve multipleclients at the same time should specify SYNC=NO. SYNC=YES willblock the entire virtual machine from execution until the functionis complete.Overlapping Socket RequestsYour program may have more than one socket call outstanding on the same IUCVpath. There are some restrictions on the types of calls that are queuedsimultaneously for the same socket descriptor.The following list describes the restrictions for each type of socket call:v Multiple read-type calls (READ, READV, RECV, RECVFROM, REC<strong>VM</strong>SG) andmultiple write-type calls (WRITE, WRITEV, SEND, SENDTO, SENDMSG), forthe same socket, can be queued simultaneously. The read-type calls are satisfiedin order, independently of the write-type calls. Similarly, the write-type calls aresatisfied in order, independently of the read-type calls.174 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


vvIUCV SocketsMultiple ACCEPT calls, for the same listening stream socket, can be queuedsimultaneously. They are satisfied in order.Multiple SELECT calls, referring to any combination of sockets, can be queuedsimultaneously on an IUCV path. <strong>TCP</strong>/<strong>IP</strong> checks all queued SELECT calls whenan event occurs and responds to any that are satisfied.vNote: This applies only to programs that specified apitype=3 in the initializationmessage.Calls other than the read-type, write-type, ACCEPT, and SELECT calls, cannot bequeued simultaneously for the same socket. For example, your program mustwait for <strong>TCP</strong>/<strong>IP</strong>’s response to a write-type call before issuing a CLOSE call forthe same socket.<strong>TCP</strong>/<strong>IP</strong> Response to an IUCV Request<strong>TCP</strong>/<strong>IP</strong>’s response to your socket call is signaled by the Message Completeexternal interrupt. When the Message Complete external interrupt is received, ifthe <strong>IP</strong>AUDIT field shows no error, your program’s reply buffer has been filled. The<strong>IP</strong>BFLN2F field indicates how many bytes of the reply buffer were not used.If the <strong>IP</strong>ADRJCT bit of the <strong>IP</strong>AUDIT field is set, then <strong>TCP</strong>/<strong>IP</strong> was unable to useIUCV REPLY to respond, and instead used IUCV REJECT. Your program issues thespecial LASTERRNO function (see “LASTERRNO” on page 200) to retrieve thereturn code and errno for the rejected call. <strong>TCP</strong>/<strong>IP</strong>’s use of IUCV REJECT does notnecessarily mean the socket call failed.The following errno values (shown in decimal) are seen only by a program usingthe IUCV socket interface.Errno Value Description1000 An unrecognized socket call constant was found in the high-orderhalfword of the Target Message Class.1001 A request or reply length field is incorrect1002 The socket number assigned by your program for ACCEPT,SOCKET, or TAKESOCKET is out of range.1003 The socket number assigned by your program for ACCEPT,SOCKET, or TAKESOCKET is already in use.1008 This request conflicts with a request already queued on the samesocket (see “Overlapping Socket Requests” on page 174).1009 The request was canceled by the CANCEL call (see “CANCEL” onpage 178).1010 Returned by the Offload function when a beginthread failureoccurs.Cancelling a Socket RequestYour socket program can use the CANCEL call to cancel a previously issued socketcall. Read-type calls, write-type calls, ACCEPT calls, and SELECT calls can becanceled using this function. See “CANCEL” on page 178 for more informationabout using the CANCEL call.IUCV PURGE can also be used to cancel a call, but it does not stop <strong>TCP</strong>/<strong>IP</strong>processing the same way as the CANCEL call.Chapter 5. Inter-User Communication Vehicle Sockets 175


IUCV SocketsIUCV Socket Call SyntaxEach IUCV SEND operation that completes with condition code zero is assigned aunique message identification number. This number is placed in the IUCVparameter list. To use the CANCEL or IUCV PURGE functions, your program mustkeep track of the message ID numbers assigned to each socket request.Each of the IUCV Socket calls described includes the C language syntax for thecall. IUCV SEND parameters and buffer contents are described using variablenames from the C syntax. Call types are in capital letters. For example, the acceptcall is ACCEPT.The parameter lists for some C language socket calls include a pointer to a datastructure defined by a C structure. When using the IUCV socket interface, thecontents of the data structure are passed in the send buffer, the reply buffer, orboth. Table 20 shows the C structures used, and the corresponding assemblerlanguage syntax.Table 20. C Structures in Assembler Language FormatC StructureAssembler Language Equivalentstruct sockaddr_in {short sin_family;ushort sin_port;struct in_addr sin_addr;char sin_zero[8];};struct timeval {long tv_sec;long tv_usec;};struct linger {int l_onoff;int l_linger;};struct ifreq {#define IFNAMSIZ 16char ifr_name[IFNAMSIZ];union {struct sockaddr ifru_addr;struct sockaddr ifru_dstaddr;struct sockaddr ifru_broadaddr;short ifru_flags;int ifru_metric;caddr_t ifru_data;} ifr_ifru;};FAMILY DS HPORT DS HADDR DS FZERO DC XL8’00’TVSEC DS FTVUSEC DS FONOFF DS FLINGER DS FNAME DS CL16ADDR.FAMILY DS HADDR.PORT DS HADDR.ADDR DS FADDR.ZERO DC XL8’00’ORG ADDR.FAMILYDST.FAMILY DS HDST.PORT DS HDST.ADDR DS FDST.ZERO DC XL8’00’ORG ADDR.FAMILYBRD.FAMILY DS HBRD.PORT DS HBRD.ADDR DS FBRD.ZERO DC XL8’00’ORG ADDR.FAMILYFLAGS DS HORG ADDR.FAMILYMETRIC DS F176 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


IUCV SocketsTable 20. C Structures in Assembler Language Format (continued)C StructureAssembler Language Equivalentstruct ifconf {int ifc_len;union {caddr_t ifcu_buf;struct ifreq *ifcu_req;} ifc_ifcu;};struct clientid {int domain;char name[8];char subtaskname[8];char reserved[20];};IFCLEN DS FIGNORED DS FDOMAIN DS FNAME DS CL8SUBTASK DS CL8RESERVED DC XL20’00’IUCV Socket CallsThis section provides the C language syntax, parameters, and other appropriateinformation for each IUCV socket call supported by <strong>TCP</strong>/<strong>IP</strong>. For information aboutC socket calls, see “Chapter 2. C Sockets Application Program Interface” on page 5.ACCEPTThe ACCEPT call is issued when the server receives a connection request from aclient. ACCEPT points to a socket that was created with a socket call and markedby a LISTEN call. ACCEPT can also be used as a blocking call. Concurrent serverprograms use the ACCEPT call to pass connection requests to child servers.When issued, the ACCEPT call:1. Accepts the first connection on a queue of pending connections2. Creates a new socket with the same properties as the socket used in the calland returns the address of the client for use by subsequent server calls. Thenew socket cannot be used to accept new connections, but can be used by thecalling program for its own connection. The original socket remains available tothe calling program for more connection requests.3. Returns the new socket descriptor to the calling program.ns = accept(s, addr, addrlen)int ns, s;struct sockaddr_in *addr;int *addrlen;Keyword ValueTRGCLS High-order halfword = 1Low-order halfword = sDATA PRMMSGPRMMSG High-order fullword = 0Low-order fullword = socket number for the new socket, chosen byyour program, in the range 0 through maxsock. See “Initializing theIUCV Connection” on page 171.ANSLEN 24Chapter 5. Inter-User Communication Vehicle Sockets 177


ACCEPTANSBUFPoints to a buffer to contain the reply from <strong>TCP</strong>/<strong>IP</strong>:Offset Name Length Comments0 ns 4 The new socket number assigned to this connection.A value of −1 indicates that the function could not becompleted and that errno contains a reason code.4 errno 4 When ns is −1, this field contains a reason code.Note: The rest of the reply buffer is filled only if thecall was successful.8 *addr 16 The remote address and port of the new socket. SeeTable 20 on page 176 for format.BINDIn a typical server program, the BIND call follows a SOCKET call and completesthe new socket creation process.The BIND call can either specify the port or let the system choose the port. Alistener program should always bind to the same well-known port so that clientsknow what socket address to use when issuing a CONNECT call.rc = bind(s, name, namelen)int rc, s;struct sockaddr_in *name;int namelen;Keyword ValueTRGCLS High-order halfword = 2Low-order halfword = sDATA BUFFERBUFLEN 16BUFFER Points to a buffer in the following format:Offset Name Length Comments0 *name 16 The local address and port to which the socket is tobe bound. See Table 20 on page 176 for format.ANSLEN 8ANSBUF Points to a buffer to contain the reply from <strong>TCP</strong>/<strong>IP</strong>:Offset Name Length Comments0 rc 4 The return code from the BIND call. A return code of0 indicates that the call was successful. A return codeof −1 indicates that the function could not becompleted and that errno contains a reason code.4 errno 4 When the return code is −1, this field contains areason code.CANCELThe CANCEL call is used to cancel a previously issued socket call. <strong>TCP</strong>/<strong>IP</strong>responds to the canceled call with a return code of −1 and an errno value of 1009.178 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


CANCELKeyword ValueTRGCLS High-order halfword = 42Low-order halfword = Low-order halfword of TRGCLS from call tobe canceled.DATA PRMMSGPRMMSG High-order fullword = High-order halfword of TRGCLS from callto be canceled.Low-order fullword = IUCV message ID of call to be canceled.ANSLEN 8ANSBUF Points to a buffer to contain the reply from <strong>TCP</strong>/<strong>IP</strong>:Offset Name Length Comments0 rc 4 The return code from the CANCEL call. A return codeof 0 indicates that the call was successful. A returncode of −1 indicates that the function could not becompleted and that errno contains a reason code.4 errno 4 When the return code is −1, this field contains areason code. Possible errno values are:3 Specifies that the call cannot befound. <strong>TCP</strong>/<strong>IP</strong> might have alreadyresponded to it.22 Specifies that the call is not a typethat may be canceled.CLOSEThe CLOSE call shuts down the socket and frees the resources that are allocated tothe socket.rc = close(s)int rc, s;Keyword ValueTRGCLS High-order halfword = 3Low-order halfword = sDATA PRMMSGPRMMSG Binary zerosANSLEN 8ANSBUF Points to a buffer to contain the reply from <strong>TCP</strong>/<strong>IP</strong>:Offset Name Length Comments0 rc 4 The return code from the CLOSE call. A return codeof 0 indicates that the call was successful. A returncode of −1 indicates that the function could not becompleted and that errno contains a reason code.4 errno 4 When the return code is −1, this field contains areason code.Chapter 5. Inter-User Communication Vehicle Sockets 179


CONNECTCONNECTThe CONNECT call is used by a client to establish a connection between a localsocket and a remote socket.For stream sockets, the CONNECT call:v Completes the binding process for a stream socket if a BIND call has not beenpreviously issued.v Attempts a connection to a remote socket. This connection must be completedbefore data can be transferred.For datagram sockets, a CONNECT call is not essential, but you can use it to sendmessages without including the destination.rc = connect(s, name, namelen)int rc, s;struct sockaddr_in *name;int namelen;Keyword ValueTRGCLS High-order halfword = 4Low-order halfword = sDATA BUFFERBUFLEN 16BUFFER Points to a buffer in the following format:Offset Name Length Comments0 *name 16 The remote address and port to which the socket is tobe connected. See Table 20 on page 176 for format.ANSLEN 8ANSBUFThe pointer to the buffer that is filled with a reply in the followingformat:Offset Name Length Comments0 rc 4 The return code from the CONNECT call. A returncode of 0 indicates that the call was successful. Areturn code of −1 indicates that the function could notbe completed and that errno contains a reason code.4 errno 4 When the return code is -1, this field contains areason code.FCNTLThe blocking mode for a socket can be queried or set using the FNDELAY flagdescribed in the FCNTL call.See “IOCTL” on page 186 for another way to control blocking for a socket.retval = fcntl(s, cmd, arg)int retval;int s, cmd, arg;180 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


FCNTLKeyword ValueTRGCLS High-order halfword = 5Low-order halfword = sDATA PRMMSGPRMMSG High-order fullword:F_GETFL (X ’00000003’)F_SETFL (X ’00000004’)The low-order fullword is used only for the F_SETFL command:ZeroFNDELAY(X ’00000000’) Socket will block(X ’00000004’) Socket is non-blockingANSLEN 8ANSBUF Points to a buffer that is filled with a reply in the format describedas follows:Offset Name Length Comments0 retval 4 For F_SETFL, the return code. A value of zeroindicates FNDELAY flag was set. For F_GETFL, thevalue of the FNDELAY flag. Zero means the socketwill block. A value of FNDELAY (4) means the socketis non-blocking. A return code of −1 indicates that thefunction could not be completed and that errnocontains a reason code.4 errno 4 When the return code is -1, this field contains areason code.GETCLIENTIDThe GETCLIENTID call returns the identifier by which the calling application isknown to the <strong>TCP</strong><strong>IP</strong> address space. The client ID structure that is returned is usedin the GIVESOCKET and TAKESOCKET calls.rc = getclientid(domain, clientid)int rc, domain;struct clientid *clientid;Keyword ValueTRGCLS High-order halfword = 30Low-order halfword = 0DATA PRMMSGPRMMSG Binary zerosANSLEN 48ANSBUF Points to the buffer that is filled with a reply in the followingformat:Chapter 5. Inter-User Communication Vehicle Sockets 181


GETCLIENTIDOffset Name Length Comments0 rc 4 The return code from the GETCLIENTID call. Areturn code of 0 indicates that the call was successful.A return code of −1 indicates that the function couldnot be completed and that errno contains a reasoncode.4 errno 4 When the return code is -1, this field contains areason code.Note: The rest of the reply buffer is filled only if thecall was successful.8 *clientid 40 See Table 20 on page 176 for format.Note: domain is not passed to <strong>TCP</strong>/<strong>IP</strong>. It is implicitly AF_INET.GETHOSTIDThe GETHOSTID call gets the unique 32-bit identifier for the current host. Thisvalue is the default home internet address.hostid = gethostidunsigned long hostid;Keyword ValueTRGCLS High-order halfword = 7Low-order halfword = 0DATA PRMMSGPRMMSG Binary zerosANSLEN 8ANSBUF Points to the buffer that is filled with a reply in the followingformat:Offset Name Length Comments0 hostid 4 The default home internet address.4 4 Your program should ignore this field.GETHOSTNAMEThe GETHOSTNAME call returns the name of the host processor on which theprogram is running. Up to namelen characters are copied into the name field.rc = gethostname(name, namelen)int rc;char *name;int namelen;Keyword ValueTRGCLS High-order halfword = 8Low-order halfword = 0DATA PRMMSGPRMMSG Binary zeros182 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


GETHOSTNAMEANSLEN namelen +8ANSBUF Points to the buffer that is filled with a reply in the followingformat:Offset Name Length Comments0 rc 4 The return code from the GETHOSTNAME call. Areturn code of 0 indicates that the call was successful.A return code of −1 indicates that the function couldnot be completed and that errno contains a reasoncode.4 errno 4 When the return code is -1, this field contains areason code.Note: The rest of the reply buffer is filled only if thecall was successful.8 *name namelen The host name, not null-terminated.GETPEERNAMEThe GETPEERNAME call returns the name of the remote socket to which the localsocket is connected.rc = getpeername(s, name, namelen)int rc, s;struct sockaddr_in *name;int *namelen;Keyword ValueTRGCLS High-order halfword = 9Low-order halfword = sDATA PRMMSGPRMMSG Binary zerosANSLEN 24ANSBUF Points to the buffer that is filled with a reply in the followingformat:Offset Name Length Comments0 rc 4 The return code from the GETPEERNAME call. Areturn code of 0 indicates that the call was successful.A return code of −1 indicates that the function couldnot be completed and that errno contains a reasoncode.4 errno 4 When the return code is -1, this field contains areason code.Note: The rest of the reply buffer is filled only if thecall was successful.8 *name 16 The remote address and port to which the socket isconnected. See Table 20 on page 176 for format.GETSOCKNAMEThe GETSOCKNAME call stores the name of the socket into the structure pointedto by the name parameter and returns the address to the socket that has beenChapter 5. Inter-User Communication Vehicle Sockets 183


GETSOCKNAMEbound. If the socket is not bound to an address, the call returns with the familyfield completed and the rest of the structure set to zeros.rc = getsockname(s, name, namelen)int rc, s;struct sockaddr_in *name;int *namelen;Keyword ValueTRGCLS High-order halfword = 10Low-order halfword = sDATA PRMMSGPRMMSG Binary zerosANSLEN 24ANSBUF Points to the buffer that is filled with a reply in the followingformat:Offset Name Length Comments0 rc 4 The return code from the GETSOCKNAME call. Areturn code of 0 indicates that the call was successful.A return code of −1 indicates that the function couldnot be completed and that errno contains a reasoncode.4 errno 4 When the return code is -1, this field contains areason code.Note: The rest of the reply buffer is filled only if thecall was successful.8 *name 16 The local address and port to which the socket isbound. See Table 20 on page 176 for format.GETSOCKOPTThe GETSOCKOPT call returns the current setting of an option for a specificsocket. Some of these options are under program control and can be changed usingthe SETSOCKOPT call.rc = getsockopt(s, level, optname, optval, &optlen)int rc, s, level, optname, optlen;char *optval;Keyword ValueTRGCLS High-order halfword = 11Low-order halfword = sDATA PRMMSGPRMMSG High-order fullword = level. Possible values are:Value C Symbol CommentsX'FFFF' SOL_SOCKET Socket optionX'0006' <strong>IP</strong>PROTO_<strong>TCP</strong> <strong>TCP</strong> protocol option184 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Low-order fullword = optname. Possible values are:Value Option Name Returned ValueX'0001' SO_DEBUG Returns current setting.X'0004' SO_REUSEADDR Returns current setting.X'0008' SO_KEEPALIVE Returns current setting.X'0010' SO_DONTROUTE Returns current setting.X'0020' SO_BROADCAST Returns current setting.X'0080' SO_LINGER Returns current setting in a C language structlinger. See Table 20 on page 176 for the assemblerlanguage equivalent.X'0100' SO_OOBINLINE Returns current setting.X'1001' SO_SNDBUF Returns the size of the <strong>TCP</strong>/<strong>IP</strong> send buffer.X'1007' SO_ERROR Returns any pending error code and clears anyerror status conditions.X'1008' SO_TYPE Socket type is returned:ValueType1 Stream2 Datagram3 RawGETSOCKOPTX'0001' <strong>TCP</strong>_NODELAY Returns current setting.Note: This option applies only tolevel=<strong>IP</strong>PROTO_<strong>TCP</strong>ANSLENANSBUF16 for option SO_LINGER, 12 for all other optionsPoints to a buffer to contain the reply from <strong>TCP</strong>/<strong>IP</strong>:Offset Name Length Comments0 rc 4 The return code from the GETSOCKOPT call. Areturn code of 0 indicates that the call was successful.A return code of −1 indicates that the function couldnot be completed and that errno contains a reasoncode.4 errno 4 When the return code is −1, this field contains areason code.Note: The rest of the reply buffer is filled only if thecall was successful.8 *optval 4 or 8 The value of the requested option. If the optionSO_LINGER was requested, 8 bytes are returned. Forall other options, 4 bytes are returned.GIVESOCKETThe GIVESOCKET call makes the socket available for a TAKESOCKET call issuedby another program. The GIVESOCKET call can specify any connected streamsocket. Typically, the GIVESOCKET call is issued by a concurrent server programthat creates sockets to be passed to a child server.The GIVESOCKET sequence is:Chapter 5. Inter-User Communication Vehicle Sockets 185


GIVESOCKETvvvvvTo pass a socket, the concurrent server first calls GIVESOCKET. If the optionalparameters, name of the child server’s virtual machine and subtask ID arespecified in the GIVESOCKET call, only a child with a matching virtual machineand subtask ID can take the socket.The concurrent server then starts the child server and passes it the socketdescriptor and concurrent server’s ID that were obtained from earlier SOCKETand GETCLIENTID calls.The child server calls TAKESOCKET, with the concurrent server’s ID and socketdescriptor.The concurrent server issues the select call to test the socket for the exceptioncondition, TAKESOCKET completion.When the TAKESOCKET has successfully completed, the concurrent serverissues the CLOSE call to free the socket.rc = givesocket(s, clientid)int rc, s;struct clientid *clientid;Keyword ValueTRGCLS High-order halfword = 31Low-order halfword = sDATA BUFFERBUFLEN 40BUFFER Points to the message in the following format:Offset Name Length Comments0 *clientid 40 See Table 20 on page 176 for format.ANSLEN 8ANSBUFThe pointer to the buffer that is filled with a reply in the followingformat:Offset Name Length Comments0 rc 4 The return code from the GIVESOCKET call. A returncode of 0 indicates that the call was successful. Areturn code of −1 indicates that the function could notbe completed and that errno contains a reason code.4 errno 4 When the return code is -1, this field contains areason code.IOCTLThe IOCTL call is used to control certain operating characteristics for a socket.Before you issue an IOCTL call, you must load a value representing thecharacteristic that you want to control into the cmd field.rc = ioctl(s, cmd, arg)int rc, s;unsigned long cmd;char *arg;186 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


IOCTLKeyword ValueTRGCLS High-order halfword = 12Low-order halfword = sDATA BUFFERBUFLEN Request arg length + 4BUFFER The pointer to the message in the format described in thefollowing format:Offset Name Length Comments0 cmd 4 The type of request. See Table 21 for values.4 *arg See Table 21. The request data, if any.ANSLEN Reply arg length + 8ANSBUF The pointer to the buffer that is filled with a reply in the followingformat:Offset Name Length Comments0 rc 4 A return code of 0 indicates that the call wassuccessful. A return code of −1 indicates that thefunction could not be completed and that errnocontains a reason code.4 errno 4 When the return code is -1, this field contains areason code.Note: The rest of the reply buffer is filled only if thecall was successful.8 *arg See Table 21. The response data, if any.Table 21. Values for cmd Argument in ioctl CallC SymbolValueRequestargLengthReplyargLengthCommentsFIONBIO X'8004A77E' 4 0 Request arg data is a fullwordinteger.FIONREAD X'4004A77F' 0 4 Reply arg data is a fullwordinteger.SIOCADDRT X'8030A70A' 48 0 For <strong>IBM</strong> use only.SIOCATMARK X'4004A707' 0 4 Reply arg data is a fullwordinteger.SIOCDELRT X'8030A70B' 48 0 For <strong>IBM</strong> use only.SIOCGIFADDR X'C020A70D' 32 32 arg data is the C language structifreq. See Table 20 on page 176 forthe assembler languageequivalent.SIOCGIFBRDADDR X'C020A712' 32 32 arg data is the C language structifreq. See Table 20 on page 176 forthe assembler languageequivalent.Chapter 5. Inter-User Communication Vehicle Sockets 187


IOCTLTable 21. Values for cmd Argument in ioctl Call (continued)||C SymbolValueRequestargLengthReplyargLengthCommentsSIOCGIFCONF X'C008A714' 8 * Request arg data is the C-language struct ifconf. See Table 20on page 176 for the assemblerlanguage equivalent. Yourprogram sets ifc_len to the replylength. The other field is ignored.Response arg data is an array of Clanguage struct ifreq structures,one for each defined interface.Note: * = the maximum numberof interfaces multiplied by 32.SIOCGIFDSTADDR X'C020A70F' 32 32 arg data is the C language structifreq. See Table 20 on page 176 forthe assembler languageequivalent.SIOCGIFFLAGS X'C020A711' 32 32 arg data is the C language structifreq. See Table 20 on page 176 forthe assembler languageequivalent.SIOCGIFMETRIC X'C020A717' 32 32 For <strong>IBM</strong> use only.SIOCGIFNETMASK X'C020A715' 32 32 arg data is the C language structifreq. See Table 20 on page 176 forthe assembler languageequivalent.SIOCSIFDSTADDR X'8020A70E' 32 0 For <strong>IBM</strong> use only.SIOCSIFFLAGS X'8020A710' 32 0 For <strong>IBM</strong> use only.SIOCSIFMETRIC X'8020A718' 32 0 For <strong>IBM</strong> use only.SIOCG<strong>IBM</strong>OPT C048D900 72 * For <strong>IBM</strong> use only.SIOCS<strong>IBM</strong>OPT 8048D900 * 0 For <strong>IBM</strong> use only.LISTENThe LISTEN call:v Completes the bind, if BIND has not already been called for the socket.vCreates a connection-request queue of a specified length for incoming connectionrequests.The LISTEN call is typically used by a concurrent server to receive connectionrequests from clients. When a connection request is received, a new socket iscreated by a later ACCEPT call. The original socket continues to listen foradditional connection requests. The LISTEN call converts an active socket to apassive socket and configures it to accept connection requests from clientprograms. If a socket is passive it cannot initiate connection requests.rc = listen(s, backlog)int rc, s, backlog;Keyword ValueTRGCLS High-order halfword = 13188 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Low-order halfword = sDATA PRMMSGPRMMSG High-order fullword = 0Low-order fullword = backlogANSLEN 8ANSBUF Points to the buffer that is filled with a reply in the followingformat:LISTENOffset Name Length Comments0 rc 4 The return code from the LISTEN call. A return codeof 0 indicates that the call was successful. A returncode of −1 indicates that the function could not becompleted and that errno contains a reason code.4 errno 4 When the return code is -1, this field contains areason code.MAXDESCYour program specifies the maximum number of AF_INET sockets in theinitialization message. For more information about the initialization message, see“Initializing the IUCV Connection” on page 171.READ, READVFrom the point of view of <strong>TCP</strong>/<strong>IP</strong>, the READ and READV calls are identical. Fromthe point of view of the application, they differ only in that the buffer for READ iscontiguous in storage, while the buffer for READV might not be contiguous.Your program, utilizing the direct IUCV socket interface, can use theANSLIST=YES parameter on IUCV SEND to specify a noncontiguous READ buffer.You can choose to use ANSLIST=YES even if your READ buffer is contiguous, sothat the reply area for cc and errno need not adjoin the READ buffer in storage.This section does not distinguish between READ and READV. IUCV usage isdescribed in terms of variable names from the C language syntax of READ.cc = read(s, buf, len)int cc, s;char *buf;int len;Keyword ValueTRGCLS High-order halfword = 14Low-order halfword = sDATA PRMMSGPRMMSG Binary zerosANSLEN len +24ANSBUF Points to the buffer that is filled with a reply in the followingformat:Chapter 5. Inter-User Communication Vehicle Sockets 189


READ, READVOffset Name Length Comments0 cc 4 The number of bytes read. A value of zero means thepartner has closed the connection. A value of −1indicates that the function could not be completedand that errno contains a reason code.4 errno 4 When cc is -1, this field contains a reason code.Note: The rest of the reply buffer is filled only if thecall was successful.8 16 Your program should ignore this field.24 *buf len The received data.RECV, RECVFROM, REC<strong>VM</strong>SGFrom the point of view of <strong>TCP</strong>/<strong>IP</strong>, the RECV, RECVFROM, and REC<strong>VM</strong>SG callsare identical.From the point of view of the application, RECVFROM differs from RECV in thatRECVFROM additionally provides the source address of the message. Yourprogram, using the direct IUCV socket interface, must provide space to receive thesource address of the message, even if the source address is not required.From the point of view of the application, REC<strong>VM</strong>SG differs from RECVFROM inthat REC<strong>VM</strong>SG additionally allows the buffer to be in noncontiguous storage. Yourprogram, utilizing the direct IUCV socket interface, can use the ANSLIST=YESparameter on IUCV SEND to specify a noncontinuous read buffer. You can chooseto use ANSLIST=YES even if your read buffer is contiguous, so that the reply areafor cc and errno, and the space to receive the source address of the message, neednot adjoin the read buffer in storage.cc = recvfrom(s, buf, len, flags, from, fromlen)int cc, s;char *buf;int len, flags;struct sockaddr_in *from;int *fromlen;Keyword ValueTRGCLS High-order halfword = 16Low-order halfword = sDATA PRMMSGPRMMSG High-order fullword = 0.Low-order fullword = flags:MSG_OOBMSG_PEEK(X'00000001')(X'00000002')ANSLEN len +24ANSBUF Points to the buffer that is filled with a reply in the followingformat:190 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


RECV, RECVFROM, REC<strong>VM</strong>SGOffset Name Length Comments0 cc 4 The number of bytes read. A value of zero indicatesthat communication is closed. A value of −1 indicatesthat the function could not be completed and thaterrno contains a reason code.4 errno 4 When cc is -1, this field contains a reason code.Note: The rest of the reply buffer is filled only if thecall was successful.8 *from 16 The source address and port of the message. SeeTable 20 on page 176 for format.24 *buf len The received data.SELECT, SELECTEXFrom the point of view of the <strong>TCP</strong>/<strong>IP</strong>, the SELECT and SELECTEX calls areidentical. From the point of view of the application, they differ in that return fromSELECTEX can be triggered by the posting of an ECB as well as the selection of adescriptor or a time-out.Your program cannot initiate other activity on an IUCV path until <strong>TCP</strong>/<strong>IP</strong>responds to the SELECT call. However, your program can cancel a SELECT callbefore <strong>TCP</strong>/<strong>IP</strong> responds by issuing IUCV PURGE. A successful IUCV PURGE canbe followed immediately by an IUCV SEND initiating another socket call.Multiple SELECT calls, referring to any combination of sockets, can be queuedsimultaneously on an IUCV path.Note: IUCV PURGE cannot be used by a multiple-request program to cancel aSELECT call. See “Issuing Socket Calls” on page 174 for more informationabout multilple-request socket programs.nfound = select(nfds, readfds, writefds, exceptfds, timeout)int nfound, nfds;fd_set *readfds, *writefds, *exceptfds;struct timeval *timeout;Descriptor SetsA descriptor set is an array of fullwords. The following is the required array size ininteger arithmetic:number_of_fullwords = (nfds +31)/32number_of_bytes = number_of_fullwords * 4DESCR<strong>IP</strong>TOR_SET, FD_CLR, FD_ISSET CallsThe following describes how to perform the function of these C language calls,which set, clear, and test the bit in the specified descriptor set corresponding to thespecified descriptor number.You can compute the offset of the fullword containing the bit (integer arithmetic)as follows:offset = (descriptor_number /32)*4Compute a mask to locate the bit within the fullword by:Chapter 5. Inter-User Communication Vehicle Sockets 191


SELECT, SELECTEXbitmask = X'00000001'


SELECT, SELECTEXOffset Name Length Comments0 nfound 4 The total number of ready sockets (in all bit masks).A value of zero indicates an expired time limit. Avalue of −1 indicates that the function could not becompleted and that errno contains a reason code.4 errno 4 When nfound is -1, this field contains a reason code.8 8 Your program ignores this field.Note: The rest of the reply buffer is filled only if thecall was successful.16 *readfds fdsize If field at offset 8 in request data was zero, then yourprogram ignores this field.16 +fdsize*writefds fdsize If field at offset 12 in request data was zero, then yourprogram ignores this field.16 + *exceptfds fdsize If field at offset 16 in request data was zero, then your(2*fdsize)program ignores this field.SENDThe SEND call sends datagrams on a specified connected socket.The flags field allows you to:v Send out-of-band data, for example, interrupts, aborts, and data marked urgent.v Suppress use of local routing tables. This implies that the caller takes control ofrouting, writing network software.For datagram sockets, the entire datagram is sent if the datagram fits into thebuffer. Excess data is discarded.For stream sockets, data is processed as streams of information with no boundariesseparating data the data. For example, if a program is required to send 1000 bytes,each call to this function can send any number of bytes, up to the entire 1000bytes, with the number of bytes sent returned in errno Therefore, programs usingstream sockets should place this call in a loop, reissuing the call until all data hasbeen sent.cc = send(s, msg, len, flags)int cc, s;char *msg;int len, flags;Keyword ValueTRGCLS High-order halfword = 20Low-order halfword = sBUFLEN len +20DATA BUFFERBUFFER The pointer to the message in the following format:Offset Name Length Comments0 flags 4 MSG_OOB (X'00000001')MSG_DONTROUTE (X'00000004')4 16 Your program should set this field to binary zeros.Chapter 5. Inter-User Communication Vehicle Sockets 193


SENDOffset Name Length Comments20 *msg len The data to be sent.ANSLEN 8ANSBUFThe pointer to the buffer that is filled in with a reply in thefollowing format:Offset Name Length Comments0 cc 4 The number of bytes sent. A value of −1 indicates thatthe function could not be completed and that errnocontains a reason code.4 errno 4 When cc is -1, this field contains a reason code.SENDMSGFrom the point of view of <strong>TCP</strong>/<strong>IP</strong>, the SENDMSG call with a null msg->msg_nameparameter is identical to the SEND call. Similarly, the SENDMSG call with anon-null msg->msg_name parameter is identical to the SENDTO call.From the point of view of the application, SENDMSG differs from SEND andSENDTO in that SENDMSG additionally allows the write buffer to be innoncontiguous storage.Your program, using the direct IUCV socket interface can use the BUFLIST=YESparameter on IUCV SEND to specify a noncontiguous write buffer. You can chooseto use BUFLIST=YES even if your write buffer is contiguous, so that the fieldspreceding the write data in the request format need not adjoin the write data instorage.See “SEND” on page 193 and “SENDTO” for more information.SENDTOSENDTO is similar to SEND, except that it includes the destination addressparameter. You can use the destination address on the SENDTO call to senddatagrams on a UDP socket that is connected or not connected.Use the flags parameter to :v Send out-of-band data such as, interrupts, aborts, and data marked as urgent.v Suppress the local routing tables. This implies that the caller takes control ofrouting, which requires writing network software.For datagram sockets, the SENDTO call sends the entire datagram if the datagramfits into the buffer.For stream sockets, data is processed as streams of information with no boundariesseparating the data. For example, if a program is required to send 1000 bytes, eachSENDTO call can send any number of bytes, up to the entire 1000 bytes, with thenumber of bytes sent returned in errno. Therefore, programs using stream socketsshould place SENDTO in a loop that repeats the call until all data has been sent.194 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


SENDTOcc = sendto(s, msg, len, flags, to, tolen)int cc, s;char *msg;int len, flags;struct sockaddr_in *to;int tolen;Keyword ValueTRGCLS High-order halfword = 22Low-order halfword = sDATA BUFFERBUFLEN len + 20.BUFFER The pointer to the message in the following format:Offset Name Length Comments0 flags 4 MSG_OOB (X'00000001')MSG_DONTROUTE (X'00000004')4 *to 16 See Table 20 on page 176 for format.20 *msg len The data to be sent.ANSLEN 8ANSBUF The pointer to the buffer that is filled with a reply in the followingformat:Offset Name Length Comments0 cc 4 The number of bytes sent. A value of −1 indicates thatthe function could not be completed and that errnocontains a reason code.4 errno 4 When cc is -1, this field contains a reason code.SETSOCKOPTThe SETSOCKOPT call sets the options associated with a socket.rc = setsockopt(s, level, optname, optval, optlen)int rc, s, level, optname;char *optval;int optlen;Keyword ValueTRGCLS High-order halfword = 23Low-order halfword = sDATA BUFFERBUFLEN 16 for option SO_LINGER, 12 for all other optionsBUFFER Points to a buffer in the following format:Offset Name Length Comments0 level 4 X'FFFF' - SOL_SOCKET - Socket optionX'0006' - <strong>IP</strong>PROTO_<strong>TCP</strong> - <strong>TCP</strong> protocol optionChapter 5. Inter-User Communication Vehicle Sockets 195


SETSOCKOPTOffset Name Length Comments4 optname 4 Option to set. See Table 22 for values.8 *optval 4 or 8 The value of the specified option. If the optionSO_LINGER is specified, 8 bytes are needed. For allother options, 4 bytes are needed.Table 22. Option name values for SETSOCKOPTValue Option Name Option ValueX'0001' SO_DEBUG On (1) or Off (0). Option may be set, but has noeffect.X'0004' SO_REUSEADDR Yes (1) or No (0).X'0008' SO_KEEPALIVE Yes (1) or No (0).X'0010' SO_DONTROUTE Yes (1) or No (0). Option may be set, but has noeffect. Use MSG_DONTROUTE on write-typecalls instead.X'0020' SO_BROADCAST Yes (1) or No (0).X'0080' SO_LINGER Value is a C language struct linger. See Table 20 onpage 176 for the assembler language equivalent.X'0100' SO_OOBINLINE Yes (1) or No (0).Note: The following option applies only tolevel=<strong>IP</strong>PROTO_<strong>TCP</strong>X'0001' <strong>TCP</strong>_NODELAY Yes (1) or No (0).ANSLEN 8ANSBUF Points to a buffer to contain the reply from <strong>TCP</strong>/<strong>IP</strong>:Offset Name Length Comments0 rc 4 The return code from the SETSOCKOPT call. A returncode of 0 indicates that the call was successful. Areturn code of −1 indicates that the function could notbe completed and that errno contains a reason code.4 errno 4 When the return code is −1, this field contains areason code.SHUTDOWNThe normal way to terminate a network connection is to issue the CLOSE callwhich attempts to complete all outstanding data transmission requests prior tobreaking the connection. The SHUTDOWN call can be used to close one-waytraffic while completing data transfer in the other direction. The how parameterdetermines the direction of the traffic to shutdown.A client program can us the SHUTDOWN call to reuse a given socket with adifferent connection.rc = shutdown(s, how)int rc, s, how;Keyword ValueTRGCLS High-order halfword = 24196 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


SHUTDOWNLow-order halfword = sDATA PRMMSGPRMMSG High-order fullword = 0Low-order fullword = how:0 = receive1 = send2 = bothANSLEN 8ANSBUFPoints to the buffer that is filled with a reply in the followingformat:Offset Name Length Comments0 rc 4 The return code from the SHUTDOWN call. A returncode of 0 indicates that the call was successful. Areturn code of −1 indicates that the function could notbe completed and that errno contains a reason code.4 errno 4 When the return code is -1, this field contains areason code.SOCKETThe SOCKET call creates an endpoint for communication and returns a socketdescriptor representing the endpoint. Different types of sockets provide differentcommunication services.s = socket(domain, type, protocol)int s, domain, type, protocolKeyword ValueTRGCLS High-order halfword = 25Low-order halfword = 0DATA BUFFERBUFLEN 16BUFFER The pointer to the message in the following format:Offset Name Length Comments0 domain 4 The only valid value is AF_INET (X'00000002')4 type 4 Fullword integer:SOCK_STREAMX'00000001'SOCK_DGRAMX'00000002'SOCK_RAWX'00000003'8 protocol 4 Fullword integer:<strong>IP</strong>PROTO_ICMP X'00000001'<strong>IP</strong>PROTO_<strong>TCP</strong> X'00000006'<strong>IP</strong>PROTO_UDP X'00000011'<strong>IP</strong>PROTO_RAW X'000000FF'Chapter 5. Inter-User Communication Vehicle Sockets 197


SOCKETOffset Name Length Comments12 s 4 Socket number for the new socket, chosen by yourprogram, in the range 0 through maxsock. See“Initializing the IUCV Connection” on page 171.ANSLEN 8ANSBUF Points to the buffer that is filled with a reply in the followingformat:Offset Name Length Comments0 s 4 The socket number assigned to this communicationsend point. A value of −1 indicates that the functioncould not be completed and that errno contains areason code.4 errno 4 When s is -1, this field contains a reason code.TAKESOCKETThe TAKESOCKET call acquires a socket from another program and creates a newsocket. Typically, a child server issues this call using client ID and socket descriptordata which it obtained from the concurrent server. When TAKESOCKET is issued,a new socket descriptor is returned in errno. You should use this new socketdescriptor in later calls such as GETSOCKOPT, which require the s (socketdescriptor) parameter.Note: Both concurrent servers and iterative servers are used by this interface. Aniterative server handles one client at a time. A concurrent server receivesconnection requests from multiple clients and creates child servers thatprocess the client requests. When a child server is created, the concurrentserver gets a new socket, passes the new socket to the child server, anddissociates itself from the connection. The <strong>TCP</strong>/<strong>IP</strong> Listener program is anexample of a concurrent server.s = takesocket(clientid, hisdesc)int s;struct clientid *clientid;int hisdesc;Keyword ValueTRGCLS High-order halfword = 32Low-order halfword = 0DATA BUFFERBUFLEN 48BUFFER The pointer to the message in the following format:Offset Name Length Comments0 *clientid 40 See Table 20 on page 176 for format.40 hisdesc 444 s 4 Socket number for the new socket, chosen by yourprogram, in the range 0 through maxsock. See“Initializing the IUCV Connection” on page 171.198 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


TAKESOCKETANSLEN 8ANSBUF The pointer to the buffer that is filled with a reply in the followingformat:Offset Name Length Comments0 s 4 The socket number assigned to this communicationsend point. A value of −1 indicates that the functioncould not be completed and that errno contains areason code.4 errno 4 When s is -1, this field contains a reason code.WRITE, WRITEVFrom the point of view of <strong>TCP</strong>/<strong>IP</strong>, the WRITE and WRITEV calls are identical.From the point of view of the application, WRITEV differs from WRITE in thatWRITEV additionally allows the write buffer to be in noncontiguous storage.Your program, using the direct IUCV socket interface, can use the BUFLIST=YESparameter on IUCV SEND to specify a noncontiguous write buffer. You can chooseto use BUFLIST=YES even if your write buffer is contiguous, so that the 20-byteprefix need not adjoin the write buffer in storage.This section does not distinguish between WRITE and WRITEV. IUCV usage isdescribed in terms of variable names from the C language syntax of WRITE.cc = write(s, buf, len)int cc, s;char *buf;int len;Keyword ValueTRGCLS High-order halfword = 26Low-order halfword = sDATA BUFFERBUFLEN len +20BUFFER The pointer to the message in the following format:Offset Name Length Comments0 20 Your program sets this parameter to binary zeros.20 *buf len The data to be sent.ANSLEN 8ANSBUF Points to the buffer that is filled with a reply in the followingformat:Offset Name Length Comments0 cc 4 The number of bytes sent. A value of −1 indicates thatthe function could not be completed and that errnocontains a reason code.4 errno 4 When cc is -1, this field contains a reason code.Chapter 5. Inter-User Communication Vehicle Sockets 199


LASTERRNOLASTERRNOAs explained in “<strong>TCP</strong>/<strong>IP</strong> Response to an IUCV Request” on page 175, if <strong>TCP</strong>/<strong>IP</strong>uses IUCV REJECT to respond to a socket request, your program uses theLASTERRNO special request to retrieve the return code and errno.Keyword ValueTRGCLS High-order halfword = 29Low-order halfword = 0DATA PRMMSGPRMMSG Binary zerosANSLEN 8ANSBUFPoints to the buffer that is filled in with a reply in the followingformat:Offset Name Length Comments0 rc 4 The return code from the last rejected call. A returncode of 0 indicates that the call was successful. Areturn code of −1 indicates that the function could notbe completed and that errno contains a reason code.4 errno 4 When the return code is -1, this field contains areason code.200 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Chapter 6. Remote Procedure CallsThe RPC InterfaceThis chapter describes the high-level remote procedure calls (RPCs) implementedin <strong>TCP</strong>/<strong>IP</strong>, including the RPC programming interface to the C language, andcommunication between processes.The RPC protocol permits remote execution of subroutines across a <strong>TCP</strong>/<strong>IP</strong>network. RPC, together with the eXternal Data Representation (XDR) protocol,defines a standard for representing data that is independent of internal protocolsor formatting. RPCs can communicate between processes on the same or differenthosts.To use the RPC interface, you must be familiar with programming in the Clanguage, and you should have a working knowledge of networking concepts.The RPC interface enables programmers to write distributed applications usinghigh-level RPCs rather than lower-level calls based on sockets.When you use RPCs, the client communicates with a server. The client invokes aprocedure to send a call message to the server. When the message arrives, theserver calls a dispatch routine, and performs the requested service. The serversends back a reply message, after which the original procedure call returns to theclient program with a value derived from the reply message.For sample RPC client, server, and raw data stream programs, see “Sample RPCPrograms” on page 246. Figure 27 on page 202 and Figure 28 on page 203 providean overview of the high-level RPC client and server processes from initializationthrough cleanup.© Copyright <strong>IBM</strong> Corp. 1987, 2001 201


RPCs(Begin)│───────────── ┌──────────────────►││┌───────┴──────────┬────────────┐│ │ <strong>TCP</strong> or UDP get_myaddress UDP only│ │ pmap_rmtcall ││ pmap_getmap ││ ┌─tcp─┐ pmap_getport ││ clnt│ │_create ││ └─udp─┘ │Initialize │ │ ││ ││ ┌─none─┐_create ││ auth│ unix │_create ││ └─unix─┘_create_default ││ │ ││ ┌───┴───────┐ ││ │───────────── │ success error ││ │ └───┐ ││ │ clnt_call clnt_pcreateerror callrpc│ clnt_broadcast │ ││ │ │ ││ │ Process │ XDR routines └────────┐ XDR routinesCall │ │ │ ┌────┴────┐│ ├────────┐ │ │ ││ │ │ success error │ success error│ │ │ │ │ ││ │ │ │ │ │ │ │ │ clnt_perrno│ │ clnt_perror │ │ ││ │ clnt_geterr │ │ ││ │ │ │ │ ││ │ │ │ │ │───────────── │ └────────┴───────────────┤ └────┬────┘│ │ │Free │ │Resources │ clnt_freeres ││ │ ││ │ │───────────── └────────────────────────────────┤ │ │Final auth_destroy │Cleanup clnt_destroy │││└─────┬────┘(End)Figure 27. Remote Procedure Call (Client)202 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


RPCs───────────── <strong>TCP</strong> or UDP UDP only│┌──────►│ │ │┌─tcp─┐ │ svc│ │_create │ registerrpc ─────┐Initialize └─udp─┘ │ │ │xprt_register │ │ │svc_register └───────┤ │pmap_set │ ││ │ ││ │ │───────────── └──────────┬──────────┘ │││┌──────────────────►││Receive │ │ │Request │ ┌──────────┴──────────┐ ││ │ │ svc_run───────►││ svc_getreq │ ││ svc_getcaller │ ││ │ │───────────── │ │ svc_getargs ││ │ │ ││ └──────────┬──────────┘ ││ │ ││ ┌──────────┴──────────┐ ││ │Process │ XDR encode decode routines ││ │ │ ││ └──────────┬──────────┘ ││ │ ││ ┌────────┴────────┐ ││ │───────────── │ error success ││ │ │ │Reply │ ││ svcerr_xxx svc_sendreply ││ │ │ │───────────── │ └────────┬────────┘ ││ │ ││ │Transaction │ svc_freeargs │Cleanup and └───────────────────┤ │Final │Cleanup pmap_unset │xprt_unregister│svc_unregister│svc_destroy│││├──────────────────────┘(End)Figure 28. Remote Procedure Call (Server)PortmapperPortmapper** is the software that supplies client programs with the port numbersof server programs.You can communicate between different computer operating systems whenmessages are directed to port numbers rather than to targeted remote programs.Clients contact server programs by sending messages to the port numbers whereChapter 6. Remote Procedure Calls 203


RPCsreceiving processes receive the message. Because you make requests to the portnumber of a server rather than directly to a server program, client programs needa way to find the port number of the server programs they wish to call.Portmapper standardizes the way clients locate the port number of the serverprograms supported on a network.Portmapper resides on all hosts on well-known port 111.The port-to-program information maintained by Portmapper is called the portmap.Clients ask Portmapper about entries for servers on the network. Servers contactPortmapper to add or update entries to the portmap.Contacting PortmapperTo find the port of a remote program, the client sends an RPC to well-known port111 of the server’s host. If Portmapper has a portmap entry for the remoteprogram, Portmapper provides the port number in a return RPC. The client thenrequests the remote program by sending an RPC to the port number provided byPortmapper.Clients can save port numbers of recently called remote programs to avoid havingto contact Portmapper for each request to a server.To see all the servers currently registered with Portmapper, use the RPCINFOcommand in the following manner:RPCINFO -p host_nameFor more information about Portmapper, see <strong>TCP</strong>/<strong>IP</strong> User’s Guide.Target AssistancePortmapper offers a program to assist clients in contacting server programs. If theclient sends Portmapper an RPC with the target program number, version number,procedure number, and arguments, Portmapper searches the portmap for an entry,and passes the client’s message to the server. When the target server returns theinformation to Portmapper, the information is passed to the client, along with theport number of the remote program. The client can then contact the server directly.|||RPCGEN CommandRPCGEN is a tool that generates C code to implement an RPC protocol. The inputto RPCGEN is a language similar to C, known as RPC language. For RPCGEN towork correctly you must have access to the CC EXEC that is a part of the Ccompiler and have accessed the <strong>TCP</strong>MAINT.592 disk.RPCGEN infile is normally used when you want to generate all four of thefollowing output files. For example, if the infile is named proto.x, RPCGENgenerates:v A header file called PROTO.Hv XDR routines called PROTOX.Cv Server-side stubs called PROTOS.Cv Client-side stubs called PROTOC.CNote: A temporary file called PROTO.EXPANDED is created by the RPCGENcommand. During normal operation, this file is also subsequently erased bythe RPCGEN command.204 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


RPCsFor additional information about the RPCGEN command, see the SunMicrosystems publication, Network Programming.►►RPCGEN-c-h-K seconds-l-m-o outfile-s <strong>TCP</strong>UDP-o outfileinfile►◄enum clnt_stat StructureParameter Description-c Compiles into XDR routines.-Dname[=value]Define a symbol ″name″. Equivalent to the #define directive in thesource. If no ″value″ is given, ″name″ is defined as 1. This optionmay be called more than once.-h Compiles into C data definitions (a header file). The -T option canbe used in conjunction to produce a header file which supportsRPC dispatch tables.-K seconds If the server was started by inetd, specify the time in seconds afterwhich the server should exit if there is no further activity. Thisoption is useful for customization. If seconds is 0, the server exitsafter serving that given request. If seconds is -1, the server hangsaround for ever after being started by inetd. This option is validonly with the -I option.-l Compiles into client-side stubs.-m Compiles into server-side stubs without generating a main routine.This option is useful for call-back routines and for writing a mainroutine for initialization.-s <strong>TCP</strong>|UDP Compiles into server-side stubs using the given transport. The <strong>TCP</strong>option supports the <strong>TCP</strong> transport protocol. The UDP optionsupports the UDP transport protocol.-o outfile Specifies the name of the output file. If none is specified, standardoutput is used for -c, -h, -l, -m, and -s modes.infileSpecifies the name of the input file written in the RPC language.The options -c, -h, -l, -m, -s and -t are used exclusively to generate a particulartype of file, while the options -D, -I, -L and -T are global and can be used with theother options.The enumerated set clnt_stat structure is defined in the CLNT.H header file.RPCs frequently return the enumerated set clnt_stat information. The following isthe format and a description of the enumerated set clnt_stat structure:Chapter 6. Remote Procedure Calls 205


RPCsenum clnt_stat {RPC_SUCCESS=0, /* call succeeded *//** local errors*/RPC_CANTENCODEARGS=1, /* can’t encode arguments */RPC_CANTDECODERES=2, /* can’t decode results */RPC_CANTSEND=3, /* failure in sending call */RPC_CANTRECV=4, /* failure in receiving result */RPC_TIMEDOUT=5, /* call timed out *//** remote errors*/RPC_VERSMISMATCH=6, /* RPC versions not compatible */RPC_AUTHERROR=7, /* authentication error */RPC_PROGUNAVAIL=8, /* program not available */RPC_PROGVERSMISMATCH=9, /* program version mismatched */RPC_PROCUNAVAIL=10, /* procedure unavailable */RPC_CANTDECODEARGS=11, /* decode arguments error */RPC_SYSTEMERROR=12, /* generic “other problem” *//** callrpc errors*/RPC_UNKNOWNHOST=13, /* unknown host name *//** create errors*/RPC_PMAPFAILURE=14, /* the pmapper failed in its call */RPC_PROGNOTREGISTERED=15, /* remote program is not registered *//** unspecified error*/RPC_FAILED=16, /* call failed */RPC_UNKNOWNPROTO=17 /* unknown protocol */};Remote Procedure Call LibraryPortingRPC requires the RPCLIB TXTLIB and the COMMTXT TXTLIB for compiling andlinking. These TXTLIBs are normally named in a GLOBAL TXTLIB statement inthe PROFILE EXEC or in the <strong>TCP</strong>LOAD EXEC.This section contains information about porting RPC applications.Remapping C Identifiers with RPC.HTo conform to the <strong>VM</strong> requirement that C identifiers are 8 characters or less inlength, a header file called MANIFEST.H remaps the RPC long names to8-character derived names for internal processing. This file is implicitly includedby the RPC.H file and must be present to compile and link.Accessing System Return MessagesTo access system return values, you need only use the ERRNO.H include statementsupplied with the compiler. To access network return values, you must add thefollowing include statement:#include 206 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Printing System Return MessagesTo print only system errors, use perror(), a procedure available in the C compilerrun-time library. To print both system and network errors, use tcperror(), aprocedure included with <strong>TCP</strong>/<strong>IP</strong>.EnumerationsTo account for varying length enumerations, use the xdr_enum() and xdr_union()macros. xdr_enum() cannot be referenced by callrpc(), svc_freeargs(), svc_getargs(),or svc_sendreply(). An XDR routine for the specific enumeration must be created.The xdr_union() is not eligible for reference by these calls in any RPC environment.For more information, see “xdr_enum()” on page 233.RPC Global Variablesrpc_createerrThis section describes the two RPC global variables, prc_createerr and svc_fds.Description: A global variable that is set when any RPC client creation routine#include RPCsstructrpc_createerr rpc_createerr;svc_fdsfails. Use clnt_pcreateerror() to print the message.See Also: clntraw_create(), clnttcp_create(), clntudp_create().int svc_fds;Description: A global variable that specifies the read descriptor bit mask on theservice machine. This is of interest only if the service programmer decides to writean asynchronous event processing routine; otherwise svc_run() should be used.Writing asynchronous routines in the <strong>VM</strong> environment is not simple, because thereis no direct relationship between the descriptors used by the socket routines andthe Event Control Blocks commonly used by <strong>VM</strong> programs for coordinatingconcurrent activities.Attention: Do not modify this variable.See Also: svc_getreq().Remote Procedure and eXternal Data Representation CallsThis section provides the syntax, parameters, and other appropriate information foreach remote procedure and external data representation call supported by <strong>TCP</strong>/<strong>IP</strong>.auth_destroy()#include void auth_destroy(auth)AUTH *auth;ParameterDescriptionChapter 6. Remote Procedure Calls 207


auth_destroy()authPoints to authentication information.Description: The auth_destroy() call deletes the authentication information forauth. Once this procedure is called, auth is undefined.See Also: authnone_create(), authunix_create(), authunix_create_default().authnone_create()&numsign.include .AUTH *authnone_create()The authnone_create() call has no parameters.Description: The authnone_create() call creates and returns an RPCauthentication handle. The handle passes the NULL authentication on each call.See Also: auth_destroy(), authunix_create(), authunix_create_default().authunix_create()#include AUTH *authunix_create(host, uid, gid, len, aup_gids)char *host;int uid;int gid;int len;int *aup_gids;Parameterhostuidgidlenaup_gidsDescriptionSpecfies a pointer to the symbolic name of the host where thedesired server is located.Identifies the user’s user ID.Identifies the user’s group ID.Specifies the length of the information pointed to by aup_gids.Specifies a pointer to an array of groups to which the user belongs.Description: The authunix_create() call creates and returns an authenticationhandle that contains UNIX-based authentication information.See Also: auth_destroy(), authnone_create(), authunix_create_default().authunix_create_default()#include AUTH *authunix_create_default()The authunix_create_default() call has no parameters.208 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


callrpc()Description: The authunix_create_default() call calls authunix_create() withdefault parameters.See Also: auth_destroy(), authnone_create(), authunix_create().#include enum clnt_statcallrpc(host, prognum, versnum, procnum, inproc, in, outproc, out)char *host;u_long prognum;u_long versnum;u_long procnum;xdrproc_t inproc;char *in;xdrproc_t outproc;char *out;authunix_create_default()ParameterhostprognumversnumprocnuminprocinoutprocoutDescriptionSpecifies a pointer to the symbolic name of the host where thedesired server is located.Identifies the program number of the remote procedure.Identifies the version number of the remote procedure.Identifies the procedure number of the remote procedure.Specifies the XDR procedure used to encode the arguments of theremote procedure.Specifies a pointer to the arguments of the remote procedure.Specifies the XDR procedure used to decode the results of theremote procedure.Specifies a pointer to the results of the remote procedure.clnt_perrno() can be used to translate the return code intomessages.Description: The callrpc() call calls the remote procedure described by prognum,versnum, and procnum running on the host system. callrpc() encodes and decodesthe parameters for transfer.For more information on callrpc() cannot call the procedure xdr_enum;, see“xdr_enum()” on page 233. For more information on, callrpc() uses UDP as itstransport layer, see “clntudp_create()” on page 217.Return Values: RPC_SUCCESS indicates success; otherwise, an error has occurred.The results of the remote procedure call are returned to out.See Also: clnt_broadcast(), clnt_call(), clnt_perrno(), clntudp_create(),clnt_sperrno(), xdr_enum().clnt_broadcast()Chapter 6. Remote Procedure Calls 209


clnt_broadcast()#include enum clnt_statclnt_broadcast(prognum, versnum, procnum, inproc, in, outproc, out, eachresult)u_long prognum;u_long versnum;u_long procnum;xdrproc_t inproc;char *in;xdrproc_t outproc;char *out;resultproc_t eachresult;ParameterprognumversnumprocnuminprocinoutprocouteachresultDescriptionIdentifies the program number of the remote procedure.Identifies the version number of the remote procedure.Identifies the procedure number of the remote procedure.Specifies the XDR procedure used to encode the arguments of theremote procedure.Specifies a pointer to the arguments of the remote procedure.Specifies the XDR procedure used to decode the results of theremote procedure.Specifies a pointer to the results of the remote procedure.Specifies the procedure called after each response.Note: resultproc_t is a type definition:#include typedef bool_t (*resultproc_t) ();Description: The clnt_broadcast() call broadcasts the remote procedure describedby prognum, versnum, and procnum to all locally connected broadcast networks.Each time clnt_broadcast() receives a response it calls eachresult(). The format ofeachresult() is:#include bool_t eachresult(out, addr)char *out;struct sockaddr_in *addr;ParameteroutaddrDescriptionHas the same function as it does for clnt_broadcast(), except thatthe output of the remote procedure is decoded.Points to the address of the machine that sent the results.Return Values: If eachresult() returns 0, clnt_broadcast() waits for more replies;otherwise, eachresult() returns the appropriate status.Note: Broadcast sockets are limited in size to the maximum transfer unit of thedata link.See Also: callrpc(), clnt_call().210 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


clnt_call()clnt_call()#include enum clnt_statclnt_call(clnt, procnum, inproc, in, outproc, out, tout)CLIENT *clnt;u_long procnum;xdrproc_t inproc;char *in;xdrproc_t outproc;char *out;struct timeval tout;ParameterclntprocnuminprocinoutprocDescriptionPoints to a client handle that was previously obtained usingclntraw_create(), clnttcp_create(), or clntudp_create().Identifies the remote procedure number.Identifies the XDR procedure used to encode procnum’s arguments.Points to the remote procedure’s arguments.Specifies the XDR procedure used to decode the remoteprocedure’s results.outPoints to the remote procedure’s results.tout Specifies the time allowed for the server to respond in units of 0.1seconds.Description: The clnt_call() call calls the remote procedure (procnum) associatedwith the client handle (clnt).Return Values: RPC_SUCCESS indicates success; otherwise, an error has occurred.The results of the remote procedure call are returned to out.See Also: callrpc(), clnt_broadcast(), clnt_geterr(), clnt_perror(), clnt_sperror(),clntraw_create(), clnttcp_create(), clntudp_create().clnt_control()#include bool_tclnt_control(clnt, request, info)CLIENT *clnt;int request;void *info;ParameterclntrequestinfoDescriptionSpecifies the pointer to a client handle that was previouslyobtained using clntraw_create(), clnttcp_create(), orclntudp_create().Determines the operation (either CLSET_TIMEOUT,CLGET_TIMEOUT, CLGET_SERVER_ADDR,CLSET_RETRY_TIMEOUT, or CLGET_RETRY_TIMEOUT).Points to information used by the request.Chapter 6. Remote Procedure Calls 211


clnt_control()Description: The clnt_control() call performs one of the following controloperations.v Control operations that apply to both UDP and <strong>TCP</strong> transports:CLSET_TIMEOUTSets time-out (info points to the timeval structure).CLGET_TIMEOUTGets time-out (info points to the timeval structure).CLGET_SERVER_ADDRGets server’s address (info points to the sockaddr_in structure).v UDP only control operations:CLSET_RETRY_TIMEOUTSets retry time-out (information points to the timeval structure).CLGET_RETRY_TIMEOUTGets retry time-out (info points to the timeval structure). If youset the timeout using clnt_control(), the timeout parameter toclnt_call() will be ignored in all future calls.clnt_create()Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: clnt_create(), clnt_destroy(), clntraw_create(), clnttcp_create(),clntudp_create().#include CLIENT *clnt_create(host, prognum, versnum, protocol)char *host;u_long prognum;u_long versnum;char *protocol;ParameterhostprognumversnumprotocolDescriptionPoints to the name of the host at which the remote programresides.Specifies the remote program number.Specifies the version number of the remote program.Points to the protocol, which can be either tcp or udp.Description: The clnt_create() call creates a generic RPC client transport handlefor the remote program specified by (prognum, versnum). The client uses thespecified protocol as the transport layer. Default timeouts are set, but can bemodified using clnt_control().Return Values: NULL indicates failure.See Also: clnt_create(), clnt_destroy(), clnt_pcreateerror(), clnt_spcreateerror(),clnt_sperror(), clnttcp_create(), clntudp_create().212 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


clnt_destroy()clnt_destroy()#include voidclnt_destroy(clnt)CLIENT *clnt;ParameterclntDescriptionPoints to a client handle that was previously created usingclntudp_create(), clnttcp_create(), or clntraw_create().Description: The clnt_destroy() call deletes a client RPC transport handle. Thisprocedure involves the deallocation of private data resources, including clnt. Oncethis procedure is used, clnt is undefined. If the RPC library opened the associatedsocket, it will close it also. Otherwise, the socket remains open.See Also: clnt_control(), clnt_create(), clntraw_create(), clnttcp_create(),clntudp_create().clnt_freeres()#include bool_tclnt_freeres(clnt, outproc, out)CLIENT *clnt;xdrproc_t outproc;char *out;ParameterclntoutprocoutDescriptionPoints to a client handle that was previously obtained usingclntraw_create(), clnttcp_create(), or clntudp_create().Specifies the XDR procedure used to decode the remoteprocedure’s results.Points to the results of the remote procedure.clnt_geterr()Description: The clnt_freeres() call deallocates any resources that were assignedby the system to decode the results of an RPC.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: clntraw_create(), clnttcp_create(), clntudp_create().#include voidclnt_geterr(clnt, errp)CLIENT *clnt;struct rpc_err *errp;ParameterDescriptionChapter 6. Remote Procedure Calls 213


clnt_geterr()clnterrpPoints to a client handle that was previously obtained usingclntraw_create(), clnttcp_create(), or clntudp_create().Points to the address into which the error structure is copied.Description: The clnt_geterr() call copies the error structure from the clienthandle to the structure at address errp.See Also: clnt_call(), clnt_pcreateerror(), clnt_perrno(), clnt_perror(),clnt_spcreateerror(), clnt_sperrno(), clnt_sperror(), clntraw_create(), clnttcp_create(),clntudp_create().clnt_pcreateerror()#include voidclnt_pcreateerror(s)char *s;ParametersDescriptionSpecifies a NULL or NULL-terminated character string. If s isnon-NULL, clnt_pcreateerror() prints the string s followed by acolon, followed by a space, followed by the error message, andterminated with a newline character. If s is NULL or points to aNULL string, just the error message and the newline character areoutput.Description: The clnt_pcreateerror() call writes a message to the standard errordevice, indicating why a client handle cannot be created. This procedure is usedafter the clntraw_create(), clnttcp_create(), or clntudp_create() calls fail.See Also: clnt_create(), clnt_geterr(), clnt_perrno(), clnt_perror(),clnt_spcreateerror(), clnt_sperrno(), clnt_sperror(), clntraw_create(), clnttcp_create(),clntudp_create().clnt_perrno()#include voidclnt_perrno(stat)enum clnt_stat stat;ParameterstatDescriptionSpecifies the client status.Description: The clnt_perrno() call writes a message to the standard error devicecorresponding to the condition indicated by stat. This procedure should be usedafter callrpc() if there is an error.clnt_perror()See Also: callrpc(), clnt_geterr(), clnt_pcreateerror(), clnt_perror(),clnt_spcreateerror(), clnt_sperrno(), clnt_sperror().214 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


clnt_perror()#include voidclnt_perror(clnt, s)CLIENT *clnt;char *s;ParameterclntsDescriptionPoints to a client handle that was previously obtained usingclntudp_create(), clnttcp_create(), or clntraw_create().Points to a string that is to be printed in front of the message. Thestring is followed by a colon.Description: The clnt_perror() call writes a message to the standard error device,indicating why an RPC failed. This procedure should be used after clnt_call() ifthere is an error.See Also: clnt_call(), clnt_geterr(), clnt_pcreateerror(), clnt_perrno(),clnt_spcreateerror(), clnt_sperrno(), clnt_sperror(), clntraw_create(), clnttcp_create(),clntudp_create().clnt_spcreateerror()#include char *clnt_spcreateerror(s)char *s;ParametersDescriptionSpecifies a NULL or NULL-terminated character string. If s isnon-NULL, clnt_spcreateerror() prints the string s followed by acolon, followed by a space, followed by the error message, andterminated with a new-line character. If s is NULL or points to aNULL string, just the error message and the new-line character areprinted.Description: The clnt_spcreateerror() call returns the address of a messageindicating why a client handle cannot be created. This procedure is used after theclnt_create(), clntraw_create(), clnttcp_create(), or clntudp_create() calls fail.Return Values: Returns a pointer to a character string in a static data area. Thisdata area is overwritten with each subsequent call.See Also: clnt_create(), clnt_geterr(), clnt_perrno(), clnt_perror(), clnt_pcreateerror(),clnt_sperrno(), clnt_sperror(), clntraw_create(), clnttcp_create(), clntudp_create().clnt_sperrno()#include char *clnt_sperrno(stat)enum clnt_stat stat;ParameterstatDescriptionSpecifies the client status.Chapter 6. Remote Procedure Calls 215


clnt_sperrno()Description: The clnt_sperrno() call returns the address of a messagecorresponding to the condition indicated by stat. This procedure should be usedafter callrpc() if there is an error.Return Values: Returns a pointer to a character string ending with a newline.See Also: callrpc(), clnt_geterr(), clnt_pcreateerror(), clnt_spcreateerror(),clnt_sperror(), clnt_perrno(), clnt_perror().clnt_sperror()#include char *clnt_sperror(clnt, s)CLIENT *clnt;char *s;ParameterclntsDescriptionPoints to a client handle that was previously obtained usingclnt_create(), clntudp_create(), clnttcp_create(), or clntraw_create().Specifies a NULL or a NULL-terminated character string. If s isnon-NULL, clnt_sperror() prints the string s followed by a colon,followed by a space, followed by the error message, andterminated with a newline character. If s is NULL or points to aNULL string, just the error message and the newline character areoutput.Description: The clnt_sperror() call returns the address of a message indicatingwhy an RPC failed. This procedure should be used after clnt_call() if there is anerror.Return Values: Returns a pointer to a character string in a static data area. Thisdata area is overwritten with each subsequent call.See Also: clnt_call(), clnt_create(), clnt_geterr(), clnt_pcreateerror(), clnt_perrno(),clnt_perror(), clnt_spcreateerror(), clnt_sperrno(), clntraw_create(), clnttcp_create(),clntudp_create().clntraw_create()#include CLIENT *clntraw_create(prognum, versnum)u_long prognum;u_long versnum;ParameterprognumversnumDescriptionSpecifies the remote program number.Specifies the version number of the remote program.Description: The clntraw_create() call creates a dummy client for the remotedouble (prognum, versnum). Because messages are passed using a buffer within thevirtual machine of the local process, the server should also use the same virtual216 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


machine, which simulates RPC programs within one virtual machine. For moreinformation, see “svcraw_create()” on page 228.Return Values: NULL indicates failure.See Also: clnt_call(), clnt_destroy(), clnt_freeres(), clnt_geterr(), clnt_pcreateerror(),clnt_perror(), clnt_spcreateerror(), clnt_sperror(), clntudp_create(), clnttcp_create(),svcraw_create().clnttcp_create()#include CLIENT *clnttcp_create(addr, prognum, versnum, sockp, sendsz, recvsz)struct sockaddr_in *addr;u_long prognum;u_long versnum;int *sockp;u_int sendsz;u_int recvsz;clntraw_create()ParameteraddrprognumversnumsockpsendszrecvszDescriptionPoints to the internet address of the remote program. If the addrport number is zero (addr −> sin_port), addr is set to the port onwhich the remote program is receiving.Specifies the remote program number.Specifies the version number of the remote program.Points to the socket. If sockp is RPC_ANYSOCK, then this routineopens a new socket and sets sockp.Specifies the size of the send buffer. Specify 0 to choose the default.Specifies the size of the receive buffer. Specify 0 to choose thedefault.Description: The clnttcp_create() call creates an RPC client transport handle forthe remote program specified by (prognum, versnum). The client uses <strong>TCP</strong> as thetransport layer.Return Values: NULL indicates failure.See Also: clnt_call(), clnt_control(), clnt_create(), clnt_destroy(), clnt_freeres(),clnt_geterr(), clnt_pcreateerror(), clnt_perror(), clnt_spcreateerror(), clnt_sperror(),clntraw_create(), clntudp_create().clntudp_create()Chapter 6. Remote Procedure Calls 217


clntudp_create()#include CLIENT *clntudp_create(addr, prognum, versnum, wait, sockp)struct sockaddr_in *addr;u_long prognum;u_long versnum;struct timeval wait;int *sockp;ParameteraddrprognumversnumwaitsockpDescriptionPoints to the internet address of the remote program. If the addrport number is zero (addr−> sin_port), addr is set to the port onwhich the remote program is receiving. The remote portmapservice is used for this.Specifies the remote program number.Specifies the version number of the remote program.Indicates that UDP resends the call request at intervals of waittime, until either a response is received or the call times out. Thetime-out length is set using the clnt_call() procedure.Points to the socket. If sockp is RPC_ANYSOCK, this routine opensa new socket and sets sockp.Description: The clntudp_create() call creates a client transport handle for theremote program (prognum) with version (versnum). UDP is used as the transportlayer.Note: This procedure should not be used with procedures that use largearguments or return large results. While UDP packet size is configurable toa maximum of 32 kilobytes, the default UDP packet size is only eightkilobytes.Return Values: NULL indicates failure.See Also: call_rpc(), clnt_call(), clnt_control(), clnt_create(), clnt_destroy(),clnt_freeres(), clnt_geterr(), clnt_pcreateerror(), clnt_perror(), clnt_spcreateerror(),clnt_sperror(), clntraw_create(), clnttcp_create().get_myaddress()#include voidget_myaddress(addr)struct sockaddr_in *addr;ParameteraddrDescriptionPoints to the location where the local internet address is placed.Description: The get_myaddress() call puts the local host’s internet address intoaddr. The port number (addr—>sin_port) is set to htons (PMAPPORT), which is 111.See Also: getrpcport(), pmap_getmaps(), pmap_getport(), pmap_rmtcall(),pmap_set(), pmap_unset().218 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


getrpcport()getrpcport()#include u_shortgetrpcport(host, prognum, versnum, protocol)char *host;u_long prognum;u_long versnum;int protocol;ParameterhostprognumversnumprotocolDescriptionPoints to the name of the foreign host.Specifies the program number to be mapped.Specifies the version number of the program to be mapped.Specifies the transport protocol used by the program(<strong>IP</strong>PROTO_<strong>TCP</strong> or <strong>IP</strong>PROTO_UDP).Description: The getrpcport() call returns the port number associated with theremote program (prognum), the version (versnum), and the transport protocol(protocol).Return Values: The value 0 indicates that the mapping does not exist or that theremote portmap could not be contacted. If Portmapper cannot be contacted,rpc_createerr contains the RPC status.See Also: get_myaddress(), pmap_getmaps(), pmap_getport(), pmap_rmtcall(),pmap_set(), pmap_unset().pmap_getmaps()#include struct pmaplist *pmap_getmaps(addr)struct sockaddr_in *addr;ParameteraddrDescriptionPoints to the internet address of the foreign host.Description: The pmap_getmaps() call returns a list of current program-to-portmappings on the foreign host specified by addr.Return Values: Returns a pointer to a pmaplist structure or NULL.See Also: getrpcport(), pmap_getport(), pmap_rmtcall(), pmap_set(), pmap_unset().pmap_getport()Chapter 6. Remote Procedure Calls 219


pmap_getport()#include u_shortpmap_getport(addr, prognum, versnum, protocol)struct sockaddr_in *addr;u_long prognum;u_long versnum;int protocol;ParameteraddrprognumversnumprotocolDescriptionPoints to the internet address of the foreign host.Identifies the program number to be mapped.Identifies the version number of the program to be mapped.Specifies the transport protocol used by the program(<strong>IP</strong>PROTO_<strong>TCP</strong> or <strong>IP</strong>PROTO_UDP).Description: The pmap_getport() call returns the port number associated with theremote program (prognum), the version (versnum), and the transport protocol(protocol).Return Values: The value 0 indicates that the mapping does not exist or that theremote portmap could not be contacted. If Portmapper cannot be contacted,rpc_createerr contains the RPC status.See Also: getrpcport() pmap_getmaps(), pmap_rmtcall(), pmap_set(),pmap_unset().pmap_rmtcall()#include enum clnt_statpmap_rmtcall(addr, prognum, versnum, procnum, inproc, in, outproc, out, tout, portp)struct sockaddr_in *addr;u_long prognum;u_long versnum;u_long procnum;xdrproc_t inproc;char *in;xdrproc_t outproc;char *out;struct timeval tout;u_long *portp;ParameteraddrprognumversnumprocnuminprocinoutprocDescriptionPoints to the internet address of the foreign host.Identifies the remote program number.Identifies the version number of the remote program.Identifies the procedure to be called.Identifies the XDR procedure used to encode the arguments of theremote procedure.Points to the arguments of the remote procedure.Identifies the XDR procedure used to decode the results of theremote procedure.220 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


pmap_rmtcall()outtoutportpPoints to the results of the remote procedure.Identifies the time-out period for the remote request.If the call from the remote portmap service is successful, portpcontains the port number of the triple (prognum, versnum, procnum).pmap_set()Description: The pmap_rmtcall() call instructs Portmapper on the host at addr tomake an RPC call to a procedure on that host, on your behalf. This procedureshould be used only for ping type functions.Return Values: Returns a clnt_stat enumerated type.See Also: getrpcport(), pmap_getmaps(), pmap_getport(), pmap_set(),pmap_unset().#include bool_tpmap_set(prognum, versnum, protocol, port)u_long prognum;u_long versnum;int protocol;u_short port;ParameterprognumversnumprotocolportDescriptionIdentifies the local program number.Identifies the version number of the local program.Specifies the transport protocol used by the local program.Identifies the port to which the local program is mapped.Description: The pmap_set() call sets the mapping of the program (specified byprognum, versnum, and protocol) toport on the local machine. This procedure isautomatically called by the svc_register() procedure.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: getrpcport(), pmap_getmaps(), pmap_getport(), pmap_rmtcall(),pmap_unset().pmap_unset()#include bool_tpmap_unset(prognum, versnum)u_long prognum;u_long versnum;ParameterprognumversnumDescriptionIdentifies the local program number.Identifies the version number of the local program.Chapter 6. Remote Procedure Calls 221


pmap_unset()Description: The pmap_unset() call removes the mappings associated withprognum and versnum on the local machine. All ports for each transport protocolcurrently mapping the prognum and versnum are removed from the portmapservice.registerrpc()Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: getrpcport(), pmap_getmaps(), pmap_getport(), pmap_rmtcall(),pmap_set().#include intregisterrpc(prognum, versnum, procnum, procname, inproc, outproc)u_long prognum;u_long versnum;u_long procnum;char *(*procname) ();xdrproc_t inproc;xdrproc_t outproc;ParameterprognumversnumprocnumprocnameinprocoutprocDescriptionThe program number to register.Identifies the version number to register.Specifies the procedure number to register.Specifies the procedure that is called when the registered programis requested. procname must accept a pointer to its arguments, andreturn a static pointer to its results.Specifies the XDR routine used to decode the arguments.Specifies the XDR routine that encodes the results.Description: The registerrpc() call registers a procedure (prognum, versnum,procnum) with the local Portmapper, and creates a control structure to rememberthe server procedure and its XDR routine. The control structure is used bysvc_run(). When a request arrives for the program (prognum, versnum, procnum), theprocedure procname is called. Procedures registered using registerrpc() are accessedusing the UDP transport layer.Note: xdr_enum() cannot be used as an argument to registerrpc(). See“xdr_enum()” on page 233 for more information.Return Values: The value 0 indicates success; the value −1 indicates an error.See Also: svc_register(), svc_run().svc_destroy()222 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


svc_destroy()#include voidsvc_destroy(xprt)SVCXPRT *xprt;ParameterxprtDescriptionPoints to the service transport handle.Description: The svc_destroy() call deletes the RPC service transport handle xprt,which becomes undefined after this routine is called.See Also: svcraw_create(), svctcp_create(), svcudp_create().svc_freeargs()#include bool_tsvc_freeargs(xprt, inproc, in)SVCXPRT *xprt;xdrproc_t inproc;char *in;ParameterxprtinprocinDescriptionPoints to the service transport handle.Specifies the XDR routine used to decode the arguments.Points to the input arguments.Description: The svc_freeargs() call frees storage allocated to decode thearguments to a service procedure using svc_getargs().Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: svc_getargs().svc_getargs()#include bool_tsvc_getargs(xprt, inproc, in)SVCXPRT *xprt;xdrproc_t inproc;char *in;ParameterxprtinprocinDescriptionPoints to the service transport handle.Specifies the XDR routine used to decode the arguments.Points to the decoded arguments.Description: The svc_getargs() call uses the XDR routine inproc to decode thearguments of an RPC request associated with the RPC service transport handlexprt. The results are placed at address in.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: svc_freeargs().Chapter 6. Remote Procedure Calls 223


svc_getcaller()svc_getcaller()#include struct sockaddr_in *svc_getcaller(xprt)SVCXPRT *xprt;ParameterxprtDescriptionPoints to the service transport handle.svc_getreq()Description: This macro obtains the network address of the client associated withthe service transport handle xprt.Return Values: Returns a pointer to a sockaddr_in structure.See Also: get_myaddress().#include voidsvc_getreq(rdfds)int rdfds;ParameterrdfdsDescriptionSpecifies the read descriptor bit mask.Description: The svc_getreq() call is used rather than svc_run() to implementasynchronous event processing. The routine returns control to the program whenall sockets have been serviced.See Also: svc_run().svc_register()#include bool_tsvc_register(xprt, prognum, versnum, dispatch, protocol)SVCXPRT *xprt;u_long prognum;u_long versnum;void (*dispatch) ();int protocol;ParameterxprtprognumversnumdispatchDescriptionPoints to the service transport handle.Specifies the program number to be registered.Specifies the version number of the program to be registered.Specifies the dispatch routine associated with prognum andversnum.Specifies the structure of the dispatch routine is:224 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


svc_register()#include protocoldispatch(request, xprt)struct svc_req *request;SVCXPRT *xprt;Specifies the protocol used. The value is generally one of thefollowing:v 0 (zero)v <strong>IP</strong>PROTO_UDPv <strong>IP</strong>PROTO_<strong>TCP</strong>When a value of 0 is used, the service is not registered withPortmapper.svc_run()Note: When using a dummy RPC service transport created with svcraw_create(), acall to xprt_register() must be made immediately after a call to svc_register().Description: The svc_register() call associates the program described by (prognum,versnum) with the service dispatch routine dispatch.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: registerrpc(), svc_unregister(), xprt_register().The svc_run() call has no parameters.#include voidsvc_run()Description: The svc_run() call does not return control. It accepts RPC requestsand calls the appropriate service using svc_getreq().See Also: registerrpc(), svc_getreq().svc_sendreply()#include bool_tsvc_sendreply(xprt, outproc, out)SVCXPRT *xprt;xdrproc_t outproc;char *out;ParameterxprtoutprocoutDescriptionPoints to the caller’s transport handle.Specifies the XDR procedure used to encode the results.Points to the results.Description: The svc_sendreply() call is called by the service dispatch routine tosend the results of the call to the caller.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_call().Chapter 6. Remote Procedure Calls 225


svc_unregister()svc_unregister()#include voidsvc_unregister(prognum, versnum)u_long prognum;u_long versnum;ParameterprognumversnumDescriptionSpecifies the program number that is removed.Specifies the version number of the program that is removed.Description: The svc_unregister() call removes all local mappings of (prognum,versnum) to dispatch routines and (prognum, versnum, *) to port numbers.svcerr_auth()See Also: svc_register().#include voidsvcerr_auth(xprt, why)SVCXPRT *xprt;enum auth_stat why;ParameterxprtwhyDescriptionPoints to the service transport handle.Specifies the reason the call is refused.Description: The svcerr_auth() call is called by a service dispatch routine thatrefuses to execute an RPC request because of authentication errors.See Also: svcerr_decode(), svcerr_noproc(), svcerr_noprog(), svcerr_progvers(),svcerr_systemerr(), svcerr_weakauth().svcerr_decode()#include voidsvcerr_decode(xprt)SVCXPRT *xprt;ParameterxprtDescriptionPoints to the service transport handle.Description: The svcerr_decode() call is called by a service dispatch routine thatcannot decode its parameters.See Also: svcerr_auth(), svcerr_noproc(), svcerr_noprog(), svcerr_progvers(),svcerr_systemerr(), svcerr_weakauth().svcerr_noproc()226 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


svcerr_noproc()#include voidsvcerr_noproc(xprt)SVCXPRT *xprt;ParameterxprtDescriptionPoints to the service transport handle.Description: The svcerr_noproc() call is called by a service dispatch routine thatdoes not implement the requested procedure.See Also: svcerr_auth(), svcerr_decode(), svcerr_noprog(), svcerr_progvers(),svcerr_systemerr(), svcerr_weakauth().svcerr_noprog()#include voidsvcerr_noprog(xprt)SVCXPRT *xprt;ParameterxprtDescriptionPoints to the service transport handle.Description: Description:program is not registered.The svcerr_noprog() call is used when the desiredSee Also: svcerr_auth(), svcerr_decode(), svcerr_noproc(), svcerr_progvers(),svcerr_systemerr(), svcerr_weakauth().svcerr_progvers()#include voidsvcerr_progvers(xprt, low_vers, high_vers)SVCXPRT *xprt;u_long low_vers;u_long high_vers;Parameterxprtlow_vershigh_versDescriptionPoints to the service transport handle.Specifies the low version number that does not match.Specifies the high version number that does not match.Description: The svcerr_progvers() call is called when the version numbers oftwo RPC programs do not match. The low version number corresponds to thelowest registered version, and the high version corresponds to the highest versionregistered on the portmapper.See Also: svcerr_auth(), svcerr_decode(), svcerr_noproc(), svcerr_noprog(),svcerr_progvers(), svcerr_systemerr(), svcerr_weakauth().svcerr_systemerr()Chapter 6. Remote Procedure Calls 227


svcerr_systemerr()#include voidsvcerr_systemerr(xprt)SVCXPRT *xprt;ParameterxprtDescriptionPoints to the service transport handle.Description: The svcerr_systemerr() call is called by a service dispatch routinewhen it detects a system error that is not handled by the protocol.See Also: svcerr_auth(), svcerr_decode(), svcerr_noproc(), svcerr_noprog(),svcerr_progvers(), svcerr_weakauth().svcerr_weakauth()#include voidsvcerr_weakauth(xprt)SVCXPRT *xprt;ParameterxprtDescriptionPoints to the service transport handle.Note: This is the equivalent of: svcerr_auth(xprt, AUTH_TOOWEAK).Description: The svcerr_weakauth() call is called by a service dispatch routinethat cannot execute an RPC because of correct but weak authentication parameters.See Also: svcerr_auth(), svcerr_decode(), svcerr_noproc(), svcerr_noprog(),svcerr_progvers(), svcerr_systemerr().svcraw_create()The svcraw_create() call has no parameters.#include SVCXPRT *svcraw_create()Description: The svcraw_create() call creates a local RPC service transport usedfor timings, to which it returns a pointer. Messages are passed using a bufferwithin the virtual machine of the local process; so, the client process must also usethe same virtual machine. This allows the simulation of RPC programs within onecomputer. See “clntraw_create()” on page 216 for more information.Return Values: NULL indicates failure.See Also: clntraw_create(), svc_destroy(), svctcp_create(), svcudp_create().svctcp_create()228 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


svctcp_create()#include SVCXPRT *svctcp_create(sock, send_buf_size, recv_buf_size)int sock;u_int send_buf_size;u_int recv_buf_size;Parametersocksend_buf_sizerecv_buf_sizeDescriptionSpecifies the socket descriptor. If sock is RPC_ANYSOCK, a newsocket is created. If the socket is not bound to a local <strong>TCP</strong> port, itis bound to an arbitrary port.Specifies the size of the send buffer. Specify 0 to choose the default.Specifies the size of the receive buffer. Specify 0 to choose thedefault.Description: The svctcp_create() call creates a <strong>TCP</strong>-based service transport towhich it returns a pointer. xprt—>xp_sock contains the transport’s socketdescriptor. xprt—>xp_port contains the transport’s port number.Return Values: NULL indicates failure.See Also: svc_destroy(), svcraw_create(), svcudp_create().svcudp_create()#include SVCXPRT *svcudp_create(sock, sendsz, recvsz)int sock;u_int sendsz;u_int recvsz;ParametersocksendszrecvszDescriptionSpecifies the socket descriptor. If sock is RPC_ANYSOCK, a newsocket is created. If the socket is not bound to a local <strong>TCP</strong> port, itis bound to an arbitrary port.Specifies the size of the send buffer.Specifies the size of the receive buffer.Description: The svcudp_create() call creates a UDP-based service transport towhich it returns a pointer. xprt—>xp_sock contains the transport’s socketdescriptor. xprt—>xp_port contains the transport’s port number.Return Values: NULL indicates failure.See Also: svc_destroy(), svcraw_create(), svctcp_create().xdr_accepted_reply()Chapter 6. Remote Procedure Calls 229


xdr_accepted_reply()#include bool_txdr_accepted_reply(xdrs, ar)XDR *xdrs;struct accepted_reply *ar;ParameterxdrsarDescription:DescriptionPoints to an XDR stream.Points to the reply to be represented.The xdr_accepted_reply() call translates RPC reply messages.xdr_array()Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include bool_txdr_array(xdrs, arrp, sizep, maxsize, elsize, elproc)XDR *xdrs;char **arrp;u_int *sizep;u_int maxsize;u_int elsize;xdrproc_t elproc;ParameterxdrsarrpsizepmaxsizeelsizeelprocDescriptionPoints to an XDR stream.Specifies the address of the pointer to the array.Points to the element count of the array.Specifies the maximum number of elements accepted.Specifies the size of each of the array’s elements, found usingsizeof().Specifies the XDR routine that translates an individual arrayelement.Description: The xdr_array() call translates between an array and its externalrepresentation.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().xdr_authunix_parms()230 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


xdr_authunix_parms()#include bool_txdr_authunix_parms(xdrs, aupp)XDR *xdrs;struct authunix_parms *aupp;ParameterxdrsauppDescription:information.DescriptionPoints to an XDR stream.Points to the authentication information.The xdr_authunix_parms() call translates UNIX-based authenticationxdr_bool()Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include bool_txdr_bool(xdrs, bp)XDR *xdrs;bool_t *bp;ParameterxdrsbpDescriptionPoints to an XDR stream.Points to the Boolean.xdr_bytes()Description: The xdr_bool() call translates between Booleans and their externalrepresentation.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include bool_txdr_bytes(xdrs, sp, sizep, maxsize)XDR *xdrs;char **sp;u_int *sizep;u_int maxsize;ParameterxdrsspsizepmaxsizeDescriptionPoints to an XDR stream.Points to a pointer to the byte string.Points to the byte string size.Specifies the maximum size of the byte string.Chapter 6. Remote Procedure Calls 231


xdr_bytes()Description: The xdr_bytes() call translates between byte strings and theirexternal representations.xdr_callhdr()Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include bool_txdr_callhdr(xdrs, chdr)XDR *xdrs;struct rpc_msg *chdr;ParameterxdrschdrDescription:format.DescriptionPoints to an XDR stream.Points to the call header.The xdr_callhdr() call translates an RPC message header into XDRReturn Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().xdr_callmsg()#include bool_txdr_callmsg(xdrs, cmsg)XDR *xdrs;struct rpc_msg *cmsg;ParameterxdrscmsgDescriptionPoints to an XDR stream.Points to the call message.xdr_double()Description: The xdr_callmsg() call translates RPC messages (header andauthentication, not argument data) to and from the xdr format.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().232 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


xdr_double()#include bool_txdr_double(xdrs, dp)XDR *xdrs;double *dp;ParameterxdrsdpDescriptionPoints to an XDR stream.Points to a double-precision number.xdr_enum()Description: The xdr_double() call translates between C double-precisionnumbers and their external representations.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include bool_txdr_enum(xdrs, ep)XDR *xdrs;enum_t *ep;ParameterxdrsepDescriptionPoints to an XDR stream.Points to the enumerated number. enum_t can be any enumerationtype such as enum colors, with colors declared as enum colors(black, brown, red).Description: The xdr_enum() call translates between C-enumerated groups andtheir external representation. When calling the procedures callrpc() andregisterrpc(), a stub procedure must be created for both the server and the clientbefore the procedure of the application program using xdr_enum(). The followingis the format of the stub procedure.The xdr_enum_t procedure is used as the inproc and outproc in both the client and#include enum colors (black, brown, red)voidstatic xdr_enum_t(xdrs, ep)XDR *xdrs;enum colors *ep;{xdr_enum(xdrs, ep)}server RPCs.For example, an RPC client would contain the following lines:Chapter 6. Remote Procedure Calls 233


xdr_enum().xdr_float()error = callrpc(argv[1],ENUMRCVPROG,VERSION,ENUMRCVPROC,xdr_enum_t,&innumber,xdr_enum_t,&outnumber);.An RPC server would contain the following line:Return Values: The value 1 indicates success; the value 0 indicates an error..registerrpc(ENUMRCVPROG,VERSION,ENUMRCVPROC,xdr_enum_t,xdr_enum_t);.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include bool_txdr_float(xdrs, fp)XDR *xdrs;float *fp;ParameterxdrsfpDescriptionPoints to an XDR stream.Points to the floating-point number.xdr_inline()Description: The xdr_float() call translates between C floating-point numbers andtheir external representations.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include long *xdr_inline(xdrs, len)XDR *xdrs;u_int len;ParameterxdrslenDescriptionPoints to an XDR stream.Specifies the byte length of the desired buffer.Description: The xdr_inline() call returns a pointer to a continuous piece of theXDR stream’s buffer. The value is long * rather than char *, because the externaldata representation of any object is always an integer multiple of 32 bits.234 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


xdr_int()Note: xdr_inline() can return NULL if there is not sufficient space in the streambuffer to satisfy the request.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include bool_txdr_int(xdrs, ip)XDR *xdrs;int *ip;xdr_inline()ParameterxdrsipDescriptionPoints to an XDR stream.Points to the integer.xdr_long()Description: The xdr_int() call translates between C integers and their externalrepresentations.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include bool_txdr_long(xdrs, lp)XDR *xdrs;long *lp;ParameterxdrslpDescriptionPoints to an XDR stream.Points to the long integer.Description: The xdr_long() call translates between C long integers and theirexternal representations.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().xdr_opaque()Chapter 6. Remote Procedure Calls 235


xdr_opaque()#include bool_txdr_opaque(xdrs, cp, cnt)XDR *xdrs;char *cp;u_int cnt;ParameterxdrscpcntDescriptionPoints to an XDR stream.Points to the opaque object.Specifies the size of the opaque object.Description: The xdr_opaque() call translates between fixed-size opaque data andits external representation.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().xdr_opaque_auth()#include bool_txdr_opaque_auth(xdrs, ap)XDR *xdrs;struct opaque_auth *ap;ParameterxdrsapDescription:DescriptionPoints to an XDR stream.Points to the opaque authentication information.The xdr_opaque_auth() call translates RPC message authentications.xdr_pmap()Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include bool_txdr_pmap(xdrs, regs)XDR *xdrs;struct pmap *regs;ParameterxdrsregsDescriptionPoints to an XDR stream.Points to the portmap parameters.Description: The xdr_pmap() call translates an RPC procedure identification, suchas is used in calls to Portmapper.Return Values: The value 1 indicates success; the value 0 indicates an error.236 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().xdr_pmaplist()#include bool_txdr_pmaplist(xdrs, rp)XDR *xdrs;struct pmaplist **rp;xdr_pmap()ParameterxdrsrpDescriptionPoints to an XDR stream.Points to a pointer to the portmap data array.Description: The xdr_pmaplist() call translates a variable number of RPCprocedure identifications, such as Portmapper creates.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().xdr_pointer()#include bool_txdr_pointer(xdrs, pp, size, proc)XDR *xdrs;char **pp;u_int size;xdrproc_t proc;ParameterxdrsppsizeprocDescriptionPoints to an XDR stream.Points to a pointer.Specifies the size of the target.Specifies the XDR procedure that translates an individual elementof the type addressed by the pointer.Description: The xdr_pointer() call provides pointer-chasing within structures.This differs from the xdr_reference() call in that it can serialize or deserialize treescorrectly.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().xdr_reference()Chapter 6. Remote Procedure Calls 237


xdr_reference()#include bool_txdr_reference(xdrs, pp, size, proc)XDR *xdrs;u_int size;xdrproc_t proc;ParameterxdrsppsizeprocDescription:DescriptionPoints to an XDR stream.Points to a pointer.Specifies the size of the target.Specifies the XDR procedure that translates an individual elementof the type addressed by the pointer.The xdr_reference() call provides pointer-chasing within structures.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().xdr_rejected_reply()#include bool_txdr_rejected_reply(xdrs, rr)XDR *xdrs;struct rejected_reply *rr;ParameterxdrsrrDescription:DescriptionPoints to an XDR stream.Points to the rejected reply.The xdr_rejected_reply() call translates RPC reply messages.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().xdr_replymsg()#include bool_txdr_replymsg(xdrs, rmsg)XDR *xdrs;struct rpc_msg *rmsg;ParameterxdrsrmsgDescription:DescriptionPoints to an XDR stream.Points to the reply message.The xdr_replymsg() call translates RPC reply messages.238 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


xdr_short()Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include bool_txdr_short(xdrs, sp)XDR *xdrs;short *sp;xdr_replymsg()ParameterxdrsspDescriptionPoints to an XDR stream.Points to the short integer.xdr_string()Description: The xdr_short() call translates between C short integers and theirexternal representations.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include bool_txdr_string(xdrs, sp, maxsize)XDR *xdrs;char **sp;u_int maxsize;ParameterxdrsspmaxsizeDescriptionPoints to an XDR stream.Points to a pointer to the string.Specifies the maximum size of the string.xdr_u_int()Description: The xdr_string() call translates between C strings and their externalrepresentations. The xdr_string() call is the only xdr routine to convert ASCII toEBCDIC.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().Chapter 6. Remote Procedure Calls 239


xdr_u_int()#include bool_txdr_u_int(xdrs, up)XDR *xdrs;unsigned *up;ParameterxdrsupDescriptionPoints to an XDR stream.Points to the unsigned integer.xdr_u_long()Description: The xdr_u_int() call translates between C unsigned integers andtheir external representations.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include bool_txdr_u_long(xdrs, ulp)XDR *xdrs;u_long *ulp;ParameterxdrsulpDescriptionPoints to an XDR stream.Points to the unsigned long integer.Description: The xdr_u_long() call translates between C unsigned long integersand their external representations.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().xdr_u_short()#include bool_txdr_u_short(xdrs, usp)XDR *xdrs;u_short *usp;ParameterxdrsuspDescriptionPoints to an XDR stream.Points to the unsigned short integer.Description: The xdr_u_short() call translates between C unsigned short integersand their external representations.Return Values: The value 1 indicates success; the value 0 indicates an error.240 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


xdr_union()xdr_union()#include bool_txdr_union(xdrs, dscmp, unp, choices, dfault)XDR *xdrs;enum_t *dscmp;char *unp;struct xdr_discrim *choices;xdrproc_t dfault;ParameterxdrsdscmpunpchoicesdfaultDescriptionPoints to an XDR stream.Points to the union’s discriminant. enum_t can be any enumerationtype.Points to the union.Points to an array detailing the XDR procedure to use on each armof the union.Specifies the default XDR procedure to use.xdr_vector()Description: The xdr_union() call translates between a discriminated C union andits external representation.Return Values: The value 1 indicates success; the value 0 indicates an error.The following is an example of this call:#include enum colors (black, brown, red);bool_txdr_union(xdrs, dscmp, unp, choices, dfault)XDR *xdrs;enum colors *dscmp;char *unp;struct xdr_discrim *choices;xdrproc_t dfault;See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().#include bool_txdr_vector(xdrs, basep, nelem, elemsize, xdr_elem)XDR *xdrs;char *basep;u_int nelem;u_int elemsize;xdrproc_t xdr_elem;ParameterxdrsDescriptionPoints to an XDR stream.Chapter 6. Remote Procedure Calls 241


xdr_vector()basepnelemelemsizexdr_elemSpecifies the base of the array.Specifies the element count of the array.Specifies the size of each of the array’s elements, found usingsizeof().Specifies the XDR routine that translates an individual arrayelement.xdr_void()Description: The xdr_vector() call translates between a fixed length array and itsexternal representation. Unlike variable-length arrays, the storage of fixed lengtharrays is static and unfreeable.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().The xdr_void() call has no parameters.#include bool_txdr_void()Description: The xdr_void () call is used like a command that does not requireany other xdr functions. This call can be placed in the inproc or outproc parameterof the clnt_call function when the user does not need to move data.Return Values: Always a value of 1.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().xdr_wrapstring()#include bool_txdr_wrapstring(xdrs, sp)XDR *xdrs;char **sp;ParameterxdrsspDescriptionPoints to an XDR stream.Points to a pointer to the string.Description: The xdr_wrapstring() call is the same as calling xdr_string() with amaximum size of MAXUNSIGNED. It is useful because many RPC proceduresimplicitly invoke two-parameter XDR routines, and xdr_string() is athree-parameter routine.Return Values: The value 1 indicates success; the value 0 indicates an error.See Also: callrpc(), clnt_broadcast(), clnt_call(), clnt_freeres(), pmap_rmtcall(),registerrpc(), svc_freeargs(), svc_getargs(), svc_sendreply().242 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


xdrmem_create()xdrmem_create()#include voidxdrmem_create(xdrs, addr, size, op)XDR *xdrs;char *addr;u_int size;enum xdr_op op;ParameterxdrsaddrsizeopDescriptionPoints to an XDR stream.Points to the memory location.Specifies the maximum size of addr.Determines the direction of the XDR stream (XDR_ENCODE,XDR_DECODE, or XDR_FREE).Description: The xdrmem_create() call initializes the XDR stream pointed to byxdrs. Data is written to, or read from, addr.xdrrec_create()#include voidxdrrec_create(xdrs, sendsize, recvsize, handle, readit, writeit)XDR *xdrs;u_int sendsize;u_int recvsize;char *handle;int (*readit) ();int (*writeit) ();Parameterxdrssendsizerecvsizehandlereadit()writeit()DescriptionPoints to an XDR stream.Indicates the size of the send buffer. Specify 0 to choose thedefault.Indicates the size of the receive buffer. Specify 0 to choose thedefault.Specifies the first parameter passed to readit() and writeit().Called when a stream’s input buffer is empty.Called when a stream’s output buffer is full.Description: The xdrrec_create() call initializes the XDR stream pointed to byxdrs.Notes:1. The op field must be set by the caller.2. This XDR procedure implements an intermediate record string.3. Additional bytes in the XDR stream provide record boundary information.Chapter 6. Remote Procedure Calls 243


xdrrec_endofrecord()xdrrec_endofrecord()#include bool_txdrrec_endofrecord(xdrs, sendnow)XDR *xdrs;int sendnow;ParameterxdrssendnowDescriptionPoints to an XDR stream.Specifies nonzero to write out data in the output buffer.xdrrec_eof()Description: The xdrrec_endofrecord() call can be invoked only on streamscreated by xdrrec_create(). Data in the output buffer is marked as a completerecord.Return Values: The value 1 indicates success; the value 0 indicates an error.#include bool_txdrrec_eof(xdrs)XDR *xdrs;ParameterxdrsDescriptionPoints to an XDR stream.Description: The xdrrec_eof() call can be invoked only on streams created byxdrrec_create().Return Values: The value 1 indicates the current record has been consumed; thevalue 0 indicates continued input on the stream.xdrrec_skiprecord()#include bool_txdrrec_skiprecord(xdrs)XDR *xdrs;ParameterxdrsDescriptionPoints to an XDR stream.Description: The xdrrec_skiprecord() call can be invoked only on streams createdby xdrrec_create(). The XDR implementation is instructed to discard the remainingdata in the input buffer.Return Values: The value 1 indicates success; the value 0 indicates an error.xdrstdio_create()244 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


xdrstdio_create()#include #include voidxdrstdio_create(xdrs, file, op)XDR *xdrs;FILE *file;enum xdr_op op;ParameterxdrsfileopDescriptionPoints to an XDR stream.Specifies the file name for the I/O stream.Determines the direction of the XDR stream (either XDR_ENCODE,XDR_DECODE, or XDR_FREE).Description: The xdrstdio_create() call initializes the XDR stream pointed to byxdrs. Data is written to, or read from, file.Note: fflush() is the destroy routine associated with this procedure. fclose() is notcalled.xprt_register()#include voidxprt_register(xprt)SVCXPRT *xprt;ParameterxprtDescriptionPoints to the service transport handle.Description: The xprt_register() call registers service transport handles with theRPC service package. This routine also modifies the global variable svc_fdsSee Also: svc_register(), svc_fds.xprt_unregister()#include voidxprt_unregister(xprt)SVCXPRT *xprt;ParameterxprtDescriptionPoints to the service transport handle.Description: The xprt_unregister() call unregisters an RPC service transporthandle. A transport handle should be unregistered with the RPC service packagebefore it is destroyed. This routine also modifies the global variable svc_fds.See also: svc_fds.Chapter 6. Remote Procedure Calls 245


Sample RPC ProgramsSample RPC ProgramsThis appendix provides examples of the following programs:v RPC client (see topic 246)v RPC server (see topic 246)v RPC raw data stream (see topic 248)RPC ClientThe following is an example of an RPC client program./* GENESEND.C *//* Send an integer to the remote host and receive the integer back *//* PORTMAPPER AND REMOTE SERVER MUST BE RUNNING */#define <strong>VM</strong>#include #include #include #define intrcvprog ((u_long)150000)#define version ((u_long)1)#define intrcvproc ((u_long)1)main(argc, argv)int argc;char *argv[];{int innumber;int outnumber;int error;if (argc != 3) {fprintf(stderr,“usage: %s hostname integer\n”, argv[0]);exit (-1);} /* endif */innumber = atoi(argv[2]);/** Send the integer to the server. The server should* return the same integer.*/error = callrpc(argv[1],intrcvprog,version,intrcvproc,xdr_int,(char *)&innumber,xdr_int,(char *)&outnumber);if (error != 0) {fprintf(stderr,“error: callrpc failed: %d \n”,error);fprintf(stderr,“intrcprog: %d version: %d intrcvproc: %d”,intrcvprog, version,intrcvproc);exit(1);} /* endif */}printf(“value sent: %dexit(0);value received: %d\n”, innumber, outnumber);RPC ServerThe following is an example of an RPC server program./* GENERIC SERVER *//* RECEIVE AN INTEGER OR FLOAT AND RETURN THEM RESPECTIVELY *//* PORTMAPPER MUST BE RUNNING */#define <strong>VM</strong>246 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


RPC Server#include #include #define intrcvprog ((u_long)150000)#define fltrcvprog ((u_long)150102)#define intvers ((u_long)1)#define intrcvproc ((u_long)1)#define fltrcvproc ((u_long)1)#define fltvers ((u_long)1)main(){int *intrcv();float *floatrcv();/*REGISTER PROG, VERS AND PROC WITH THE PORTMAPPER*//*FIRST PROGRAM*/registerrpc(intrcvprog,intvers,intrcvproc,intrcv,xdr_int,xdr_int);printf(“Intrcv Registration with Port Mapper completed\n”);/*OR MULT<strong>IP</strong>LE PROGRAMS*/registerrpc(fltrcvprog,fltvers,fltrcvproc,floatrcv,xdr_float,xdr_float);printf(“Floatrcv Registration with Port Mapper completed\n”);}/** svc_run will handle all requests for programs registered.*/svc_run();printf(“Error:svc_run returned!\n”);exit(1);/** Procedure called by the server to receive and return an integer.*/int *intrcv(in)int *in;{int *out;}printf(“integer received: %d\n”,*in);out = in;printf(“integer being returned: %d\n”,*out);return (out);/** Procedure called by the server to receive and return a float.*/float *floatrcv(in)float *in;{float *out;}printf(“float received: %e\n”,*in);out=in;printf(“float being returned: %e\n”,*out);return(out);Chapter 6. Remote Procedure Calls 247


RPC Raw Data StreamRPC Raw Data StreamThe following is an example of an RPC raw data stream program./*RAWEX *//* AN EXAMPLE OF THE RAW CLIENT/SERVER USAGE *//* PORTMAPPER MUST BE RUNNING *//** This program does not access an external interface. It provides* a test of the raw RPC interface allowing a client and server* program to be in the same process.*/#define <strong>VM</strong>#include #include #define rawprog ((u_long)150104)#define rawvers ((u_long)1)#define rawproc ((u_long)1)extern enum clnt_stat clntraw_call();extern void raw2();main(argc,argv)int argc;char *argv[];{SVCXPRT *transp;struct hostent *hp;struct timeval pertry_timeout, total_timeout;struct sockaddr_in server_addr;int bout,in;register CLIENT *clnt;enum clnt_stat cs;int addrlen;/** The only argument passed to the program is an integer to* be transferred from the client to the server and back.*/if(argc!=2) {printf(“usage: %s integer\n”, argv[0]);exit(-1);}in = atoi(argv[1]);/** Create the raw transport handle for the server.*/transp = svcraw_create();if (transp == NULL) {fprintf(stderr, “can’t create an RPC server transport\n”);exit(-1);}/* In case the program is already registered, deregister it */pmap_unset(rawprog, rawvers);/* Register the server program with PORTMAPPER */if (!svc_register(transp,rawprog,rawvers,raw2, 0)) {fprintf(stderr, “can’t register service\n”);exit(-1);}/** The following registers the transport handle with internal248 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


RPC Raw Data Stream* data structures.*/xprt_register(transp);/** Create the client transport handle.*/if ((clnt = clntraw_create(rawprog, rawvers)) == NULL ) {clnt_pcreateerror(“clntudp_create”);exit(-1);}total_timeout.tv_sec = 60;total_timeout.tv_usec = 0;printf(“Argument: %d\n”,in);/** Make the call from the client to the server.*/cs=clnt_call(clnt,rawproc,xdr_int,(char *)&in,xdr_int,(char *)&bout,total_timeout);}printf(“Result: %d”,bout);if(cs!=0) {clnt_perror(clnt,“Client call failed”);exit(1);}exit(0);/** Service procedure called by the server when it receives the client* request.*/void raw2(rqstp,transp)struct svc_req *rqstp;SVCXPRT *transp;{int in,out;if (rqstp->rq_proc=rawproc) {/** Unpack the integer passed by the client.*/svc_getargs(transp,xdr_int,&in);printf(“Received: %d\n”,in);/** Send the integer back to the client.*/out=in;printf(“Sent: %d\n”,out);if (!svc_sendreply(transp, xdr_int,&out)) {printf(“Can’t reply to RPC call.\n”);exit(1);}}}Chapter 6. Remote Procedure Calls 249


RPC Raw Data Stream250 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Chapter 7. X Window System InterfaceWhat Is ProvidedSoftware RequirementsThis chapter contains information specific to the <strong>VM</strong> implementation of the XWindow System. The X Window System application program interface (API)allows you to write applications in the <strong>VM</strong>/CMS environment that can bedisplayed on X11 servers on a <strong>TCP</strong>/<strong>IP</strong>-based network. This API provides theapplication with graphics capabilities as defined by the X Window Systemprotocol. For more information about the X protocol and application programinterface, see the X Window System publications listed in “Bibliography” onpage 447.The X Window System support provided with <strong>TCP</strong>/<strong>IP</strong> includes support for thefollowing API from the X Window System Version 11, Release 4:v X11LIB TXTLIB (Xlib, Xmu, Xext, and Xau routines)v OLDXLIB TXTLIB (X Release 10 compatibility routines)v XTLIB TXTLIB (X Intrinsics)v XAWLIB TXTLIB (Athena widget set)v Header files needed for compiling X clientsIn addition, it also includes support for the following API based on Release 1.1 ofthe OSF/Motif-based widget set:v XMLIB TXTLIB (OSF/Motif-based widget set)v Header files needed for compiling clients using the OSF/Motif-based widget set.Application programs using the X Window System API are written in C andrequire the following:vv<strong>IBM</strong> C for <strong>VM</strong>/ESA Compiler, Version 3 Release 1 Program (Program Number5654-033).<strong>IBM</strong> Language Environment ® for MVS & <strong>VM</strong>, Version 1 Release 5 Program(Program Number 5688-198).Using the X Window System Interface in the <strong>VM</strong> EnvironmentThe X Window System is a network-transparent protocol that supports windowingand graphics. The protocol is communicated between a client or application and anX server over a reliable bidirectional byte stream. This byte stream is provided bythe <strong>TCP</strong>/<strong>IP</strong> communication protocol.In the <strong>VM</strong>/CMS environment, X Window System support consists of a set ofapplication calls that create the X protocol, as requested by the application. Thisapplication program interface allows an application to be created, which uses the XWindow System protocol to be displayed on an X server.In an X Window System environment, the X server distributes user input to andaccepts requests from various client programs located either on the same system orelsewhere on a network. The X client code uses sockets to communicate with the Xserver.© Copyright <strong>IBM</strong> Corp. 1987, 2001 251


X Window System InterfaceFigure 29 shows a high-level abstraction of how the X Window System works in a<strong>VM</strong> environment. As an application writer, you need to be concerned only with theclient API in writing your application.User Virtual Machine┌────────────────────┬───────────────────┐│ │ ││ CMS │ ││ Application │ ││ │ ││ │ ││ (X client) │ ││ │ │├───XOpenDisplay()───┤││ │ ││ │ │ ┌──────────────┐│ X11.4 Routines │ │ │ ││ │ │ │ X server ││ │ <strong>TCP</strong><strong>IP</strong> │ INTERNET │ ││ (Xlib) │ ├──────────────┤ ││ │ │ │ │├──────socket()──────┤ Virtual │ │ ││ │ │ │ ││ │ │ │ ││ <strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong> │ Machine │ │ ││ │ │ └──────────────┘│ │ ││ │ ││ │ │├────────iucv────────┴───────iucv────────┤│ ││ │ │ ││ └───────────────────┘ ││││ C P │││└────────────────────────────────────────┘Figure 29. <strong>VM</strong> X Window System Application to ServerThe communication path from the <strong>VM</strong> X Window System application to the serverinvolves the client code and <strong>TCP</strong>/<strong>IP</strong>. The application program that you create isthe client part of a client-server relationship. The X server provides access to theresources that are shared among many X applications, such as the screen,keyboard, mouse, fonts, and graphics contexts. A single X server can control morethan one physical screen.Each client can interact with multiple servers, and each server can interact withmultiple clients.If your application is written to the Xlib interface, it calls XOpenDisplay() to startcommunication with an X server on a workstation. The Xlib code opens acommunication path called a socket to the X server, and sends the appropriate Xprotocol to initiate client-server communication.The X protocol generated by the Window System client code uses an ISO Latin-1encoding for character strings, while the <strong>VM</strong>/CMS encoding for character strings isEBCDIC. The X Window System client code in the <strong>VM</strong>/CMS environmentautomatically transforms character strings from EBCDIC to ISO Latin-1 or fromISO Latin-1 to EBCDIC, as needed using internal translate tables.252 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Application Resource FileWhen programming using the C/<strong>VM</strong> Compiler, CMS file identifiers are specifiedas filename filetype filemode. In the following sections a file specified asfilename.filetype refers to the CMS file, file name file type.In the <strong>VM</strong>/CMS environment, external names must be eight characters or less.Many of the X Window System application program interface names exceed thislimit. To support the X API in CMS, all X names longer than eight characters areremapped to unique names using the C compiler preprocessor. This nameremapping is found in a header file called X11GLUE.H, which is automaticallyincluded in your program when you include the standard X header file calledXLIB.H. In debugging your application, it may be helpful to reference theX11GLUE.H header file to find the remapped names of the X API routines.The X Window System allows you to modify certain characteristics of anapplication at run time by means of application resources. Typically, applicationresources are set to tailor the appearance and possibly the behavior of anapplication. The application resources may specify information about anapplication’s window sizes, placement, coloring, font usage, and other functionaldetails.On a UNIX system, this information can be found in the user’s home directory in afile called ·Xdefaults. In the <strong>VM</strong>/CMS environment, this file is calledX DEFAULTS. Each line of this file represents resource information for anapplication. Figure 30 shows an example of a set of resources specified for a typicalX Window System application.XClock*geometry: 500x60+5-5XClock*font: -bitstream-*-bold-r-*-33-240-*XClock*foreground: orangeXClock*background: skyblueXClock*borderWidth: 4XClock*borderColor: blueXClock*analog: falseX Window System InterfaceFigure 30. Resources Specified for a Typical X Window System ApplicationIn this example, the Xclock application automatically creates a window in thelower left corner of the screen with a digital display in orange letters on a skybluebackground.These resources can also be set on the RESOURCE_MANAGER property of the Xserver, which allows a single, central place where resources are found, whichcontrol all applications that are displayed on an X server. You can use the xrdbprogram to control the X server resource database in the resource property.The xrdb program is an X client that you can use either to get or to set thecontents of the RESOURCE_MANAGER property on the root window of screen 0.This property is then used by all applications at startup to control the applicationresource.Chapter 7. X Window System Interface 253


X Window System InterfaceIdentifying the Target DisplayA CMS global command is used by the X Window System to identify the internetaddress of the target display.The following is the format of the CMS global command.►► GLOBALV SELECT CENV SET DISPLAY internet_address :target_server ►►.target_screen►◄ParameterDescriptioninternet_addressSpecifies the internet address of the host machine on which the XWindow System server is running.target_servertarget_screenSpecifies the number of the display server on the host machine.Specifies the screen to be used on the same target server.Creating an ApplicationTo create an application that uses the X Window System protocol, you shouldstudy the X Window System application program interface.You should ensure that the first X header file your program includes is the XLIB.Hheader file. This file defines a number of preprocessor symbols, which enable yourprogram to compile correctly. If your program uses the X Intrinsics, you shouldensure that the INTRINSIC.H header file is the first X header file included in yourprogram. This file defines a number of preprocessor symbols that allow yourprogram to compile correctly. In addition, these header files include the CMSheader files that remap the external names of the X Window System routines toshorter names that are unique within the X Window System support in <strong>TCP</strong>/<strong>IP</strong>.Generating X-Window System Applications||||The following steps should serve as a guideline for generating an X WindowSystem application called myxprog. Your installation may have different names ortechniques for performing these steps.Before you begin to generate your application, make sure you have access to theC/<strong>VM</strong> Compiler and to the <strong>TCP</strong>MAINT 592 minidisk, where the X WindowSystem support is installed. To compile your application, do the following:1. Set the LOADLIB and TXTLIB search order by entering the following GLOBALcommands:SET LDRTBLS 25GLOBAL LOADLIB SCEERUNGLOBAL TXTLIB X11LIB COMMTXT CMSLIB2. Compile the application with the <strong>IBM</strong> C for <strong>VM</strong>/ESA Compiler by entering thefollowing command:CC myxprog (DEFINE(<strong>IBM</strong>CPP)254 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System InterfaceThe option passed to the CC EXEC defines the preprocessor symbol <strong>IBM</strong>CPP,which is used in many of the X Window System header files by the Cpreprocessor to generate the correct code for use under CMS. To simplifycompiling X Window System applications, you can create a version of the CCEXEC that automatically defines this symbol. If your application includes theXLIB.H header file as the first included X Window System header file, you donot have to define the <strong>IBM</strong>CPP preprocessor symbol, because it is automaticallydefined by this header file.||For applications written using the X Window System Toolkit, including theINTRINSIC.H header file as the first X Window System header file also definesthe preprocessor symbol for you. You do not have to define it again when youinvoke the compiler.3. Generate the executable module by entering the CMOD command:CMOD myxprogYou should now have the file, myxprog MODULE, on your A disk. Verify thatyou have set the LOADLIB and TXTLIB search order. To run this module, dothe following:4. Specify the <strong>IP</strong> address of the X server on which you wish to display theapplication output by setting the DISPLAY global variable in the CENV (CEnvironment) group of global variables:GLOBALV SELECT CENV SET DISPLAY charm.cambridge.ibm.com:0.0orGLOBALV SELECT CENV SET DISPLAY 129.42.3.105:0.0Note: charm.cambridge.ibm.com:0.0 and 129.42.3.105:0.0 are exampleaddresses.5. Allow the host application access to the X server.On the workstation where you wish to display the application output, youmust grant permission for the <strong>VM</strong> host to access the X server. To do this enterthe xhost command:xhost cambvm3|Note: cambvm3 is an example host name.6. Run the application by entering the following command:myxprogTypically, an X application uses the global variable DISPLAY in the CENV group asthe X server address on which it is to display. Some applications also allow you tospecify this information as a command line option. You should refer to thedocumentation for the application you are attempting to run for these and otheroptions that are available to you.In the preceding example, the application is displayed on the X server at theinternet address associated with the name charm.cambridge.ibm.com. Theapplication is displayed on the X server on screen 0 on this system.In the preceding example, the GLOBAL TXTLIB command specified the X11LIBand COMMTXT TXTLIBs in the TXTLIB search order. Depending on the facilitiesof X that your application makes use of, additional libraries may have to bespecified to generate your application. For example, to generate an application thatis written to the OSF/Motif interface, specify the following command:Chapter 7. X Window System Interface 255


X Window System InterfaceGLOBAL TXTLIB XMLIB XTLIB X11LIB COMMTXT CMSLIBTable 23 describes the various TXTLIBs associated with the X Window Systemsupport in the <strong>VM</strong>/CMS environment.Table 23. TXTLIBs Associated with X Window System SupportTXTLIBX11LIBOLDXLIBXTLIBXAWLIBXMLIBRoutine(s)X11.4 X Window System client routines andX11.4 Miscellaneous Utility routinesX10 Compatibility routinesX11.4 Intrinsics routinesAthena widget routinesOSF/Motif-based widget routinesX Window System SubroutinesThis section provides information about X Window System in tabular form forquick reference.The following tables list the subroutines supported by <strong>TCP</strong>/<strong>IP</strong> Level 320 for <strong>VM</strong>.The subroutines are grouped according to the type of function provided.Opening and Closing a DisplayTable 24 provides the subroutines for opening and closing a display.Table 24. Opening and Closing DisplaySubroutineXCloseDisplay()XFree()XNoOp()XOpenDisplay()DescriptionCloses a display.Frees in-memory data created by Xlibfunction.Executes a NoOperation protocol request.Opens a display.Creating and Destroying WindowsTable 25 provides the subroutines for creating and destroying windows.Table 25. Creating and Destroying WindowsSubroutineXConfigureWindow()XCreateSimpleWindow()XCreateWindow()XDestroySubwindows()XDestroyWindow()DescriptionConfigures the specified window.Creates unmapped InputOutput subwindow.Creates unmapped subwindow.Destroys all subwindows of specifiedwindow.Unmaps and destroys window and allsubwindows.256 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Manipulating WindowsTable 26 provides the subroutines for manipulating windows.Table 26. Manipulating WindowsSubroutineXCirculateSubwindows()XCirculateSubwindowsUp()XCirculateSubwindowsDown()XIconifyWindow()XLowerWindow()XMapRaised()XMapSubwindows()XMapWindow()XMoveResizeWindow()XMoveWindow()XRaiseWindow()XReconfigureWMWindow()XResizeWindow()XRestackWindows()XSetWindowBorderWidth()XUnmapSubwindows()XUnmapWindow()XWithdrawWindow()X Window System InterfaceDescriptionCirculates a subwindow up or down.Raises the lowest mapped child of thewindow.Lowers the highest mapped child of thewindow.Sends a WM_CHANGE_STATEClientMessage to the root window of thespecified screen.Lowers the specified window.Maps and raises the specified window.Maps all subwindows of the specifiedwindow.Maps the specified window.Changes the specified window’s size andlocation.Moves the specified window.Raises the specified window.Issues a ConfigureWindow request on thespecified top-level window.Changes the specified window’s size.Restacks a set of windows from top tobottom.Changes the border width of the window.Unmaps all subwindows of the specifiedwindow.Unmaps the specified window.Unmaps the specified window and sends asynthetic UnmapNotify event to the rootwindow of the specified screen.Changing Window AttributesTable 27 provides the subroutines for changing window attributes.Table 27. Changing Window AttributesSubroutineXChangeWindowAttributes()XSetWindowBackground()XSetWindowBackgroundPixmap()XSetWindowBorder()DescriptionChanges one or more window attributes.Sets the window’s background to a specifiedpixel.Sets the window’s background to a specifiedpixmap.Changes the window’s border to a specifiedpixel.Chapter 7. X Window System Interface 257


X Window System InterfaceTable 27. Changing Window Attributes (continued)SubroutineDescriptionXSetWindowBorderPixmap()Changes the window’s border tile.XTranslateCoordinates()Transforms coordinates between windows.Obtaining Window InformationTable 28 provides the subroutines for obtaining window information.Table 28. Obtaining Window InformationSubroutineXGetGeometry()XGetWindowAttributes()XQueryPointer()XQueryTree()DescriptionGets the current geometry of the specifieddrawable.Gets the current attributes for the specifiedwindow.Gets the pointer coordinates and the rootwindow.Obtains the IDs of the children and parentwindows.Obtaining Properties and AtomsTable 29 provides the subroutines for obtaining properties and atoms.Table 29. Properties and AtomsSubroutineXGetAtomName()XInternAtom()DescriptionGets a name for the specified atom ID.Gets an atom for the specified name.Manipulating Window PropertiesTable 30 provides the subroutines for manipulating the properties of windows.Table 30. Manipulating Window PropertiesSubroutineXChangeProperty()XDeleteProperty()XGetWindowProperty()XListProperties()XRotateWindowProperties()DescriptionChanges the property for the specifiedwindow.Deletes a property for the specified window.Gets the atom type and property format forthe window.Gets the specified window’s property list.Rotates the properties in a property array.Setting Window SelectionsTable 31 provides the subroutines for setting window selections.Table 31. Setting Window SelectionsSubroutineXConvertSelection()DescriptionConverts a selection.258 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System InterfaceTable 31. Setting Window Selections (continued)SubroutineDescriptionXGetSelectionOwner()Gets the selection owner.XSetSelectionOwner()Sets the selection owner.Manipulating ColormapsTable 32 provides the subroutines for manipulating color maps.Table 32. Manipulating ColormapsSubroutineXAllocStandardColormap()XCopyColormapAndFree()XCreateColormap()XFreeColormap()XQueryColor()XQueryColors()XSetWindowColormap()DescriptionAllocates an XStandardColormap structure.Creates a new colormap from a specifiedcolormap.Creates a colormap.Frees the specified colormap.Queries the RGB value for a specified pixel.Queries the RGB values for an array ofpixels.Sets the colormap of the specified window.Manipulating Color CellsTable 33 provides the subroutines for manipulating color cells.Table 33. Manipulating Color CellsSubroutineXAllocColor()XAllocColorCells()XAllocColorPlanes()XAllocNamedColor()XFreeColors()XLookupColor()XStoreColor()XStoreColors()XStoreNamedColor()DescriptionAllocates a read-only color cell.Allocates read/write color cells.Allocates read/write color resources.Allocates a read-only color cell by name.Frees colormap cells.Looks up a colorname.Stores an RGB value into a single colormapcell.Stores RGB values into colormap cells.Sets a pixel color to the named color.Creating and Freeing PixmapsTable 34 provides the subroutines for creating and freeing pixmaps.Table 34. Creating and Freeing PixmapsSubroutineXCreatePixmap()XFreePixmap()DescriptionCreates a pixmap of a specified size.Frees all storage associated with specifiedpixmap.Chapter 7. X Window System Interface 259


X Window System InterfaceManipulating Graphics ContextsTable 35 provides the subroutines for manipulating graphics contexts.Table 35. Manipulating Graphics ContextsSubroutineXChangeGC()XCopyGC()XCreateGC()XFreeGC()XGetGCValues()XGContextFromGC()XQueryBestTile()XQueryBestSize()XQueryBestStipple()XSetArcMode()XSetBackground()XSetClipmask()XSetClipOrigin()XSetClipRectangles()XSetDashes()XSetFillRule()XSetFillStyle()XSetFont()XSetForeground()XSetFunction()XSetGraphicsExposures()XSetLineAttributes()XSetPlaneMask()XSetState()XSetStipple()XSetSubwindowMode()XSetTile()XSetTSOrigin()DescriptionChanges the components in the specifiedGraphics Context (GC).Copies the components from a source GC toa destination GC.Creates a new GC.Frees the specified GC.Returns the GC values in the specifiedstructure.Obtains the GContext resource ID for GC.Gets the best fill tile shape.Gets the best size tile, stipple, or cursor.Gets the best stipple shape.Sets the arc mode of the specified GC.Sets the background of the specified GC.Sets the clip_mask of the specified GC to aspecified pixmap.Sets the clip origin of the specified GC.Sets the clip_mask of GC to a list ofrectangles.Sets the dashed line style components of aspecified GC.Sets the fill rule of the specified GC.Sets the fill style of the specified GC.Sets the current font of the specified GC.Sets the foreground of the specified GC.Sets display function in the specified GC.Sets the graphics-exposure flag of thespecified GC.Sets the line-drawing components of the GC.Sets the plane mask of the specified GC.Sets the foreground, background, planemask, and function in GC.Sets the stipple of the specified GC.Sets the subwindow mode of the specifiedGC.Sets the fill tile of the specified GC.Sets the tile or stipple origin of the specifiedGC.260 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Clearing and Copying AreasTable 36 provides the subroutines for clearing and copying areas.Table 36. Clearing and Copying AreasSubroutineXClearArea()XClearWindow()XCopyArea()XCopyPlane()X Window System InterfaceDescriptionClears a rectangular area of window.Clears the entire window.Copies the drawable area between drawablesof the same root and the same depth.Copies single bit-plane of the drawable.Drawing LinesTable 37 provides the subroutines for drawing lines.Table 37. Drawing LinesSubroutineXDraw()XDrawArc()XDrawArcs()XDrawFilled()XDrawLine()XDrawLines()XDrawPoint()XDrawPoints()XDrawRectangle()XDrawRectangles()XDrawSegments()DescriptionDraws an arbitrary polygon or curve that isdefined by the specified list of Vertexes asspecified in vlist.Draws a single arc in the drawable.Draws multiple arcs in a specified drawable.Draws arbitrary polygons or curves and thenfills them.Draws a single line between two points in adrawable.Draws multiple lines in the specifieddrawable.Draws a single point in the specifieddrawable.Draws multiple points in the specifieddrawable.Draws an outline of a single rectangle in thedrawable.Draws an outline of multiple rectangles inthe drawable.Draws multiple line segments in thespecified drawable.Filling AreasTable 38 provides the subroutines for filling areas.Table 38. Filling AreasSubroutineXFillArc()XFillArcs()XFillPolygon()DescriptionFills a single arc in drawable.Fills multiple arcs in drawable.Fills a polygon area in the drawable.Chapter 7. X Window System Interface 261


X Window System InterfaceTable 38. Filling Areas (continued)SubroutineXFillRectangle()XFillRectangles()DescriptionFills a single rectangular area in thedrawable.Fills multiple rectangular areas in thedrawable.Loading and Freeing FontsTable 39 provides the subroutines for loading and freeing fonts.Table 39. Loading and Freeing FontsSubroutineXFreeFont()XFreeFontInfo()XFreeFontNames()XFreeFontPath()XGetFontPath()XGetFontProperty()XListFontsWithInfo()XLoadFont()XLoadQueryFont()XListFonts()XQueryFont()XSetFontPath()XUnloadFont()DescriptionUnloads the font and frees the storage usedby the font.Frees the font information array.Frees a font name array.Frees data returned by XGetFontPath.Gets the current font search path.Gets the specified font property.Gets names and information about loadedfonts.Loads a font.Loads and queries font in one operation.Gets a list of available font names.Gets information about a loaded font.Sets the font search path.Unloads the specified font.Querying Character String SizesTable 40 provides the subroutines for querying the character size of a string.Table 40. Querying Character String SizesSubroutineXFreeStringList()XQueryTextExtents()XQueryTextExtents16()XTextExtents()XTextExtents16()XTextPropertyToStringList()DescriptionFrees the in-memory data associated with thespecified string list.Gets a 1-byte character string bounding boxfrom the server.Gets a 2-byte character string bounding boxfrom the server.Gets a bounding box of a 1-byte characterstring.Gets a bounding box of a 2-byte characterstring.Returns a list of strings representing theelements of the specified XTextPropertystructure.262 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System InterfaceTable 40. Querying Character String Sizes (continued)SubroutineDescriptionXTextWidth()Gets the width of an 8-bit character string.XTextWidth16()Gets the width of a 2-byte character string.Drawing TextTable 41 provides the subroutines for drawing text.Table 41. Drawing TextSubroutineXDrawImageString()XDrawImageString16()XDrawString()XDrawString16()XDrawText()XDrawText16()DescriptionDraws 8-bit image text in the specifieddrawable.Draws 2-byte image text in the specifieddrawable.Draws 8-bit text in the specified drawable.Draws 2-byte text in the specified drawable.Draws 8-bit complex text in the specifieddrawable.Draws 2-byte complex text in the specifieddrawable.Transferring ImagesTable 42 provides the subroutines for transferring images.Table 42. Transferring ImagesSubroutineXGetImage()XGetSubImage()XPutImage()DescriptionGets the image from the rectangle in thedrawable.Copies the rectangle on the display to image.Puts the image from memory into therectangle in the drawable.Manipulating CursorsTable 43 provides the subroutines for manipulating cursors.Table 43. Manipulating CursorsSubroutineXCreateFontCursor()XCreateGlyphCursor()XDefineCursor()XFreeCursor()XQueryBestCursor()XRecolorCursor()XUndefineCursor()DescriptionCreates a cursor from a standard font.Creates a cursor from font glyphs.Defines a cursor for a window.Frees a cursor.Gets useful cursor sizes.Changes the color of a cursor.Undefines a cursor for a window.Chapter 7. X Window System Interface 263


X Window System InterfaceHandling Window Manager FunctionsTable 44 provides the subroutines for handling the window manager functions.Table 44. Handling Window Manager FunctionsSubroutineXAddToSaveSet()XAllowEvents()XChangeActivePointerGrab()XChangePointerControl()XChangeSaveSet()XGetInputFocus()XGetPointerControl()XGrabButton()XGrabKey()XGrabKeyboard()XGrabPointer()XGrabServer()XInstallColormap()XKillClient()XListInstalledColormaps()XRemoveFromSaveSet()XReparentWindow()XSetCloseDownMode()XSetInputFocus()XUngrabButton()XUngrabKey()XUngrabKeyboard()XUngrabPointer()XUngrabServer()XUninstallColormap()XWarpPointer()DescriptionAdds a window to the client’s save-set.Allows events to be processed after a deviceis frozen.Changes the active pointer grab.Changes the interactive feel of the pointerdevice.Adds or removes a window from the client’ssave-set.Gets the current input focus.Gets the current pointer parameters.Grabs a mouse button.Grabs a single key of the keyboard.Grabs the keyboard.Grabs the pointer.Grabs the server.Installs a colormap.Removes a client.Gets a list of currently installed colormaps.Removes a window from the client’s save-set.Changes the parent of a window.Changes the close down mode.Sets the input focus.Ungrabs a mouse button.Ungrabs a key.Ungrabs the keyboard.Ungrabs the pointer.Ungrabs the server.Uninstalls a colormap.Moves the pointer to arbitrary point on thescreen.Manipulating Keyboard SettingsTable 45 provides the subroutines for manipulating keyboard settings.Table 45. Manipulating Keyboard SettingsSubroutineXAutoRepeatOff()XAutoRepeatOn()XBell()DescriptionTurns off the keyboard auto-repeat.Turns on the keyboard auto-repeat.Sets the volume of the bell.264 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Table 45. Manipulating Keyboard Settings (continued)SubroutineXChangeKeyboardControl()XChangeKeyboardMapping()XDeleteModifiermapEntry()XFreeModifiermap()XGetKeyboardControl()XGetKeyboardMapping()XGetModiferMapping()XGetPointerMapping()XInsertModifiermapEntry()XNewModifiermap()XQueryKeymap()XSetPointerMapping()XSetModifierMapping()X Window System InterfaceDescriptionChanges the keyboard settings.Changes the mapping of symbols tokeycodes.Deletes an entry from the XModifierKeymapstructure.Frees XModifierKeymap structure.Gets the current keyboard settings.Gets the mapping of symbols to keycodes.Gets keycodes to be modifiers.Gets the mapping of buttons on the pointer.Adds an entry to the XModifierKeymapstructure.Creates the XModifierKeymap structure.Gets the state of the keyboard keys.Sets the mapping of buttons on the pointer.Sets keycodes to be modifiers.Controlling the Screen SaverTable 46 provides the subroutines for controlling the screen saver.Table 46. Controlling the Screen SaverSubroutineXActivateScreenSaver()XForceScreenSaver()XGetScreenSaver()XResetScreenSaver()XSetScreenSaver()DescriptionActivates the screen saver.Turns the screen saver on or off.Gets the current screen saver settings.Resets the screen saver.Sets the screen saver.Manipulating Hosts and Access ControlTable 47 provides the subroutines for manipulating hosts and toggling the accesscontrol.Table 47. Manipulating Hosts and Access ControlSubroutineXDisableAccessControl()XEnableAccessControl()XListHosts()XSetAccessControl()DescriptionDisables access control.Enables access control.Gets the list of hosts.Changes access control.Chapter 7. X Window System Interface 265


X Window System InterfaceHandling EventsTable 48 provides the subroutines for handling events.Table 48. Handling EventsSubroutineXCheckIfEvent()XCheckMaskEvent()XCheckTypedEvent()XCheckTypedWindowEvent()XCheckWindowEvent()XEventsQueued()XFlush()XGetMotionEvents()XIfEvent()XMaskEvent()XNextEvent()XPeekEvent()XPeekIfEvent()XPending()XPutBackEvent()XSelectInput()XSendEvent()XSync()XWindowEvent()DescriptionChecks event queue for the specified eventwithout blocking.Removes the next event that matches aspecified mask without blocking.Gets the next event that matches event type.Gets the next event for the specified window.Removes the next event that matches thespecified window and mask withoutblocking.Checks the number of events in the eventqueue.Flushes the output buffer.Gets the motion history for the specifiedwindow.Checks the event queue for the specifiedevent and removes it.Removes the next event that matches aspecified mask.Gets the next event and removes it from thequeue.Peeks at the event queue.Checks the event queue for the specifiedevent.Returns the number of events that arepending.Pushes the event back to the top of the eventqueue.Selects events to be reported to the client.Sends an event to a specified window.Flushes the output buffer and waits until allrequests are completed.Removes the next event that matches thespecified window and mask.Enabling and Disabling SynchronizationTable 49 provides the subroutines for toggling synchronization.Table 49. Enabling and Disabling SynchronizationSubroutineXSetAfterFunction()XSynchronize()DescriptionSets the previous after function.Enables or disables synchronization.266 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Using Default Error HandlingTable 50 provides the subroutines for using the default error handling.Table 50. Using Default Error HandlingSubroutineXDisplayName()XGetErrorText()XGetErrorDatabaseText()XSetErrorHandler()XSetIOErrorHandler()DescriptionX Window System InterfaceGets the name of the display currently beingused.Gets the error text for the specified errorcode.Gets the error text from the error database.Sets the error handler.Sets the error handler for unrecoverable I/Oerrors.Communicating with Window ManagersTable 51 provides the subroutines for communicating with window managers.Table 51. Communicating with Window ManagersSubroutineXAllocClassHints()XAllocIconSize()XAllocSizeHints()XAllocWMHints()XGetClassHint()XFetchName()XGetCommand()XGetIconName()XGetIconSizes()XGetNormalHints()XGetRGBColormaps()XGetSizeHints()XGetStandardColormap()XGetTextProperty()XGetTransientForHint()XGetWMClientMachine()XGetWMColormapWindows()XGetWMHints()XGetWMName()XGetWMIconName()DescriptionAllocates storage for an XClassHint structure.Allocates storage for an XIconSize structure.Allocates storage for an XSizeHints structure.Allocates storage for an XWMHints structure.Gets the class of a window.Gets the name of a window.Gets a window’s WM_COMMAND property.Gets the name of an icon window.Gets the values of icon size atom.Gets size hints for window in normal state.Gets colormap associated with specifiedatom.Gets the values of type WM_SIZE_HINTSproperties.Gets colormap associated with specifiedatom.Gets a window’s property of type TEXT.Gets WM_TRANSIENT_FOR property forwindow.Gets the value of a window’sWM_CLIENT_MACHINE property.Gets the value of a window’sWM_COLORMAP_WINDOWS property.Gets the value of the window manager’shints atom.Gets the value of the WM_NAME property.Gets the value of the WM_ICON_NAMEproperty.Chapter 7. X Window System Interface 267


X Window System InterfaceTable 51. Communicating with Window Managers (continued)SubroutineXGetWMNormalHints()XGetWMProtocols()XGetWMSizeHints()XGetZoomHints()XSetCommand()XSetClassHint()XSetIconName()XSetIconSizes()XSetNormalHints()XSetRGBColormaps()XSetSizeHints()XSetStandardColormap()XSetStandardProperties()XSetTextProperty()XSetTransientForHint()XSetWMClientMachine()XSetWMColormapWindows()XSetWMHints()XSetWMIconName()XSetWMName()XSetWMNormalHints()XSetWMProperties()XSetWMProtocols()XSetWMSizeHints()XSetZoomHints()XStoreName()DescriptionGets the value of the window manager’shints atom.Gets the value of a window’sWM_PROTOCOLS property.Gets the values of type WM_SIZE_HINTSproperties.Gets values of the zoom hints atom.Sets the value of the command atom.Sets the class of a window.Assigns a name to an icon window.Sets the values of icon size atom.Sets size hints for a window in normal state.Sets the colormap associated with thespecified atom.Sets the values of the type WM_SIZE_HINTSproperties.Sets the colormap associated with thespecified atom.Specifies a minimum set of properties.Sets a window’s properties of type TEXT.Sets WM_TRANSIENT_FOR property forwindow.Sets a window’s WM_CLIENT_MACHINEproperty.Sets a window’sWM_COLORMAP_WINDOWS property.Sets the value of the window manager’shints atom.Sets the value of the WM_ICON_NAMEproperty.Sets the value of the WM_NAME property.Sets the value of the window manager’shints atom.Sets the values of properties for a windowmanager.Sets the value of the WM_PROTOCOLSproperty.Sets the values of type WM_SIZE_HINTSproperties.Sets the values of the zoom hints atom.Assigns a name to a window.Manipulating Keyboard Event FunctionsTable 52 on page 269 provides the subroutines for manipulating the functions ofkeyboard events.268 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System InterfaceTable 52. Keyboard Event FunctionsSubroutineXKeycodeToKeysym()XKeysymToKeycode()XKeysymToString()XLookupKeysym()XLookupMapping()XLookupString()XRebindCode()XRebindKeysym()XRefreshKeyboardMapping()XStringToKeysym()XUseKeymap()XGeometry()XGetDefault()XParseColor()XParseGeometry()XWMGeometry()DescriptionConverts a keycode to a keysym value.Converts a keysym value to keycode.Converts a keysym value to keysym name.Translates a keyboard event into a keysymvalue.Gets the mapping of a keyboard event froma keymap file.Translates the keyboard event into acharacter string.Changes the keyboard mapping in thekeymap file.Maps the character string to a specifiedkeysym and modifiers.Refreshes the stored modifier and keymapinformation.Converts the keysym name to the keysymvalue.Changes the keymap files.Parses window geometry given padding andfont values.Gets the default window options.Obtains RGB values from color name.Parses standard window geometry options.Obtains a window’s geometry information.Manipulating RegionsTable 53 provides the subroutines for manipulating regions.Table 53. Manipulating RegionsSubroutineXClipBox()XCreateRegion()XEmptyRegion()XEqualRegion()XIntersectRegion()XDestroyRegion()XOffsetRegion()XPointInRegion()XPolygonRegion()DescriptionGenerates the smallest enclosing rectangle inthe region.Creates a new empty region.Determines whether a specified region isempty.Determines whether two regions are thesame.Computes the intersection of two regions.Frees storage associated with the specifiedregion.Moves the specified region by the specifiedamount.Determines if a point lies in the specifiedregion.Generates a region from points.Chapter 7. X Window System Interface 269


X Window System InterfaceTable 53. Manipulating Regions (continued)SubroutineXRectInRegion()XSetRegion()XShrinkRegion()XSubtractRegion()XUnionRegion()XUnionRectWithRegion()XXorRegion()DescriptionDetermines if a rectangle lies in the specifiedregion.Sets the GC to the specified region.Reduces the specified region by a specifiedamount.Subtracts two regions.Computes the union of two regions.Creates a union of source region andrectangle.Gets the difference between the union andintersection of regions.Using Cut and Paste BuffersTable 54 provides the subroutines for using cut and paste buffers.Table 54. Using Cut and Paste BuffersSubroutineXFetchBuffer()XFetchBytes()XRotateBuffers()XStoreBuffer()XStoreBytes()DescriptionGets data from a specified cut buffer.Gets data from the first cut buffer.Rotates the cut buffers.Stores data in a specified cut buffer.Stores data in first cut buffer.Querying Visual TypesTable 55 provides the subroutines for querying visual types.Table 55. Querying Visual TypesSubroutineXGetVisualInfo()XListDepths()XListPixmapFormats()XMatchVisualInfo()XPixmapFormatValues()DescriptionGets a list of visual information structures.Determines the number of depths that areavailable on a given screen.Gets the pixmap format information for agiven display.Gets visual information matching screendepth and class.Gets the pixmap format information for agiven display.270 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Manipulating ImagesTable 56 provides the subroutines for manipulating images.Table 56. Manipulating ImagesSubroutineXAddPixel()XCreateImage()XDestroyImage()XGetPixel()XPutPixel()XSubImage()DescriptionX Window System InterfaceIncreases each pixel in a pixmap by aconstant value.Allocates memory for the XImage structure.Frees memory for the XImage structure.Gets a pixel value in an image.Sets a pixel value in an image.Creates an image that is a subsection of aspecified image.Manipulating BitmapsTable 57 provides the subroutines for manipulating bitmaps.Table 57. Manipulating BitmapsSubroutineXCreateBitmapFromData()XCreatePixmapFromBitmapData()XDeleteContext()XFindContext()XReadBitmapFile()XSaveContext()XUniqueContext()XWriteBitmapFile()DescriptionIncludes a bitmap in the C program.Creates a pixmap using bitmap data.Deletes data associated with the window andcontext type.Gets data associated with the window andcontext type.Reads in a bitmap from a file.Stores data associated with the window andcontext type.Allocates a new context.Writes out a bitmap to a file.Using the Resource ManagerTable 58 provides the subroutines for using the resource manager.Table 58. Using the Resource ManagerSubroutineXpermalloc()XrmDestroyDatabase()XrmGetFileDatabase()XrmGetResource()XrmGetStringDatabase()XrmInitialize()XrmMergeDatabases()XrmParseCommand()XrmPutFileDatabase()DescriptionAllocates memory that is never freed.Destroys a resource database and frees itsallocated memory.Creates a database from a specified file.Retrieves a resource from a database.Creates a database from a specified string.Initializes the resource manager.Merges two databases.Stores command options in a database.Copies the database into a specified file.Chapter 7. X Window System Interface 271


X Window System InterfaceTable 58. Using the Resource Manager (continued)SubroutineXrmPutLineResource()XrmPutResource()XrmPutStringResource()XrmQGetResource()XrmQGetSearchList()XrmQGetSearchResource()XrmQPutResource()XrmQPutStringResource()XrmQuarkToString()XrmStringToQuark()XrmStringToQuarkList()XrmStringToBindingQuarkList()XrmUniqueQuark()DescriptionStores a single resource entry in a database.Stores a resource in a database.Stores string resource in a database.Retrieves a quark from a database.Gets a resource search list of database levels.Gets a quark search list of database levels.Stores binding and quarks in a database.Stores string binding and quarks in adatabase.Converts a quark to a character string.Converts a character string to a quark.Converts character strings to a quark list.Converts strings to bindings and quarks.Allocates a new quark.Manipulating Display FunctionsTable 59 provides the subroutines for manipulating the display functions.Table 59. Display FunctionsSubroutineAllPlanes() XAllPlanes()BitMapBitOrder() XBitMapOrder()BitMapPad() XBitMapPad()BitMapUnit() XBitMapUnit()BlackPixel() XBlackPixel()BlackPixelOfScreen() XBlackPixelOfScreen()CellsOfScreen() XCellsOfScreen()ConnectionNumber() XConnectionNumber()CreatePixmapCursor()XCreatePixmapCursor()CreateWindow() XCreateWindow()DefaultColormap() XDefaultColormap()DefaultColormapOfScreen()XDefaultColormapOfScreenDefaultDepth() XDefaultDepth()DescriptionReturns all bits suitable for use in planeargument.Returns either the most or least significantbit in each bitmap unit.Returns the multiple of bits padding eachscanline.Returns the size of a bitmap’s unit in bits.Returns the black pixel value of the screenspecified.Returns the black pixel value of the screenspecified.Returns the number of colormap cells.Returns the file descriptor of the connection.Creates a pixmap of a specified size.Creates an unmapped subwindow for aspecified parent window.Returns a default colormap ID for allocationon the screen specified.Returns the default colormap ID of thescreen specified.Returns the depth of the default rootwindow.272 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System InterfaceTable 59. Display Functions (continued)SubroutineDefaultDepthOfScreen()XDefaultDepthOfScreen()DefaultGC() XDefaultGC()DefaultGCOfScreen() XDefaultGCOfScreen()DefaultScreen() XDefaultScreen()DefaultScreenofDisplay()XDefaultScreenofDisplay()DefaultRootWindow()XDefaultRootWindow()DefaultVisual() XDefaultVisual()DefaultVisualOfScreen()XDefaultVisualOfScreen()DisplayCells() XDisplayCells()DisplayHeight() XDisplayHeight()DisplayHeightMM() XDisplayHeightMM()DisplayOfScreen() XDisplayOfScreen()DisplayPlanes() XDisplayPlanes()DisplayString() XDisplayString()DisplayWidth() XDisplayWidth()DisplayWidthMM() XDisplayWidthMM()DoesBackingStore() XDoesBackingStore()DoesSaveUnders() XDoesSaveUnders()EventMaskOfScreen() XEventMaskOfScreen()HeightMMOfScreen() XHeightMMOfScreen()HeightOfScreen() XHeightOfScreen()ImageByteOrder() XImageByteOrder()IsCursorKey()IsFunctionKey()IsKeypadKey()DescriptionReturns the default depth of the screenspecified.Returns the default GC of the default rootwindow.Returns the default GC of the screenspecified.Obtains the default screen referenced in theXOpenDisplay routine.Returns the default screen of the displayspecified.Obtains the root window for the defaultscreen specified.Returns the default visual type of the screenspecified.Returns the default visual type of the screenspecified.Displays the number of entries in the defaultcolormap.Displays the height of the screen in pixels.Displays the height of the screen inmillimeters.Displays the type of screen specified.Displays the depth (number of planes) of theroot window of the screen specified.Displays the string passed to XOpenDisplaywhen the current display was opened.Displays the width of the specified screen inpixels.Displays the width of the specified screen inmillimeters.Indicates whether the specified screensupports backing stores.Indicates whether the specified screensupports save unders.Returns the initial root event mask for aspecified screen.Returns the height of a specified screen inmillimeters.Returns the height of a specified screen inpixels.Specifies the required byte order for eachscanline unit of an image.Returns TRUE if keysym is on cursor key.Returns TRUE if keysym is on function keys.Returns TRUE if keysym is on keypad.Chapter 7. X Window System Interface 273


X Window System InterfaceTable 59. Display Functions (continued)SubroutineIsMiscFunctionKey()IsModifierKey()IsPFKey()LastKnownRequestProcessed()XLastKnownRequestProcessed()MaxCmapsOfScreen() XMaxCmapsOfScreen()MinCmapsOfScreen() XMinCmapsOfScreen()NextRequest() XNextRequest()PlanesOfScreen() XPlanesOfScreen()ProtocolRevision() XProtocolRevision()ProtocolVersion() XProtocolVersion()QLength() XQLength()RootWindow() XRootWindow()RootWindowOfScreen()XRootWindowOfScreen()ScreenCount() XScreenCount()XScreenNumberOfScreen()ScreenOfDisplay() XScreenOfDisplay()ServerVendor() XServerVendor()VendorRelease() XVendorRelease()WhitePixel() XWhitePixel()WhitePixelOfScreen() XWhitePixelOfScreen()WidthMMOfScreen() XWidthMMOfScreen()WidthOfScreen() XWidthOfScreen()DescriptionReturns TRUE if keysym is on miscellaneousfunction keys.Returns TRUE if keysym is on modifier keys.Returns TRUE if keysym is on PF keys.Extracts the full serial number of the lastknown request processed by the X server.Returns the maximum number of colormapssupported by the specified screen.Returns the minimum number of colormapssupported by the specified screen.Extracts the full serial number to be used forthe next request to be processed by the XServer.Returns the depth (number of planes) in aspecified screen.Returns the minor protocol revision number(zero) of the X server associated with thedisplay.Returns the major version number (11) of theprotocol associated with the display.Returns the length of the event queue for thedisplay.Returns the root window of the currentscreen.Returns the root window of the specifiedscreen.Returns the number of screens available.Returns the screen index number of thespecified screen.Returns the pointer to the screen of thedisplay specified.Returns the pointer to a null-determinedstring that identifies the owner of the Xserver implementation.Returns the number related to the vendor’srelease of the X server.Returns the white pixel value for the currentscreen.Returns the white pixel value of the specifiedscreen.Returns the width of the specified screen inmillimeters.Returns the width of the specified screen inpixels.274 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Extension RoutinesTable 60 lists the X Window System Extension Subroutines.X Window System InterfaceTable 60. Extension RoutinesSubroutineXAllocID()XESetCloseDisplay()XESetCopyGC()XESetCreateFont()XESetCreateGC()XESetError()XESetErrorString()XESetEventToWire()XESetFreeFont()XESetFreeGC()XESetWireToEvent()XFreeExtensionList()XListExtensions()XQueryExtension()DescriptionReturns a resource ID that can be used whencreating new resources.Defines a procedure to call whenXCloseDisplay is called.Defines a procedure to call when a GC iscopied.Defines a procedure to call whenXLoadQueryFont is called.Defines a procedure to call when an new GCis created.Suppresses the call to an external errorhandling routine and defines an alternativeroutine for error handling.Defines a procedure to call when an I/Oerror is detected.Defines a procedure to call when an eventmust be converted from the host to wireformat.Defines a procedure to call when XFreeFontis called.Defines a procedure to call when a GC isfreed.Defines a procedure to call when an event isconverted from the wire to the host format.Frees memory allocated by XListExtensions.Returns a list of all extensions supported bythe server.Indicates whether named extension ispresent.MIT Extensions to XTable 61 lists the routines that allow an application to use these extensions:Table 61. MIT Extensions to XSubroutineXShapeQueryExtensionXShapeQueryVersionXShapeCombineRegionXShapeCombineRectanglesDescriptionQueries to see if the server supports theSHAPE extension.Checks the version number of the serverSHAPE extension.Converts the specified region into a list ofrectangles and calls XShapeRectangles.Performs a CombineRectangles operation.Chapter 7. X Window System Interface 275


X Window System InterfaceTable 61. MIT Extensions to X (continued)SubroutineXShapeCombineMaskXShapeCombineShapeXShapeOffsetShapeXShapeQueryExtentsXShapeSelectInputXShapeInputSelectedXShapeGetRectanglesXMITMiscQueryExtensionXMITMiscSetBugModeXMITMiscGetBugModeXmbufQueryExtensionXmbufGetVersionXmbufCreateBuffersXmbufDestroyBuffersXmbufDisplayBuffersXmbufGetWindowAttributesXmbufChangeWindowAttributesXmbufGetBufferAttributesXmbufChangeBufferAttributesXmbufGetScreenInfoXmbufCreateStereoWindowDescriptionPerforms a CombineMask operation.Performs a CombineShape operation.Performs an OffsetShape operation.Sets the extents of the bounding and clipshapes.Selects Input Events.Returns the current input mask for extensionevents on the specified window.Gets a list of rectangles describing the regionspecified.Queries to see if the server supports theMITMISC extension.Sets the compatibility mode switch.Queries the compatibility mode switch.Queries to see if the server supports theMULTIBUF extension.Gets the version number of the extension.Requests that multiple buffers be created.Requests that the buffers be destroyed.Displays the indicated buffers.Gets the multibuffering attributes.Sets the multibuffering attributes.Gets the attributes for the indicated buffer.Sets the attributes for the indicated buffer.Gets the parameters controlling how monoand stereo windows may be created on theindicated screen.Creates a stereo window.Associate Table FunctionsTable 62 lists the Associate Table functions.Table 62. Associate Table FunctionsSubroutineXCreateAssocTable()XDeleteAssoc()XDestroyAssocTable()XLookUpAssoc()XMakeAssoc()DescriptionReturns a pointer to the newly createdassociate table.Deletes an entry from the specified associatetable.Frees memory allocated to the specifiedassociate table.Obtains data from the specified associatetable.Creates an entry in the specified associatetable.276 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System InterfaceMiscellaneous Utility RoutinesTable 63 lists the Miscellaneous Utility routines.Table 63. Miscellaneous Utility RoutinesSubroutineXctCreate()XctFree()XctNextItem()XctReset()XmuAddCloseDisplayHook()XmuAddInitializer()XmuAllStandardColormaps()XmuCallInitializers()XmuClientWindow()XmuCompareISOLatin1()XmuConvertStandardSelection()XmuCopyISOLatin1Lowered()XmuCopyISOLatin1Uppered()XmuCreateColormap()XmuCreatePixmapFromBitmap()XmuCreateStippledPixmap()XmuCursorNameToIndex()XmuCvtFunctionToCallback()XmuCvtStringToBackingStore()XmuCvtStringToBitmap()XmuCvtStringToCursor()XmuCvtStringToJustify()XmuCvtStringToLong()DescriptionCreates an XctData structure for parsing aCompound Text string.Frees all data associated with the XctDatastructure.Parses the next item from the Compound Textstring.Resets the XctData structure to reparse theCompound Text string.Adds a callback for the given display.Registers a procedure, to be invoked the firsttime XmuCallInitializers is called on a givenapplication context.Creates all of the appropriate standardcolormaps.Calls each of the procedures that have beenregistered with XmuAddInitializer.Finds a window, at or below the specifiedwindow.Compares two strings, ignoring casedifferences.Converts many standard selections.Copies a string, changing all Latin-1uppercase letters to lowercase.Copies a string, changing all Latin-1lowercase letters to uppercase.Creates a colormap.Creates a pixmap of the specified width,height, and depth.Creates a two pixel by one pixel stippledpixmap of specified depth on the specifiedscreen.Returns the index in the standard cursor fontfor the name of a standard cursor.Converts a callback procedure to a callbacklist containing that procedure.Converts a string to a backing-store integer.Creates a bitmap suitable for windowmanager icons.Converts a string to a Cursor.Converts a string to an XtJustify enumerationvalue.Converts a string to an integer of type long.Chapter 7. X Window System Interface 277


X Window System InterfaceTable 63. Miscellaneous Utility Routines (continued)SubroutineXmuCvtStringToOrientation()XmuCvtStringToShapeStyle()XmuCvtStringToWidget()XmuDeleteStandardColormap()XmuDQAddDisplay()XmuDQCreate()XmuDQDestroy()XmuDQLookupDisplay()XmuDQNDisplays()XmuDQRemoveDisplay()XmuDrawLogo()XmuDrawRoundedRectangle()XmuFillRoundedRectangle()XmuGetAtomName()XmuGetColormapAllocation()XmuGetHostname()XmuInternAtom()XmuInternStrings()XmuLocateBitmapFile()XmuLookupAPL()XmuLookupArabic()XmuLookupCloseDisplayHook()XmuLookupCyrillic()XmuLookupGreek()XmuLookupHebrew()DescriptionConverts a string to an XtOrientationenumeration value.Converts a string to an integer shape style.Converts a string to an immediate childwidget of the parent widget passed as anargument.Removes the specified property from thespecified screen.Adds the specified display to the queue.Creates and returns an emptyXmuDisplayQueue.Releases all memory associated with thespecified queue.Returns the queue entry for the specifieddisplay.Returns the number of displays in thespecified queue.Removes the specified display from thespecified queue.Draws the official X Window System logo.Draws a rounded rectangle.Draws a filled rounded rectangle.Returns the name of an Atom.Determines the best allocation of reds,greens, and blues in a standard colormap.Returns the host name.Caches the Atom value for one or moredisplays.Converts a list of atom names into Atomvalues.Reads a file in standard bitmap file format.Maps a key event to an APL string. Thisfunction is similar to XLookupString.Maps a key event to a Latin/Arabic (ISO8859-6) string. This function is similar toXLookupString.Determines if a callback is installed.Maps a key event to a Latin/Cyrillic (ISO8859-5) string. This function is similar toXLookupString, except that it maps aMaps a key event to a Latin/Greek (ISO8859-7) string. This function is similar toXLookupString.Maps a key event to a Latin/Hebrew (ISO8859-8) string. This function is similar toXLookupString.278 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Table 63. Miscellaneous Utility Routines (continued)SubroutineXmuLookupJISX0201()XmuLookupKana()XmuLookupLatin1()XmuLookupLatin2()XmuLookupLatin3()XmuLookupLatin4()XmuLookupStandardColormap()XmuLookupString()XmuMakeAtom()XmuNameOfAtom()XmuPrintDefaultErrorMessage()XmuReadBitmapData()XmuReadBitmapDataFromFile()XmuReleaseStippledPixmap()XmuRemoveCloseDisplayHook()XmuReshapeWidget()XmuScreenOfWindow()XmuSimpleErrorHandler()XmuStandardColormap()XmuUpdateMapHints()XmuVisualStandardColormaps()DescriptionX Window System InterfaceMaps a key event to a string in the JISX0201-1976 encoding. This function is similarto XLookupString.Maps a key event to a string in the JISX0201-1976 encoding. This function is similarto XLookupString.This function is identical to XLookupString.Maps a key event to a Latin-2 (ISO 8859-2)string. This function is similar toXLookupString.Maps a key event to a Latin-3 (ISO 8859-3)string. This function is similar toXLookupString.Maps a key event to a Latin-4 (ISO 8859-4)string. This function is similar toXLookupString.Creates or replaces a standard colormap ifone does not currently exist.Maps a key event into a specific key symbolset.Creates and initializes an opaque object.Returns the name of an AtomPtr.Prints an error message, equivalent to Xlib’sdefault error message.Reads a standard bitmap file description.Reads a standard bitmap file descriptionfrom the specified file.Frees a pixmap created withXmuCreateStippledPixmap.Deletes a callback that has been added withXmuAddCloseDisplayHook.Reshapes the specified widget, using theShape extension.Returns the screen on which the specifiedwindow was created.A simple error handler for Xlib errorconditions.Creates a standard colormap for the givenscreen.Clears the PPosition and PSize flags and setsthe USPosition and USSize flags.Creates all of the appropriate standardcolormaps for a given visual.Chapter 7. X Window System Interface 279


X Window System InterfaceX Authorization RoutinesTable 64 lists the X Authorization routines.Table 64. Authorization Data RoutinesSubroutineXauFileName()XauReadAuth()XuWriteAuth()XauGetAuthByAddr()XauLockAuth()XauUnlockAuth()XauDisposeAuth()DescriptionGenerates the default authorization filename.Reads the next entry from the authfile.Writes an authorization entry to the authfile.Searches for an authorization entry.Does the work necessary to synchronouslyupdate an authorization file.Undoes the work of XauLockAuth.Frees storage allocated to hold anauthorization entry.X Intrinsics RoutinesTable 65 provides the X Intrinsics Routines.Table 65. X Intrinsics RoutinesRoutineCompositeClassPartInitializeCompositeDeleteChildCompositeDestroyCompositeInitializeCompositeInsertChildRemoveCallbackXrmCompileResourceListXtAddActionsXtAddCallbackXtAddCallbacksXtAddConverterXtAddEventHandlerXtAddExposureToRegionXtAddGrabDescriptionInitializes the CompositeClassPart of aComposite Widget.Deletes a child widget from a CompositeWidget.Destroys a composite widget.Initializes a Composite Widget structure.Inserts a child widget in a CompositeWidget.Removes a callback procedure from acallback list.Compiles an XtResourceList into anXrmResourceList.Declares an action table and registers it withthe translation managerAdds a callback procedure to the callback listof the specified widget.Adds a list of callback procedures to thecallback list of specified widget.Adds a new converter.Registers an event handler procedure withthe dispatch mechanism when an eventmatching the mask occurs on the specifiedwidget.Computes the union of the rectangle definedby the specified exposure event and region.Redirects user input to a model widget.280 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System InterfaceTable 65. X Intrinsics Routines (continued)RoutineXtAddInputXtAddRawEventHandlerXtAddTimeOutXtAddWorkProcXtAppAddActionHookXtAppAddActionsXtAppAddConverterXtAppAddInputXtAppAddTimeOutXtAppAddWorkProcXtAppCreateShellXtAppErrorXtAppErrorMsgXtAppGetErrorDatabaseXtAppGetErrorDatabaseTextXtAppGetSelectionTimeoutXtAppInitializeXtAppMainLoopXtAppNextEventXtAppPeekEventXtAppPendingXtAppProcessEventXtAppReleaseCacheRefsDescriptionRegisters a new source of events.Registers an event handler procedure withthe dispatch mechanism without causing theserver to select for that event.Creates a timeout value in the defaultapplication context and returns an identifierfor it.Registers a work procedure in the defaultapplication context.Adds an actionhook procedure to anapplication context.Declares an action table and registers it withthe translation manager.Registers a new converter.Registers a new file as an input source for aspecified application.Creates a timeout value and returns anidentifier for it.Registers a work procedure for a specifiedprocedure.Creates a top-level widget that is the root ofa widget tree.Calls the installed fatal error procedure.Calls the high-level error handler.Obtains the error database and merges itwith an application or widget-specifieddatabase.Obtains the error database text for an erroror warning for an error message handler.Gets and returns the current selectiontimeout (ms) value.A convenience routine for initializing thetoolkit.Processes input by calling XtAppNextEventand XtDispatchEvent.Returns the value from the top of a specifiedapplication input queue.Returns the value from the top of a specifiedapplication input queue without removinginput from queue.Determines if the input queue has any eventsfor a specified application.Processes applications that require directcontrol of the processing for different typesof input.Decrements the reference count for theconversion entries identified by the refsargument.Chapter 7. X Window System Interface 281


X Window System InterfaceTable 65. X Intrinsics Routines (continued)RoutineXtAppSetErrorHandlerXtAppSetErrorMsgHandlerXtAppSetFallbackResourcesXtAppSetSelectionTimeoutXtAppSetTypeConverterXtAppSetWarningHandlerXtAppSetWarningMsgHandlerXtAppWarningXtAppWarningMsgXtAugmentTranslationsXtBuildEventMaskXtCallAcceptFocusXtCallActionProcXtCallbackExclusiveXtCallbackNoneXtCallbackNonexclusiveXtCallbackPopdownXtCallbackReleaseCacheRefXtCallbackReleaseCacheRefListXtCallCallbackListXtCallCallbacksDescriptionRegisters a procedure to call on fatal errorconditions. The default error handler printsthe message to standard error.Registers a procedure to call on fatal errorconditions. The default error handlerconstructs a string from the error resourcedatabase.Sets the fallback resource list that will beloaded at display initialization time.Sets the Intrinsics selection time-out value.Registers the specified type converter anddestructor in all application contexts createdby the calling process.Registers a procedure to call on nonfatalerror conditions. The default warninghandler prints the message to standard error.Registers a procedure to call on nonfatalerror conditions. The default warninghandler constructs a string from errorresource database.Calls the installed nonfatal error procedure.Calls the installed high-level warninghandler.Merges new translations into an existingwidget translation table.Retrieves the event mask for a specifiedwidget.Calls the accept_focus procedure for thespecified widget.Searches for the named action routine and, iffound, calls it.Calls customized code for callbacks to createpop-up shell.Calls customized code for callbacks to createpop-up shell.Calls customized code for callbacks to createpop-up shell.Pops down a shell that was mapped bycallback functions.A callback that can be added to a callbacklist to release a previously returnedXtCacheRef value.A callback that can be added to a callbacklist to release a list of previously returnedXtCacheRef value.Calls all callbacks on a callback list.Executes the callback procedures in a widgetcallback list.282 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System InterfaceTable 65. X Intrinsics Routines (continued)RoutineXtCallConverterXtCallocXtClassXtCloseDisplayXtConfigureWidgetXtConvertXtConvertAndStoreXtConvertCaseXtCopyAncestorSensitiveXtCopyDefaultColormapXtCopyDefaultDepthXtCopyFromParentXtCopyScreenXtCreateApplicationContextXtCreateApplicationShellXtCreateManagedWidgetXtCreatePopupShellXtCreateWidgetXtCreateWindowXtDatabaseXtDestroyApplicationContextXtDestroyGCXtDestroyWidgetXtDirectConvertXtDisownSelectionXtDispatchEventDescriptionLooks up the specified type converter in theapplication context and invokes theconversion routine.Allocates and initializes an array.Obtains the class of a widget and returns apointer to the widget class structure.Closes a display and removes it from anapplication context.Moves and resizes the sibling widget of thechild making the geometry request.Invokes resource conversions.Looks up the type converter registered toconvert from_type to to_type and then callsXtCallConverter.Determines upper and lowercase equivalentsfor a KeySym.Copies the sensitive value from a widgetrecord.Copies the default colormap from a widgetrecord.Copies the default depth from a widgetrecord.Copies the parent from a widget record.Copies the screen from a widget record.Creates an opaque type application context.Creates an application shell widget by callingXtAppCreateShell.Creates and manages a child widget in asingle procedure.Creates a pop-up shell.Creates an instance of a widget.Calls XcreateWindow with the widgetstructure and parameter.Obtains the resource database for a particulardisplay.Destroys an application context.Deallocates graphics context when it is nolonger needed.Destroys a widget instance.Invokes resource conversion.Informs the Intrinsics selection mechanismthat the specified widget is to lose ownershipof the selection.Receives X events and calls appropriate eventhandlers.Chapter 7. X Window System Interface 283


X Window System InterfaceTable 65. X Intrinsics Routines (continued)RoutineXtDisplayXtDisplayInitializeXtDisplayOfObjectXtDisplayStringConversionWarningXtDisplayToApplicationContextXtErrorXtErrorMsgXtFindFileXtFreeXtGetActionKeysymXtGetApplicationNameAndClassXtGetApplicationResourcesXtGetConstraintResourceListXtGetErrorDatabaseXtGetErrorDatabaseTextXtGetGCXtGetKeysymTableXtGetMultiClickTimeXtGetResourceListXtGetSelectionRequestXtGetSelectionTimeoutXtGetSelectionValueXtGetSelectionValueIncrementalXtGetSelectionValuesDescriptionReturns the display pointer for the specifiedwidget.Initializes a display and adds it to anapplication context.Returns the display pointer for the specifiedwidget.Issues a warning message for conversionroutines.Retrieves the application context associatedwith a Display.Calls the installed fatal error procedure.A low-level error and warning handlerprocedure type.Searches for a file using substitutions in apath list.Frees an allocated block of storage.Retrieves the KeySym and modifiers thatmatched the final event specification in atranslation table entry.Returns the application name and class aspassed to XtDisplayInitializeRetrieves resources that are not specific to awidget, but apply to the overall application.Returns the constraint resource list for aparticular widget.Obtains the error database and returns theaddress of the error database.Obtains the error database text for an erroror warning.Returns a read-only sharable GC.Returns a pointer to the KeySym to KeyCodemapping table for a particular display.Returns the multi-click time setting.Obtains the resource list structure for aparticular class.Retrieves the SelectionRequest event whichtriggered the convert_selection procedure.Obtains the current selection timeout.Obtains the selection value in a single, logicalunit.Obtains the selection value using incrementaltransfers.Takes a list of target types and client dataand obtains the current value of the selectionconverted to each of the targets.284 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System InterfaceTable 65. X Intrinsics Routines (continued)RoutineXtGetSelectionValuesIncrementalXtGetSubresourcesXtGetSubvaluesXtGetValuesXtGrabButtonXtGrabKeyXtGrabKeyboardXtGrabPointerXtHasCallbacksXtInitializeXtInitializeWidgetClassXtInsertEventHandlerXtInsertRawEventHandlerXtInstallAcceleratorsXtInstallAllAcceleratorsXtIsApplicationShellXtIsCompositeXtIsConstraintXtIsManagedXtIsObjectXtIsOverrideShellXtIsRealizedXtIsRectObjXtIsSensitiveDescriptionA function similar toXtGetSelectionValueIncremental except that ittakes a list of targets and client_data.Obtains resources other than widgets.Retrieves the current value of a non-widgetresource data associated with a widgetinstance.Retrieves the current value of a resourceassociated with a widget instance.Passively grabs a single pointer button.Passively grabs a single key of the keyboard.Actively grabs the keyboard.Actively grabs the pointer.Finds the status of a specified widgetcallback list.Initializes the toolkit, application, and shell.Initializes a widget class without creatingany widgets.Registers an event handler procedure thatreceives events before or after all previouslyregistered event handler.Registers an event handler procedure thatreceives events before or after all previouslyregistered event handler without selecting forthe events.Installs accelerators from a source widget todestination widget.Installs all the accelerators from a widget andall the descendants of the widget onto onedestination widget.Determines whether a specified widget is asubclass of an Application Shell widget.Determines whether a specified widget is asubclass of a Composite widget.Determines whether a specified widget is asubclass of a Constraint widget.Determines the managed state of a specifiedchild widget.Determines whether a specified widget is asubclass of an Object widget.Determines whether a specified widget is asubclass of an Override Shell widget.Determines if a widget has been realized.Determines whether a specified widget is asubclass of a RectObj widget.Determines the current sensitivity state of awidget.Chapter 7. X Window System Interface 285


X Window System InterfaceTable 65. X Intrinsics Routines (continued)RoutineXtIsShellXtIsSubclassXtIsTopLevelShellXtIsTransientShellXtIsVendorShellXtIsWidgetXtIsWMShellXtKeysymToKeycodeListXtLastTimestampProcessedXtMainLoopXtMakeGeometryRequestXtMakeResizeRequestXtMallocXtManageChildXtManageChildrenXtMapWidgetXtMenuPopupActionXtMergeArgListsXtMoveWidgetXtNameXtNameToWidgetXtNewStringXtNextEventXtOpenDisplayXtOverrideTranslationsDescriptionDetermines whether a specified widget is asubclass of a Shell widget.Determines whether a specified widget is ina specific subclass.Determines whether a specified widget is asubclass of a TopLevelShell widget.Determines whether a specified widget is asubclass of a TransientShell widget.Determines whether a specified widget is asubclass of a VendorShell widget.Determines whether a specified widget is asubclass of a Widget widget.Determines whether a specified widget is asubclass of a WMShell widget.Returns the list of KeyCodes that map to aparticular KeySym.Retrieves the timestamp from the most recentcall to XtDispatchEvent.An infinite loop which processes input.A request from the child widget to a parentwidget for a geometry change.Makes a resize request from a widget.Allocates storage.Adds a single child to a parent widget list ofmanaged children.Adds a list of widgets to thegeometry-managed, displayable, subset of itscomposite parent widget.Maps a widget explicitly.Pops up a menu when a pointer button ispressed or when the pointer is moved intothe widget.Merges two ArgList structures.Moves a sibling widget of the child makingthe geometry request.Returns a pointer to the instance name of thespecified object.Translates a widget name to a widgetinstance.Copies an instance of a string.Returns the value from the header of theinput queue.Opens, initializes, and adds a display to anapplication context.Overwrites existing translations with newtranslations.286 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System InterfaceTable 65. X Intrinsics Routines (continued)RoutineXtOwnSelectionXtOwnSelectionIncrementalXtParentXtParseAcceleratorTableXtParseTranslationTableXtPeekEventXtPendingXtPopdownXtPopupXtPopupSpringLoadedXtProcessEventXtQueryGeometryXtRealizeWidgetXtReallocXtRegisterCaseConverterXtRegisterGrabActionXtReleaseGCXtRemoveActionHookXtRemoveAllCallbacksXtRemoveCallbackXtRemoveCallbacksXtRemoveEventHandlerXtRemoveGrabDescriptionSets the selection owner when using atomictransfer.Sets the selection owner when usingincremental transfers.Returns the parent widget for the specifiedwidget.Parses an accelerator table into the opaqueinternal representation.Compiles a translation table into the opaqueinternal representation of type XtTranslations.Returns the value from the front of the inputqueue without removing it from the queue.Determines if the input queue has eventspending.Unmaps a pop-up from within anapplication.Maps a pop-up from within an application.Maps a spring-loaded pop-up from within anapplication.Processes one input event, timeout, oralternate input source.Queries the preferred geometry of a childwidget.Realizes a widget instances.Changes the size of an allocated block ofstorage, sometimes moving it.Registers a specified case converter.Registers button and key grabs for a widget’swindow according to the event bindings inthe widget’s translation table.Deallocates a shared GC when it is no longerneeded.Removes an action hook procedure withoutdestroying the application context.Deletes all callback procedures from aspecified widget callback list.Deletes a callback procedure from a specifiedwidget callback list only if both theprocedure and the client data match.Deletes a list of callback procedures from aspecified widget callback list.Removes a previously registered eventhandler.Removes the redirection of user input to amodal widget.Chapter 7. X Window System Interface 287


X Window System InterfaceTable 65. X Intrinsics Routines (continued)RoutineXtRemoveInputXtRemoveRawEventHandlerXtRemoveTimeOutXtRemoveWorkProcXtResizeWidgetXtResizeWindowXtResolvePathnameXtScreenXtScreenOfObjectXtSetErrorHandlerXtSetErrorMsgHandlerXtSetKeyboardFocusXtSetKeyTranslatorXtSetMappedWhenManagedXtSetMultiClickTimeXtSetSelectionTimeoutXtSetSensitiveXtSetSubvaluesXtSetTypeConverterXtSetValuesXtSetWarningHandlerXtSetWarningMsgHandlerXtSetWMColormapWindowsDescriptionDiscontinues a source of input by causing theIntrinsics read routine to stop watching forinput from the input source.Removes previously registered raw eventhandler.Clears a timeout value by removing thetimeout.Removes the specified background workprocedure.Resizes a sibling widget of the child makingthe geometry request.Resizes a child widget that already has thevalues for its width, height, and borderwidth.Searches for a file using standardsubstitutions in a path list.Returns the screen pointer for the specifiedwidget.Returns the screen pointer for the nearestancestor of object that is of class Widget.Registers a procedure to call under fatal errorconditions.Registers a procedure to call under fatal errorconditions.Redirects keyboard input to a child of acomposite widget without callingXSetInputFocus.Registers a key translator.Changes the widget map_when_managedfield.Sets the multi-click time for an application.Sets the Intrinsics selection timeout.Sets the sensitivity state of a widget.Sets the current value of a non-widgetresource associated with an instance.Registers a type converter for all applicationcontexts in a process.Modifies the current value of a resourceassociated with widget instance.Registers a procedure to be called onnon-fatal error conditions.Registers a procedure to be called onnon-fatal error conditions.Sets the value of theWM_COLORMAP_WINDOWS property on awidget’s window.288 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System InterfaceTable 65. X Intrinsics Routines (continued)RoutineXtStringConversionWarningXtSuperclassXtToolkitInitializeXtTranslateCoordsXtTranslateKeyXtTranslateKeycodeXtUngrabButtonXtUngrabKeyXtUngrabKeyboardXtUngrabPointerXtUninstallTranslationsXtUnmanageChildXtUnmanageChildrenXtUnmapWidgetXtUnrealizeWidgetXtVaAppCreateShellXtVaAppInitializeXtVaCreateArgsListXtVaCreateManagedWidgetXtVaCreatePopupShellXtVaCreateWidgetXtVaGetApplicationResourcesXtVaGetSubresourcesXtVaGetSubvaluesXtVaGetValuesDescriptionA convenience routine for old-formatresource converters that convert from strings.Obtains the superclass of a widget byreturning a pointer to the superclassstructure of the widget.Initializes the X Toolkit internals.Translates an [x,y] coordinate pair fromwidget coordinates to root coordinates.The default key translator routine.Registers a key translator.Cancels a passive button grab.Cancels a passive key grab.Cancels an active keyboard grab.Cancels an active pointer grab.Causes the entire translation table for widgetto be removed.Removes a single child from the managed setof its parent.Removes a list of children from the managedlist of the parent, but does not destroy thechildren widgets.Unmaps a widget explicitly.Destroys the associated with a widget and itsdescendants.Creates a top-level widget that is the root ofa widget tree using varargs lists.Initializes the Xtk internals, creates anapplication context, opens and initializes adisplay and creates the initial applicationshell instance using varargs lists.Dynamically allocates a varargs list for usewith XtVaNestedList in multiple calls.Creates and manages a child widget in asingle procedure using varargs lists.Creates a pop-up shell using varargs lists.Creates an instance of a widget using varargslists.Retrieves resources for the overall applicationusing varargs list.Fetches resources for widget sub-parts usingvarargs list.Retrieves the current values of non-widgetresources associated with a widget instanceusing varargs lists.Retrieves the current values of resourcesassociated with a widget instance usingvarargs lists.Chapter 7. X Window System Interface 289


X Window System InterfaceTable 65. X Intrinsics Routines (continued)RoutineXtVaSetSubvaluesXtVaSetValuesXtWarningXtWarningMsgXtWidgetToApplicationContextXtWindowXtWindowOfObjectXtWindowToWidgetDescriptionSets the current values of non-widgetresources associated with a widget instanceusing varargs lists.Modifies the current values of resourcesassociated with a widget instance usingvarargs lists.Calls the installed non-fatal error procedure.Calls the installed high-level warninghandler.Gets the application context for given widget.Returns the window of the specified widget.Returns the window for the nearest ancestorof object that is of class Widget.Translates a window and display pointer intoa widget instance.Athena Widget SupportTable 66 provides the Athena widget routines.Table 66. Athena Widget RoutinesRoutineXawAsciiSaveXawAsciiSaveAsFileXawAsciiSourceChangedXawAsciiSourceFreeStringXawDialogAddButtonXawDialogGetValueStringXawDiskSourceCreateXawFormDoLayoutXawInitializeWidgetSetXawListChangeXawListHighlightXawListShowCurrentXawListUnhighlightXawPanedAllowResizeXawPanedGetMinMaxDescriptionSaves the changes made in the current textsource into a file.Saves the contents of the current text bufferinto a named file.Determines if the text buffer in an AsciiSrcobject has changed.Frees the storage associated with the stringfrom an AsciiSrc widget requested with a callto XtGetValues.Adds a new button to a Dialog widget.Returns the character string in the text fieldof a Dialog Widget.Creates a disk source.Forces or defers a re-layout of the form.Forces a reference to vendor shell so that theone in this widget is installed.Changes the list that is displayed.Highlights an item in the list.Retrieves the list element that is currently set.Unhighlights an item in the list.Enables or disables a child’s request for paneresizing.Retrieves the minimum and maximum heightsettings for a pane.290 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Table 66. Athena Widget Routines (continued)RoutineXawPanedGetNumSubXawPanedSetMinMaxXawPanedSetRefigureModeXawScrollbarSetThumbXawSimpleMenuAddGlobalActionsXawSimpleMenuClearActiveEntryXawSimpleMenuGetActiveEntryXawStringSourceCreateXawTextDisableRedisplayXawTextDisplayXawTextDisplayCaretXawTextEnableRedisplayXawTextGetInsertionPointXawTextGetSelectionPosXawTextGetSourceXawTextInvalidateXawTextReplaceXawTextSearchXawTextSetInsertionPointXawTextSetLastPosXawTextSetSelectionXawTextSetSelectionArrayXawTextSetSourceXawTextSinkClearToBackgroundXawTextSinkDisplayTextXawTextSinkFindDistanceXawTextSinkFindPositionDescriptionX Window System InterfaceRetrieves the number of panes in a panedwidget.Sets the minimum and maximum heightsettings for a pane.Enables or disables automatic recalculation ofpane sizes and positionsSets the position and length of a Scrollbarthumb.Registers an XawPositionSimpleMenu globalaction routine.Clears the SimpleMenu widget’s internalinformation about the currently highlightedmenu entry.Gets the currently highlighted menu entry.Creates a string source.Disables redisplay while making severalchanges to a Text Widget.Displays batched updates.Enables and disables the insert point.Enables redisplay.Returns the current position of the insertpoint.Retrieves the text that has been selected bythis text widget.Retrieves the current text source for thespecified widget.Redisplays a range of characters.Modifies the text in an editable Text widget.Searches for a string in a Text widget.Moves the insert point to the specified sourceposition.Sets the last position data in an AsciiSourceObject.Selects a piece of text.Assigns a new selection array to a textwidget.Replaces the text source in the specifiedwidget.Clears a region of the sink to the backgroundcolorStub function that in subclasses will displaytext.Finds the Pixel Distance between two textPositions.Finds a position in the text.Chapter 7. X Window System Interface 291


X Window System InterfaceTable 66. Athena Widget Routines (continued)RoutineXawTextSinkGetCursorBoundsXawTextSinkInsertCursorXawTextSinkMaxHeightXawTextSinkMaxLinesXawTextSinkResolveXawTextSinkSetTabsXawTextSourceConvertSelectionXawTextSourceReadXawTextSourceReplaceXawTextSourceScanXawTextSourceSearchXawTextSourceSetSelectionXawTextTopPositionXawTextUnsetSelectionXawToggleChangeRadioGroupXawToggleGetCurrentXawToggleSetCurrentXawToggleUnsetCurrentDescriptionFinds the bounding box for the insert cursor.Places the InsertCursor.Finds the Minimum height that will containa given number of lines.Finds the Maximum number of lines thatwill fit in a given height.Resolves a location to a position.Sets the Tab stops.Dummy selection converter.Reads the source into a buffer.Replaces a block of text with new text.Scans the text source for the number andtype of item specified.Searches the text source for the text blockpassed.Allows special setting of the selection.Returns the character position of theleft-most character on the first line displayedin the widget.Unhighlights previously highlighted text in awidget.Allows a toggle widget to change radiogroups.Returns the RadioData associated with thetoggle widget that is currently active in atoggle group.Sets the Toggle widget associated with theradio_data specified.Unsets all Toggles in the radio_groupspecified.Extension RoutinesX Window System Extension Routines allow you to create extensions to the coreXlib functions with the same performance characteristics. The following are theprotocol requests for X Window System extensions:v XQueryExtensionv XListExtensionsv XFreeExtensionListFor a table that lists these extension routines and provides a description of eachextension routine, see Table 60 on page 275.292 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


MIT Extensions to XX Window System InterfaceThe AIX extensions described in the <strong>IBM</strong> AIX X-Windows Programmer’s <strong>Reference</strong> arenot supported by the X Window System API provided by the <strong>TCP</strong>/<strong>IP</strong> libraryroutines.||||The following MIT extensions are supported by the <strong>TCP</strong>/<strong>IP</strong> Level 3A0:v SHAPEv MITMISCv MULTIBUFSee Table 61 on page 275Associate Table FunctionsWhen you need to associate arbitrary information with resource IDs, theXAssocTable allows you to associate your own data structures with X resources,such as bitmaps, pixmaps, fonts, and windows.An XAssocTable can be used to type X resources. For example, to create three orfour types of windows with different properties, each window ID is associatedwith a pointer to a user-defined window property data structure. (A generic type,called XID, is defined in XLIB.H.)Follow these guidelines when using an XAssocTable:v Ensure the correct display is active before initiating an XAssocTable function,because all XIDs are relative to a specified display.v Restrict the size of the table (number of buckets in the hashing system) to apower of two, and assign no more than eight XIDs for each bucket to maximizethe efficiency of the table.There is no restriction on the number of XIDs for each table or display, or thenumber of displays for each table. For a table that lists these associate tablefunctions and provides a description of each function, see Table 62 on page 276.Miscellaneous Utility RoutinesX Authorization RoutinesX Window System ToolkitIncluded in the X11LIB TXTLIB are the MIT X Miscellaneous Utility routines. Theseroutines are a set of common utility functions that have been useful to applicationwriters. For a table that lists these utility routines and provides a description ofeach utility routine, see Table 63 on page 277.Included in the X11LIB TXTLIB are the MIT X Authorization routines. Theseroutines are used to deal with X authorization data in X clients. For a table thatlists these subroutines and provides a description of each authorization routine, seeTable 64 on page 280.An X Window System Toolkit is a set of library functions layered on top of the XWindow System Xlib functions that allows you to simplify the design ofapplications by providing an underlying set of common user interface functions.Included are mechanisms for defining and expanding interclient andChapter 7. X Window System Interface 293


X Window System Interfaceintracomponent interaction independently, masking implementation details fromboth the application and component implementor.An X Window System Toolkit consists of the following:v A set of programming mechanisms, called Intrinsics, used to build widgets.v An architectural model to help programmers design new widgets, with enoughflexibility to accommodate different application interface layers.v A consistent interface, in the form of a coordinated set of widgets andcomposition policies, some of which are application domain-specific, whileothers are common across several application domains.The fundamental data type of the X Window System Toolkit is the widget. Awidget is allocated dynamically and contains state information. Every widgetbelongs to one widget class that is allocated statically and initialized. The widgetclass contains the operations allowed on widgets of that class.An X Window System Toolkit manages the following functions:v Toolkit initializationv Widgets and widget geometryv Memoryv Window, file, and timer eventsv Input focusv Selectionsv Resources and resource conversionv Translation of eventsv Graphics contextsv Pixmapsv Errors and warnings.In the <strong>VM</strong>/CMS environment, you must remap many of the X Widget and XIntrinsics routine names. This remapping is done in a file called XT_REMAP.H.This file is automatically included by the INTRINSIC.H header file. In debuggingyour application, it may be helpful to reference the XT_REMAP.H file to find theremapped names of the X Toolkit routines.Some of the X Window System header files have been renamed from their originaldistribution names, because of the file-naming conventions in the <strong>VM</strong>/CMSenvironment. Such name changes are generally restricted to those header files usedinternally by the actual widget code, rather than the application header files, tominimize the number of changes required for an application to be ported to the<strong>VM</strong>/CMS environment.In porting applications to the <strong>VM</strong>/CMS environment, you may have to make filename changes as shown in Table 67 on page 295.294 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System InterfaceTable 67. X Intrinsic Header File NamesMIT Distribution NameCompositeI.hCompositeP.hConstrainP.hIntrinsicI.hIntrinsicP.hPassivGraI.hProtocolsP.hSelectionI.hWindowObjP.h<strong>TCP</strong>/<strong>IP</strong> NameComposiI.hComposiP.hConstraP.hIntriniI.hIntriniP.hPassivGr.hProtocoP.hSelectiI.hWindowOP.hApplication ResourcesX applications can be modified at run time by a set of resources. Applications thatmake use of an X Window System toolkit can be modified by additional sets ofapplication resources. These resources are searched until a resource specification isfound. The X Intrinsics determine the actual search order used for determining aresource value.The search order used in the CMS environment in descending order of preferenceis:1. Command LineStandard arguments include:a. Command switches (-display, -fg, -foreground, +rv, and so forth)b. Resource manager directives (-name, -xrm)c. Natural language directive (-xnllanguage)2. User Environment FileUse the first source found from:a. The file named by the XENVIRONMENT environment variable, which canbe set with the CMS command:GLOBALV SELECT CENV SET XENVIRONMENT filename.filetypeb. XDEFAULT. host fileIn this case, host is the string returned by the gethostname() call.3. Server and User Preference ResourcesUse the first source found from:a. RESOURCE_MANAGER property on the root window (screen())b. X.DEFAULTS file4. Application User ResourcesUse the first source found from:a. The file named by the XUSERFILESEARCHPATH environment variable thatcan be set with the CMS command:GLOBALV SELECT CENV SET XUSERFILESEARCHPATH filename.filetypeb. The file, which is called XAPDF.classname.xapplresdir, if the XAPPLRESDIRenvironment variable has been set. In this case, XAPDF is the file name; andclassname is the file type. The environment variable, xapplresdir, contains thevalue of the file mode.Chapter 7. X Window System Interface 295


X Window System InterfaceAthena Widget SetThe XAPPLRESDIR environment variable can be set with the CMScommand:GLOBALV SELECT CENV SET XAPPLRESDIR filemodeThe CMS file name XAPDF is modified if a natural language directive isspecified to be XAPDF xnllanguage, where xnllanguage is the string specifiedby the natural language directive.5. Application Class ResourcesUse the first source found from:a. The file named by the XFILESEARCHPATH environment variable, whichcan be set with the CMS command:GLOBALV SELECT CENV SET XFILESEARCHPATH filename.filetypeb. The default application resource file named XAPDF.classname, whereclassname is the application-specified class name.The CMS file name XAPDF is modified if a natural language directive isspecified as xnllanguageXAPDF, where xnllanguage is the string specified bythe natural language directive.c. Fallback resources defined by XtAppSetFallbackResources within theapplication.The X Window System Support with <strong>TCP</strong>/<strong>IP</strong> includes the widget set developed atMIT, which is generally known as the Athena widget set.The Athena widget set supports the following widgets:AsciiSinkAsciiSrcAsciiTextBoxClockCommandDialogFormGripLabelListLogoMailboxMenuButtonPanedScrollbarSimpleSimpleMenuSme (Simple Menu Entry)SmeBSB (BSB Menu Entry)SmelineStripChartTextTextSinkTextSrcToggleVPanedViewportFor a complete list of the widgets supported by the Athena widget set, see“Athena Widget Support” on page 290.Some of the header files have been renamed from their original distribution names,because of the file-naming conventions in the <strong>VM</strong>/CMS environment. In addition,some of the header file names were changed to eliminate duplicate file names withthe OSF/Motif-based Widget support. If your application uses these header files, it296 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System Interfacewill have to be modified to use the new header file name, see Table 68.Table 68. Athena Header File NamesMIT Distribution NameAsciiSinkP.hAsciiSrcP.hAsciiTextP.hCommand.hCommandP.hForm.hFormP.hLabel.hLabelP.hList.hListP.hMenuButtoP.hScrollbar.hScrollbarP.hSimpleMenP.hStripCharP.hTemplateP.hText.hTextSinkP.hTextP.hTextSrcP.hViewportP.h<strong>TCP</strong>/<strong>IP</strong> NameAscSinkP.hAscSrcP.hAscTextP.hACommand.hACommanP.hAForm.hAFormP.hALabel.hALabelP.hAList.hAListP.hMenuButP.hAScrollb.hAScrollP.hSimpleMP.hStripChP.hTemplatP.hAText.hTextSinP.hATextP.hATextSrP.hViewporP.hOSF/Motif-Based Widget SupportThe X Window System support with <strong>TCP</strong>/<strong>IP</strong> includes the OSF/Motif-based widgetset (Release 1.1).The OSF/Motif-based Widget set supports theChapter 7. X Window System Interface 297


X Window System Interfacefollowing gadgets and widgets:ArrowButtonArrowGadgetArrowButtonGadgetBulletinBoardCascadeButtonCascadeButtonGadgetCommandDialogShellDrawingAreaDrawnButtonFileSelectionBoxFileSelectionDialogFormFrameLabelLabelGadgetListMainWindowMenuShellMessageBoxPanedWindowPushButtonPushButtonGadgetRowColumnSashScaleScrollBarScrolledWindowSelectionBoxSelectionDialogSeparatorSeparatorGadgetTextToggleButtonToggleButtonGadgetSome of the header files have been renamed from their original distribution names,because of the file-naming conventions in the CMS environment. Such namechanges are generally restricted to those header files used internally by the actualwidget code, rather than the application header files, to minimize the number ofchanges required for an application to be ported to the <strong>VM</strong>/CMS environment.In porting applications to the CMS environment, you may have to make headerfile name changes as shown in Table 67 on page 295. In porting applications to theCMS environment, the header file name changes shown in Table 69 on page 299may have to be made.298 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


X Window System InterfaceTable 69. OSF/Motif Header File NamesOSF/Motif Distribution NameBulletinBP.hCascadeBG.hCascadeBGP.hCascadeBP.hCutPasteP.hMenuShellP.hMessageBP.hRowColumnP.hScrollBarP.hScrolledWP.hSelectioB.hSelectioBP.hSeparatoG.hSeparatoGP.hSeparatorP.hToggleBGP.hToggleBP.h<strong>TCP</strong>/<strong>IP</strong> NameBulletBP.hCascadBG.hCascaBGP.hCascadBP.hCutPastP.hMenuSheP.hMessagBP.hRowColuP.hScrollBP.hScrollWP.hSelectiB.hSelectBP.hSeparatG.hSeparaGP.hSeparatP.hTogglBGP.hToggleBP.hSample X Window System ApplicationsXlib Sample ProgramThis section contains the following sample programs:v A simple program that uses Xlib calls (see page “Xlib Sample Program”)v A simple program that uses the Athena widget set (see page “Athena WidgetSample Program” on page 300)v A simple program that uses the OSF/Motif-based widget set (see page“OSF/Motif-Based Widget Sample Program” on page 302).The following is an X Window System program that uses basic Xlib functions tocreate a window, map the window to the screen, wait 60 seconds, destroy thewindow, and end./** This is an X window program using X11 API,* that opens the display and creates a window, waits* 60 seconds, then destroys the window before ending.*/#include #include #include main(argc, argv)int argc;char *argv[];{Display *dp;Window w;/** X will lookup the value of the DISPLAY global variable inChapter 7. X Window System Interface 299


Xlib Sample Program* the CENV group when passed a NULL pointer in XOpenDisplay.*/dp = XOpenDisplay(NULL);/** Create a 200X200 window at xy(40,40) with black border and name.*/w = XCreateSimpleWindow(dp, RootWindow(dp, 0),40, 40, 200, 200, 2, BlackPixel(dp, 0),WhitePixel(dp, 0));XStoreName(dp, w, “<strong>VM</strong>/CMS X Sample”);XSetIconName(dp, w, “X Sample”);/** Map the window to the display.* This will cause the window to become visible on the screen.*/XMapWindow(dp, w);/** Force X to write buffered requests.*/XFlush(dp);fprintf(stderr, “Going to sleep now.... 60 seconds...\n”);system(“CP SLEEP 60 SEC”);fprintf(stderr, “Okay, back!\n”);/** Destroy the window and end the connection to the X Server.*/}XDestroyWindow(dp, w);XCloseDisplay(dp);Athena Widget Sample ProgramThe following is a simple X Window System program that uses the Athena Labelwidget to create a window with the string Hello, World centered in the middle of awindow./** This an example of how "Hello, World" could be written using* The X Toolkit and the Athena widget set.** November 14, 1989 - Chris D. Peterson*//** $XConsortium: xhw.c,v 1.7 89/12/11 15:31:33 kit Exp $** Copyright 1989 Massachusetts Institute of Technology** Permission to use, copy, modify, distribute, and sell this* software and its documentation for any purpose is hereby* granted without fee, provided that the above copyright notice* appear in all copies and that both that copyright notice and* this permission notice appear in supporting documentation, and* that the name of M.I.T. not be used in advertising or* publicity pertaining to distribution of the software* without specific, written prior permission. M.I.T. makes no300 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Athena Widget Sample Program* representations about the suitability of this software* for any purpose. It is provided "as is" without express or* implied warranty.** M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,* IN NO EVENT SHALL M.I.T. BE LIABLE FOR ANY SPECIAL, INDIRECT* OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.*/#include #include /* Include standard Toolkit Header file.We do not need "StringDefs.h" */#ifdef <strong>IBM</strong>CPP#include /* Include the Label widget’s header file. */#else#include /* Include the Label widget’s header file. */#endif#include /* Definition of ZERO. *//** These resources will be loaded only if there is no app-defaults* file for this application. Since this is such a simple application* I am just loading the resources here. For more complex applications* It is best to install an app-defaults file.*/String fallback_resources[] = { "*Label.Label: Hello, World", NULL };main(argc, argv)int argc;char **argv;{XtAppContext app_con;Widget toplevel;/** Initialize the Toolkit, set the fallback resources, and get* the application context associated with this application.*/toplevel = XtAppInitialize(&app_con, "Xhw", NULL, ZERO, &argc, argv,fallback_resources, NULL, ZERO);/** Create a Widget to display the string. The label is picked up* from the resource database.*/(void) XtCreateManagedWidget("label", labelWidgetClass, toplevel,NULL, ZERO);/** Create the windows, and set their attributes according* to the Widget data.*/XtRealizeWidget(toplevel);/** Now process the events.Chapter 7. X Window System Interface 301


Athena Widget Sample Program*/}XtAppMainLoop(app_con);OSF/Motif-Based Widget Sample ProgramThe following is a simple X Window System program that uses theOSF/Motif-based PushButton widget to pop up a window with the string Presshere in it. It exits when you press the button.#include #include #include #include static void CloseApp();Widget Shell;Widget Button;void main(argc, argv)int argc;char *argv[];{Arg args[10];int n;XmString xst;Display *display;XtAppContext app_context;XtToolkitInitialize();app_context = XtCreateApplicationContext();display = XtOpenDisplay(app_context, NULL, argv[0], “Xsamp3”,NULL, 0, &argc, argv);if (display == NULL) {fprintf(stderr, “%s: Can’t open display\n”, argv[0]);exit(1);}n=0;XtSetArg(args[n], XmNwidth, 100); n++;XtSetArg(args[n], XmNheight, 75); n++;XtSetArg(args[n], XmNallowShellResize, True); n++;Shell = XtAppCreateShell(argv[0], NULL, applicationShellWidgetClass,display, args, n);XtRealizeWidget(Shell);n=0;Button = XmCreatePushButton(Shell, “Press here”, args, n);XtManageChild(Button);XtAddCallback (Button, XmNactivateCallback, CloseApp, NULL);}XtAppMainLoop(app_context);/********************************************************************//* CloseApp() *//********************************************************************/staticvoid CloseApp(w, client_data, call_data)Widget w;caddr_t client_data;caddr_t call_data;{exit(0);}302 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Chapter 8. Kerberos Authentication SystemAuthentication ServerThis chapter describes the Kerberos Authentication system and the routines thatyou can use to write applications that make use of the ticket-granting system.Kerberos is an authentication system that can be used within or across a <strong>TCP</strong>/<strong>IP</strong>network to identify clients and authenticate connection requests.Most conventional time-sharing systems require prospective users to identifythemselves to the system during the logon process. For example, in an <strong>VM</strong>environment a CMS user must enter a CMS user ID and password to access theapplications running on the system. In other environments that containworkstations, you cannot rely on the operating system to provide authentication.Because of this limitation, a third party must authenticate the prospective user. In a<strong>TCP</strong>/<strong>IP</strong> environment, Kerberos provides this authentication service. You mustsupply a password only when first contacting Kerberos. You do not have to enter apassword for each remote service that you request.The Kerberos system in <strong>TCP</strong>/<strong>IP</strong> consists of the following protocols and functions:v Authentication serverv Ticket-granting serverv Kerberos databasev Administration serverv Kerberos applications libraryv Applicationsv User programs.When you log on to most computer systems, you must identify yourself with apassword. Initiating the Kerberos session is similar to logging on to any othertime-sharing system, except that Kerberos requires additional checks. Theauthentication server provides a way for authenticated users to prove their identityto other servers across a network. The authentication server reads the Kerberosdatabase to verify that the client making the request is the client named in therequest.Name StructuresFor Kerberos to authenticate a client, that client must first be assigned a Kerberosname. A Kerberos name consists of three parts:Parameterprincipal nameinstanceDescriptionSpecifies the unique name of a user (client) or service.Specifies a label that is used to distinguish among variations of theprincipal name. Aninstance allows for the possibility that the sameclient or service can exist in several forms, which require distinctauthentication.For users, an instance can provide different identifiers for differentprivileges. For example, the admin instance provides specialprivileges to the users assigned to it.© Copyright <strong>IBM</strong> Corp. 1987, 2001 303


Kerberos Authentication SystemrealmFor services, an instance usually specifies the host name of themachine that provides the service.Specifies the domain name of an administrative entity. The realmidentifies each independent Kerberos site. The principal name andinstance are qualified by the realm to which they belong, and areunique only within that realm. The realm is commonly the domainname.When writing a Kerberos name, the principal name is separated from the instance (ifnot NULL) by a period. The realm follows, preceded by an @ sign. The followingare examples of valid Kerberos names:NAMEDESCR<strong>IP</strong>TIONbillbPrincipal namejis.adminPrincipal name and instancesrz@inorg.chem.eduPrincipal name, null instance, realmtrees.root@org.chem.edu Principal name, instance, realmTickets and AuthenticatorsKerberos uses the combination of a ticket and an authenticator to provideauthentication.A ticket includes the following information:v The client’s identityv A session keyv A time stampv A lifetime for the ticketv A service nameThis information is encrypted in a private key, which is known only to Kerberosand the end server. A ticket can be used multiple times by the named client to gainaccess to the named server for the lifetime of the ticket.An authenticator contains the name of the client, the client’s fully qualified domainname, and the current time. The authenticator maintains this initial information tokeep other users from capturing and using tickets not granted to them andimpersonating another user. This initial information, when compared against theinformation contained in the ticket, verifies that the client presenting the ticket isthe same client to whom the ticket was issued. Unlike a ticket, the authenticatorcan be used only once. A new authenticator must be obtained each time a clientprogram needs access to a service.Note: The design of Kerberos assumes that system clocks are synchronized towithin a few minutes on all machines that run Kerberos-authenticatedservices.Communicating with the Authentication ServerThe following four steps describe the authentication process. You must:1. Establish your identity with the authentication server.2. Obtain the initial ticket to access the ticket-granting server.3. Request a ticket for a specific service from the ticket-granting server.4. Present your ticket to the end server.304 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Ticket-Granting ServerKerberos Authentication SystemWhen you contact Kerberos, you are prompted for your user name. A request isthen sent to the authentication server containing your name and the name of aspecial service called the ticket-granting server.The authentication server searches the Kerberos database for your user name. Ifyour user name appears in the database, the authentication server generates arandom session key and the initial ticket.The information contained in the ticket is encrypted in a key known only to theticket-granting server and to the authentication server. The encrypted ticket andthe session key are further encrypted, using a key known only to the Kerberosauthentication server and the requester, and derived from the user’s password.In the <strong>TCP</strong>/<strong>IP</strong> implementation of Kerberos, the network service that supplies thetickets is called the KERBEROS server. The KERBEROS server is comprised of theauthentication server and the ticket-granting server. For information about how toset up the KERBEROS server, see <strong>TCP</strong>/<strong>IP</strong> Planning and Customization.When you receive the initial ticket, you are prompted for your password, which isconverted to a data encryption standard key and used to decrypt the responsefrom the authentication server. Your password is not passed to Kerberos; it is onlyused locally to decrypt the initial ticket. The ticket and session key, along with theother information provided by the authentication server, are kept for future use.A ticket, granted by the ticket-granting server, is valid only for a single, specificservice. You must obtain a ticket for each service you wish to access. The ticket canbe used to access the service over the lifetime of the ticket.The ticket granting server generates tickets to be used by client applications withdifferent servers. To obtain a ticket for a new service, the program must providethe ticket-granting server with the name of the target service, as well as the initialticket and the authenticator. The ticket-granting server again compares information,builds a ticket for the new service, and generates a new random session key. Thisinformation is encrypted and returned to the client program to authorize access tothe new service.Accessing a ServiceOnce you have been authenticated and obtained a ticket to a service, the clientapplication then builds an authenticator, encrypting your name and fully qualifieddomain name, as well as the current time, with the session key that was originallyreceived. With this information you can prove your identity for the lifetime of theticket-granting ticket.The target service decrypts the ticket, and uses the session key included in theticket to decrypt the authenticator. The target service compares the informationcontained in the ticket and the authenticator. If the information matches, therequest for the service is authorized. If the information does not match, the requestfor service is denied.A client can request that a server prove its identity. To do so, the server returns anauthenticator time stamp, incremented by one, back to the client.Chapter 8. Kerberos Authentication System 305


Kerberos Authentication SystemFigure 31 summarizes the ticket-granting process for accessing a service.┌───────┬────────────────┐ 1 ┌─────────────┐ ┌──────────────────┐│ Kerberos │◄───────────┤ │ │ ││ D │ Authentication │ 2 │ User │ │ ││ A Server ├───────────►│ │ │ ││ T │ │ │ │ │ Server ││ A --------│ │-------│ 5 │ ││ B │ Ticket │ 3 │ ├──────────►│ ││ A Granting │◄───────────┤ Client │ 6 │ ││ S │ Server │ 4 │ │◄──────────┤ ││ E ├───────────►│ │ │ │└───────┴────────────────┘ └─────────────┘ └──────────────────┘Kerberos DatabaseAdministration ServerFigure 31. Protocol for Accessing a Service1. Client asks the authentication server for a ticket to the ticket-granting server.2. The authentication server provides the client with a ticket to the ticket-grantingserver.3. Client asks the ticket-granting server for a ticket to a service.4. Ticket-granting server provides the client with a ticket to a service.5. Client accesses the service.6. Service returns incremented time stamp.Note: The authentication server and the ticket-granting server are implemented ina single program (KERBEROS authentication server or KERBEROS server).Kerberos requires that each realm maintain a database of Kerberos user names(principal names), their private session keys, their expiration dates, and otheradministrative information. The authentication server reads this database toauthenticate clients, but cannot change or update the information residing on thedatabase. The administration server has both read and write authority. Only oneKerberos database can be maintained in each realm. <strong>TCP</strong>/<strong>IP</strong> provides this databasewith its Kerberos support.The Administration server, known as ADMSERV, provides a read-write interface tothe Kerberos database. You can request to change a password by using theKPASSWD program. Database administrators use the KADMIN program to add orupdate information from the database. All transactions performed with theADMSERV server are logged. Both KADMIN and KPASSWD client applicationsuse the authentication server rather than the ticket-granting server to get a ticketfor the ADMSERV server. You must enter the password.The Figure 32 on page 307 summarizes the steps involving the Kerberos databaseand the ADMSERV.306 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


┌────────────────────┐│││ User/Administrator │││└────────────────────┘│ 1│ │3│ │ │┌────────────────────┐ ┌────────────────────┐│ │ ──────► │ Kerberos ││ ADMSERV Server │ 2 │ Database ││ │ ◄────── │ │└────────────────────┘ └────────────────────┘1. The user or administrator makes a request to the ADMSERV server, using the KPASSWDuser command or the KADMIN utility program.2. The following two steps occur:a. The ADMSERV verifies the identity of a requestor.b. ADMSERV updates or retrieves the database entry.3. The ADMSERV server informs the client of the result of the operation.Notes:1. The client does not need an initial ticket for this operation.2. The ADMSERV has read/write access to the database, while the <strong>VM</strong>KERB server hasread only access to the same database.Figure 32. Protocol for Changing the Kerberos DatabaseKerberos C Language Applications LibraryKerberos C Language Applications LibraryThe Kerberos applications library provides an interface for client and serverapplication programs. Usually these applications are used to write applicationprograms in the C language. The applications library also contains routines forcreating and reading authentication requests, and routines for creating and passingsafe or private messages.krb_mk_req() is the most commonly used client-side routine. krb_rd_req() is themost commonly used server-side routine.The following is an example of a typical client-server exchange:1. The client supplies krb_mk_req() with the service principal name, serviceinstance, and realm of the target service.2. The client sends the message returned by the krb_mk_req() routine over thenetwork to the server-side of the application.3. When the server receives this message, it calls krb_rd_req().4. krb_rd_req() authenticates the identity of the requester and returns eitherpermission or denial to access the application program.Note: If the application requires that the messages exchanged between client andserver be secret, the krb_mk_priv() and krb_rd_priv() routines are used toencrypt and decrypt the exchanges.Chapter 8. Kerberos Authentication System 307


Kerberos Routines <strong>Reference</strong>Kerberos Routines <strong>Reference</strong>This section provides a reference for Kerberos routines. Table 70 provides thenames, descriptions, and page numbers of the routines, located in the KRBTXTLIB, which are needed to interface with Kerberos.Table 70. Kerberos krb_ Routines <strong>Reference</strong>Kerberos krb_ Routine Description pagekrb_get_cred()Searches the caller’s ticket file for aticket containing the specifiedprincipal name, instance, and realm.309krb_kntoln()krb_mk_err()krb_mk_priv()krb_mk_req()krb_mk_safe()krb_rd_err()krb_rd_priv()krb_rd_req()krb_rd_safe()krb_recvauth()krb_sendauth()Converts a Kerberos name to a localname.Constructs an application level errormessage that can be used inconjunction with the krb_mk_priv()and krb_mk_safe() routines.Creates an encrypted, authenticatedmessage from any arbitraryapplication data pointed to by in.Takes a pointer to a text structure inwhich an authenticator is to be built.It also takes the principal name,instance, and realm of the service to beused and an optional checksum.Creates an authenticated, butunencrypted message from anyarbitrary application data pointed toby in.Unpacks a message received fromkrb_mk_err().Decrypts and authenticates a messagereceived from krb_mk_priv().Finds out information about theprincipal name when a request hasbeen made to a service.Authenticates a message receivedfrom krb_mk_safe().Called by the server to verify anauthentication message received froma client.Prepares and transmits a ticket over afile descriptor.309310310311311312313314315315316Client CommandsKerberos provides the following end-user commands:v KINIT, to log on to Kerberosv KLIST, to display Kerberos ticketsv KDESTROY, to destroy Kerberos ticketsv KPASSWD, to change a Kerberos passwordFor information about how to use these commands, see <strong>TCP</strong>/<strong>IP</strong> User’s Guide.308 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


ApplicationsApplicationsYou are responsible for securing your particular application through Kerberos.Programmers can write routines to call the applications library as an interface totheir applications programs.Kerberos RoutinesFor a sample of a typical client program that establishes a connection on a remoteserver and a typical service program that authenticates a client’s service request,see “Sample Kerberos Programs” on page 318.This section provides the syntax, parameters, and other appropriate information forroutines, located in the KRB TXTLIB, which are needed to interface with Kerberos.krb_get_cred()int krb_get_cred(service, instance, realm, c)char *service;char *instance;char *realm;CREDENTIALS *c;ParameterserviceinstancerealmcDescriptionSpecifies the first part of the Kerberos name (principal name) ofthetarget service.Specifies the second part of the Kerberos name of the targetservice.Specifies the third part of the Kerberos name of the target service.Points to the structure, which is filled with credentials information.krb_kntoln()Description: The krb_get_cred() routine searches the caller’s ticket file (tickets aremaintained in the TMP TKT0 file) for a ticket containing the specified principalname, instance, and realm. If a matching ticket is found, krb_get_cred() fills thespecified CREDENTIALS structure with the ticket information. See the KRB.Hheader file for a definition of the CREDENTIALS structure.Return Values: If successful, krb_get_cred() returns KSUCCESS. The errorGC_TKFIL is returned when any of the following occur:v The ticket cannot be read.v The ticket file does not belong to the user.v The ticket file is not a regular file.If the ticket file cannot be found, krb_get_cred() returns GC_NOTKT.See the KRB.H header file for a definition of the GC_TKFIL and GC_NOTKTreturn codes.int krb_kntoln(ad, lname)AUTH_DAT *ad;char *lname;Chapter 8. Kerberos Authentication System 309


krb_kntoln()ParameteradlnameDescriptionSpecifies an authentication structure containing a Kerberos name.Specifies a local name.krb_mk_err()Description: The krb_kntoln() routine takes a Kerberos name in an AUTH_DATstructure and checks that the instance is NULL and that the realm is the same as thelocal realm.Return Values: KSUCCESS indicates success. The principal name is returned inlname. KFAILURE indicates an error.long krb_mk_err(out, code, string)unsigned char *out;long code;char *string;ParameteroutcodestringDescriptionPoints to the output buffer area.Specifies an application-specific error code.Specifies an application-specific error string.Description: The krb_mk_err() routine constructs an application-level errormessage consisting of the protocol version number, the message type, the host byteorder, the specified code, and the text string. The krb_mk_err() routine returns apacket pointed to by out. The returned packet can be used in conjunction with thekrb_mk_priv() and krb_mk_safe() routines.The counterpart of the krb_mk_err() routine is the krb_rd_err() routine, whichreads the message that is returned.Return Values: krb_mk_error() returns an application-level error message pointedto by out. The long integer that is returned specifies the length of the messagepointed to by out.krb_mk_priv()long krb_mk_priv(in, out, in_length, schedule, key, sender, receiver)unsigned char *in;unsigned char *out;unsigned long in_length;des_key_schedule schedule;C_Block key;struct sockaddr_in *sender;struct sockaddr_in *receiver;Parameterinoutin_lengthschedulekeysenderreceiverDescriptionPoints to an input structure containing application data.Points to the output structure containing the encrypted data.Specifies the length of the application data pointed to by in.Specifies the session key schedule.Points to a private session key.Specifies the fully qualified domain name of the sender.Specifies the fully qualified domain name of the receiver.310 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Description: The krb_mk_priv() routine constructs an AUTH_MSG_PRIV message.The routine takes user data pointed to by in, of length specified by in_length, andcreates a packet in out. This packet consists of the message type, the host byteorder, user data, a time stamp, and the network address of the sender and receiver.The packet is encrypted using the supplied key and schedule. The returned packet isdecoded by the krb_rd_priv() routine in the receiver. In addition to providingprivacy, this protocol message protects against modifications, insertions, or replays.Return Values: krb_mk_priv() places the encrypted and authenticated message andheader information in the area pointed to by out. The length of the output isreturned upon success; the value −1 indicates an error.krb_mk_req()extern char *krb_err_txt[];int krb_mk_req(authent, service, instance, realm, checksum)KTEXT authent;char *service;char *instance;char *realm;unsigned long checksum;krb_mk_priv()ParameterauthentserviceinstancerealmchecksumDescriptionPoints to the text structure in which an authenticator (including aservice ticket) is to be built.Specifies the first part of the Kerberos name (principal name) oftheservice.Specifies the second part of the Kerberos name of the service.Specifies the third part of the Kerberos name of the service.Specifies any long integer supplied by the calling routine forverification.Description: The krb_mk_req() routine generates an authenticator by taking theprincipal name, instance, and realm of the service and an optional checksum. Theapplication decides how to generate the checksum.krb_mk_req() then retrieves a ticket for the desired service and creates anauthenticator. If the ticket is not in the ticket file, krb_mk_req() obtains the desiredticket from the KERBEROS server. The calling routine passes the returnedauthenticator to the service, where it is read by krb_rd_req().The authenticator cannot be modified without the session key contained in theticket. The checksum can be used to verify the authenticity of the returned data.Return Values: krb_mk_req() returns an authenticator, which is built in the authentstructure and is accessible to the calling procedure. The return code is an indexinto an array of error messages called krb_err_txt. A return code of KSUCCESSindicates success; otherwise, an error.krb_mk_safe()Chapter 8. Kerberos Authentication System 311


krb_mk_safe()long krb_mk_safe(in, out, in_length, key, sender, receiver)unsigned char *in;unsigned char *out;unsigned long in_length;C_Block *key;struct sockaddr_in *sender;struct sockaddr_in *receiver;Parameterinoutin_lengthkeysenderreceiverDescriptionPoints to an input structure containing application data.Points to the output structure containing the encrypted data.Indicates the length of the application data pointed to by in.Points to a private session key.Specifies the fully qualified domain name of the sender.Specifies the fully qualified domain name of the receiver.krb_rd_err()Description: The krb_mk_safe() routine constructs an AUTH_MSG_SAFE message.The routine takes user data pointed to by in of length in_length. The krb_mk_safe()routine then creates a packet in out consisting of the user data, a time stamp, theKerberos protocol version, the host byte order, and the network addresses of thesender and receiver. A checksum is derived from this information using thespecified private session key. This protocol message does not provide privacy (thedata is not encrypted), but it does protect against modifications, insertions, orreplays. The message is received and verified using the krb_rd_safe() function.The authentication provided by this routine is not as stringent as that provided bykrb_mk_priv().Return Values: krb_mk_safe() places the encapsulated message and headerinformation in the area pointed to by out. The length of the output is returnedupon success; the value −1 indicates an error.int krb_rd_err(in, in_length, code, msg_data)unsigned char *in;unsigned long in_length;long *code;MSG_DAT *msg_data;Parameterinin_lengthcodemsg_dataDescriptionPoints to the beginning of the received message.Indicates the length of the received message pointed to by in.Points to a value filled with the error value provided by theapplication.Points to the MSG_DAT structure, defined in KRB.H, which isfilled by krb_rd_err().Description: The krb_rd_err() routine unpacks a message received fromkrb_mk_err(), and fills the following MSG_DAT fields:Parameter Descriptionapp_data Points to the application error text.app_length Indicates the in_length specified by the calling routine.krb_rd_err() detects host byte order differences and swaps bytes accordingly.312 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Return Values: krb_rd_err() places the decrypted message and header informationin the area pointed to by msg_data. The value 0 (RD_AP_OK) indicates success.Other return codes that indicate failure are:v RD_AP_VERSIONv RD_AP_MSG_TYPESee the KRB.H header file for a description of these return codes. See the PROT.Hheader file for the definition, current protocol version, and possible Kerberosmessage types.krb_rd_priv()long krb_rd_priv(in, in_length, schedule, key, sender, receiver, msg_data)unsigned char *in;unsigned long in_length;des_key_schedule schedule;C_Block key;struct sockaddr_in *sender;struct sockaddr_in *receiver;MSG_DAT *msg_data;krb_rd_err()Parameterinin_lengthschedulekeysenderreceivermsg_dataDescriptionPoints to the beginning of the received message.Indicates the length of the received message pointed to by in.Specifies the session key schedule.Points to a private session key.Specifies the fully qualified domain name of the sender to bechecked against the message pointed to by in.Specifies the fully qualified domain name of the receiver to bechecked against the message pointed to by in.Points to the MSG_DAT structure, defined in KRB.H, which isfilled by krb_rd_priv().Description: The krb_rd_priv() routine decrypts and authenticates a messagereceived from krb_mk_priv(), and, if successful, fills the following MSG_DATfields:Parameter Descriptionapp_data Points to the decrypted application data.app_length Indicates the length of the app_data field.time_sec Specifies the time stamps in the message.time_5ms Specifies the time stamps in the message.krb_rd_priv() detects host byte order differences and swaps bytes accordingly.krb_rd_priv() checks for additional errors (see Return Values).Return Values: krb_rd_priv() places the decrypted message and headerinformation in the area pointed to by msg_data. The value 0 (RD_AP_OK) indicatessuccess; a return code indicates an error. Valid error codes are:v RD_AP_VERSIONv RD_AP_MSG_TYPEv RD_AP_MODIFIEDv RD_AP_TIMEChapter 8. Kerberos Authentication System 313


krb_rd_priv()krb_rd_req()See the KRB.H header file for a description of these return codes. See the PROT.Hheader file for the definition, current protocol version, and possible Kerberosmessage types.int krb_rd_req(authent, service, instance, from_addr, ad, filename)KTEXT authent;char *service;char *instance;unsigned long from_addr;AUTH_DAT *ad;char *filename;Parameterauthentserviceinstancefrom_addradfilenameDescriptionSpecifies the authenticator of type KTEXT.Specifies the first part of the Kerberos name (principal name).Specifies the second part of the Kerberos name.Specifies the address of the host originating the request, obtainedfrom the incoming packet, to check against the client’s host addressin the authenticator. This is ignored in the current version.Points to the structure AUTH_DAT, which is filled withinformation obtained from the authenticator.Specifies an optional file name containing the secret keys for theservice.314 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>Description: The krb_rd_req() routine reads an authentication request and returnsinformation about the identity of the requestor or an indication that the identityinformation was not authentic.The service and instance parameters name the desired service and are used to getthe service’s key from a key file to decrypt the ticket in the received message, andcompare it against the service name contained in the ticket.The krb_rd_req() routine is used by a service to obtain information about theprincipal name when a request has been made to a service. The application protocolpasses the authenticator from the client to the service. The authenticator is thenpassed to krb_rd_req() to extract the desired information.If the value of filename is a null string, the ETC SRVTAB file (the default key file) issearched to find the secret keys. If the value of filename is NULL, the routineassumes that the keys have been set and does not search for them. For informationon ETC SRVTAB, see <strong>TCP</strong>/<strong>IP</strong> Planning and Customization.Return Values: The value 0 (RD_AP_OK) indicates success. If a packet was forged,modified, or replayed, authentication fails. If the authentication fails, a nonzerovalue is returned indicating the particular problem encountered. Valid error codesare:v RD_AP_VERSIONv RD_AP_MSG_TYPEv RD_AP_MODIFIEDv RD_AP_UNDECv RD_AP_INCONv RD_AP_BADD


krb_rd_req()vvvRD_AP_TIMERD_AP_NYVRD_AP_EXPSee the KRB.H header file for a description of these return codes. See the PROT.Hheader file for the definition, current protocol version, and possible Kerberosmessage types.krb_rd_safe()long krb_rd_safe(in, in_length, key, sender, receiver, msg_data)unsigned char *in;unsigned long in_length;C_Block *key;struct sockaddr_in *sender;struct sockaddr_in *receiver;MSG_DAT *msg_data;Parameterinin_lengthkeysenderreceivermsg_dataDescriptionPoints to the beginning of the received message.Indicates the length of the received message pointed to by in.Points to a private session key.Specifies the fully qualified domain name of the sender to bechecked against the message pointed to be in.Specifies the fully qualified domain name of the receiver to bechecked against the message pointed to be in.Points to the MSG_DAT structure, defined in KRB.H, which isfilled by krb_rd_safe().Description: The krb_rd_safe() routine authenticates a message received fromkrb_mk_safe(), and, if successful, fills the following MSG_DAT fields:Parameter Descriptionapp_data Points to the decrypted application data.app_length Indicates the length of the app_data field.time_sec Specifies the time stamps in the message.time_5ms Specifies the time stamps in the message.krb_rd_safe() detects host byte order differences and swaps bytes accordingly.krb_rd_safe() checks for additional errors (see Return Values).Return Values: The authenticated message is placed in the area pointed to bymsg_data. The value 0 (RD_AP_OK) indicates success; otherwise, a return codeindicates an error. Valid error codes are:v RD_AP_VERSIONv RD_AP_MSG_TYPEv RD_AP_MODIFIEDv RD_AP_TIMESee the KRB.H header file for a description of these return codes. See the PROT.Hfor the definition, current protocol version, and possible Kerberos message types.krb_recvauth()Chapter 8. Kerberos Authentication System 315


krb_recvauth()int krb_recvauth(options, fd, ticket, service, instance, faddr, laddr, kdata, filename,schedule, version)long options;int fd;KTEXT ticket;char *service;char *instance;struct sockaddr_in *faddr;struct sockaddr_in *laddr;AUTH_DAT *kdata;char *filename;des_key_schedule schedule;char *version;ParameteroptionsfdticketserviceinstancefaddrladdrkdatafilenamescheduleversionDescriptionIndicates a bit-field of selected options. The only option valid forkrb_recvauth() is KOPT_DO_MUTUAL.Specifies the socket descriptor from which to read theauthentication message (and write to, if mutual authentication isrequested).Specifies a Kerberos ticket, which is part of the received messagesent by the client.Specifies the first part of the Kerberos name (principal name) ofthetarget service.Specifies the second part of the Kerberos name of the targetservice.Specifies the network address of the sending host (client).Specifies the network address of the local server. Can be NULL,unless mutual authentication is requested.Specifies the authentication information extracted from themessage.Specifies the name of the file containing the server’s keys. filenameis passed to krb_rd_req(). If filename is NULL, the ETC SRVTABfile is used.Specifies the session key schedule.Specifies the version string, which should be large enough to holda KRB_SENDAUTH_VLEN character string (defined in KRB.H).Description: The krb_recvauth() routine is called by the server to verify anauthentication message received from a client. The client must use thecorresponding routine, krb_sendauth(), to prepare and transmit this authenticationmessage. For an example of the usage of krb_recvauth(), see “Sample KerberosPrograms” on page 318.Return Values: The integer KSUCCESS indicates that the authentication wassuccessful. KFAILURE indicates that the authentication has failed.krb_sendauth()316 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


krb_sendauth()int krb_sendauth(options, fd, ticket, service, instance, realm, checksum, msg_data, cred,schedule, laddr, faddr, version)long options;int fd;KTEXT ticket;char *service;char *instance;char *realm;unsigned long checksum;MSG_DAT *msg_data;CREDENTIALS *cred;struct sockaddr_in *faddr;struct sockaddr_in *laddr;des_key_schedule schedule;char *version;Parameteroptionsfdticketserviceinstancerealmchecksummsg_datacredscheduleladdrfaddrversionDescriptionIndicates a bit-field of selected options.Specifies the socket descriptor to write to (and read from, if mutualauthentication is requested).Indicates the area where the ticket is returned when any optionexcept KOPT_DONT_MK_REQ is requested. WhenKOPT_DONT_MK_REQ is requested, you must supply a value forticket.Specifies the first part of the Kerberos name (principal name) ofthetarget service.Specifies the second part of the Kerberos name of the targetservice.Specifies the third part of the Kerberos name of the target service.If realm is NULL, the local realm is used.Specifies any long integer supplied by the calling routine formutual authentication purposes.Points to the MSG_DAT structure, defined in KRB.H, which isfilled by krb_sendauth(), if the mutual authentication option isspecified.Specifies the space you must allocate to hold the session key.Specifies the space you must allocate to hold the session keyschedule.Specifies the network address of the client.Specifies the network address of the server.Specifies the version string, which should be large enough to holda KRB_SENDAUTH_VLEN character string (as defined in KRB.H).Description: The krb_sendauth() routine takes the supplied information andprepares and transmits a ticket over a file descriptor for a desired service, instance,and realm, and performs mutual authentication if requested.The following options can be specified:v KOPT_DO_MUTUALv KOPT_DONT_CANONv KOPT_DONT_MK_REQChapter 8. Kerberos Authentication System 317


krb_sendauth()Sample Kerberos ProgramsKerberos ClientThe KOPT_DO_MUTUAL option requests mutual authentication. If you selectKOPT_DO_MUTUAL, you must supply the checksum, msg_data, cred, schedule, laddr,and faddr variables. The krb_mk_priv() routine performs the mutual authenticationon the remote side. The krb_rd_priv() routine performs the mutual authenticationon the local side.The KOPT_DONT_CANON option requests that instance not be used as a hostname.The KOPT_DONT_MK_REQ option requests that a server ticket not be supplied bythe KERBEROS server. You must supply the ticket variable.For an example of the usage of krb_sendauth(), see “Sample Kerberos Programs”.Return Values: KSUCCESS indicates that a ticket was successfully transmitted.KFAILURE indicates an error.This section provides examples of the following programs:v Kerberos client (SAMPLE@C C).v Kerberos server (SAMPLE@S C).The following is an example of a Kerberos client program./** $Source: /mit/kerberos/src/appl/sample/RCS/sample_client.c,v $* $Author: jtkohl $** Copyright 1987, 1988 by the Massachusetts Institute of Technology.** For copying and distribution information,* please see the file .** sample_client:* A sample Kerberos client, which connects to a server on a remote host,* at port “sample” (be sure to define it in /etc/services)* and authenticates itself to the server. The server then writes back* (in ASCII) the authenticated name.** Usage:* sample_client ** is the name of the foreign host to contact.** is an integer checksum to be used for the call to krb_mk_req()* and mutual authentication**/#define <strong>VM</strong>#include #include #include #include #include #include #include #include #include 318 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Kerberos Client#include #include #include #define SAMPLE_SERVICE“sample”extern char *malloc();main(argc, argv)int argc;char **argv;{struct servent *sp;struct hostent *hp;struct sockaddr_in sin, lsin;char *remote_host;int status;int sock, namelen;KTEXT_ST ticket;char buf[512];long authopts;MSG_DAT msg_data;CREDENTIALS cred;Key_schedule sched;long cksum;if (argc != 3) {fprintf(stderr, “usage: %s \n”,argv[0]);exit(1);}/* convert cksum to internal rep */cksum = atol(argv[2]);(void) printf(“Setting checksum to %ld\n”,cksum);/* clear out the structure first */(void) memset((char *)&sin, 0, sizeof(sin));/* find the port number for knetd */sp = getservbyname(SAMPLE_SERVICE, “tcp”);if (!sp) {fprintf(stderr,“unknown service %s/tcp; checkSAMPLE_SERVICE);exit(1);}/* copy the port number */sin.sin_port = sp->s_port;sin.sin_family = AF_INET;etc services file\n”,/* look up the server host */hp = gethostbyname(argv[1]);if (!hp) {fprintf(stderr, “unknown host %s\n”,argv[1]);exit(1);}/* copy the hostname into dynamic storage */remote_host = malloc(strlen(hp->h_name) + 1);(void) strcpy(remote_host, hp->h_name);/* set up the address of the foreign socket for connect() */sin.sin_family = hp->h_addrtype;(void) memcpy((char *)sin_addr,(char *)hp->h_addr,Chapter 8. Kerberos Authentication System 319


Kerberos Clientsizeof(hp->h_addr));/* open a <strong>TCP</strong> socket */sock = socket(PF_INET, SOCK_STREAM, 0);if (sock < 0) {tcperror(“socket”);exit(1);}/* connect to the server */if (connect(sock, &sin, sizeof(sin)) < 0) {tcperror(“connect”);close(sock);exit(1);}/* find out who I am, now that we are connected and therefore bound */namelen = sizeof(lsin);if (getsockname(sock, (struct sockaddr *) &lsin, &namelen) < 0) {tcperror(“getsockname”);close(sock);exit(1);/* call Kerberos library routine to obtain an authenticator,pass it over the socket to the server, and obtain mutualauthentication. */authopts = KOPT_DO_MUTUAL;status = krb_sendauth(authopts, sock, &ticket,SAMPLE_SERVICE, remote_host,NULL, cksum, &msg_data, &cred,sched, &lsin, &sin, “VERSION9”);if (status != KSUCCESS) {fprintf(stderr, “%s: cannot authenticate to server: %s\n”,argv[0], krb_err_txt[status]);exit(1);}/* After we send the authenticator to the server, it will writeback the name we authenticated to. Recv what it has to say. */status = recv(sock, buf, 512,0);if (status < 0) {printf(“error: recv\n”);exit(1);}/* make sure it’s null terminated before printing */if (status < 512)buf[status] = ’\0’;printf(“The server says:\n%s\n”, buf);}close(sock);exit(0);Kerberos Server320 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>The following is an example of a Kerberos server program./** $Source: /mit/kerberos/src/appl/sample/RCS/sample_server.c,v $* $Author: jtkohl $** Copyright 1987, 1988 by the Massachusetts Institute of Technology.** For copying and distribution information,


* please see the file .** sample_server:* A sample Kerberos server, which reads a ticket from a <strong>TCP</strong> socket,* decodes it, and writes back the results (in ASCII) to the client.** Usage:* sample_server** file descriptor 0 (zero) should be a socket connected to the requesting* client (this will be correct if this server is started by inetd).*/#define <strong>VM</strong>#include #include #include #include #include #include #include #include #include #include #include #include #include #define SAMPLE_SERVICE “sample”#define SAMPLE_SERVER “sample”#define SRVTAB “”main(){struct sockaddr_in peername, myname;int namelen = sizeof(peername);int status, count, len;long authopts;AUTH_DAT auth_data;KTEXT_ST clt_ticket;Key_schedule sched;char instance[INST_SZ];char version[9];char retbuf[512];char lname[ANAME_SZ];int s, ns;struct servent *sp;openlog(“sample_server”, 0);Kerberos Serversp = getservbyname(SAMPLE_SERVICE, “tcp”);if (!sp) {fprintf(stderr,“unknown service %s/tcp; checkSAMPLE_SERVICE);exit(1);}/* copy the port number */myname.sin_port = sp->s_port;myname.sin_family = AF_INET;etc services file\n”,s = socket(AF_INET, SOCK_STREAM, 0);if(s


Kerberos Server}if (listen(s, 10) < 0) {tcperror(“sample_s: listen”);exit(1);}again:namelen = sizeof(peername);ns = accept(s, &peername, &namelen);/** To verify authenticity, we need to know the address of the* client.*/if (getpeername(ns, (struct sockaddr *)&peername, &namelen) < 0) {syslog(LOG_ERR, “getpeername: %m”);exit(1);}/* for mutual authentication, we need to know our address */namelen = sizeof(myname);if (getsockname(ns, (struct sockaddr *)&myname, &namelen) < 0) {syslog(LOG_ERR, “getsocknamename: %m”);exit(1);}/* read the authenticator and decode it. Since wedon’t care what the instance is, we use “*” so that krb_rd_reqwill fill it in from the authenticator */(void) strcpy(instance, “*”);/* we want mutual authentication */authopts = KOPT_DO_MUTUAL;status = krb_recvauth(authopts, ns, &clt_ticket,SAMPLE_SERVER, instance, &peername, &myname, &auth_data,SRVTAB, sched, version);if (status != KSUCCESS) {syslog(LOG_ERR, “Kerberos error: %s\n”, krb_err_txt[status]);(void) sprintf(retbuf, “Kerberos error: %s\n”,krb_err_txt[status]);} else {/* Check the version string (8 chars) */if (strncmp(version, “VERSION9”, 8)) {/* didn’t match the expected version *//* could do something different, but we just log an errorand continue */version[8] = ’\0’; /* make sure null term */syslog(LOG_ERR, “Version mismatch: ’%s’ isn’t ’VERSION9’”,version);}/* now that we have decoded the authenticator, translatethe kerberos principal.instance@realm into a local name */if (krb_kntoln(&auth_data, lname) != KSUCCESS)strcpy(lname,“*No local name returned by krb_kntoln*”);/* compose the reply */sprintf(retbuf,“You are %s.%s@%s (local name %s),\n at address %s,version %s,cksum %ld\n”,auth_data.pname,auth_data.pinst,auth_data.prealm,lname,inet_ntoa(peername.sin_addr),version,auth_data.checksum);}322 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


* write back the response */if ((count = send(ns, retbuf, (len = strlen(retbuf) + 1),0))


Kerberos Server324 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Chapter 9. SNMP Agent Distributed Program InterfaceSNMP Agents and SubagentsThe Simple Network Management Protocol (SNMP) agent distributed programinterface (DPI) permits end users to dynamically add, delete, or replacemanagement variables in the local Management Information Base (MIB) withoutrequiring you to recompile the SNMP agent.SNMP defines an architecture that consists of network management stations(SNMP clients), network elements (hosts and gateways), and network managementagents and subagents. The network management agents perform informationmanagement functions, such as gathering and maintaining network performanceinformation and formatting and passing this data to clients when requested. Thisinformation is collectively called the Management Information Base (MIB). Formore information about clients, agents, and the MIB, see the <strong>TCP</strong>/<strong>IP</strong> User’s Guide.A subagent provides an extension to the functionality provided by the SNMPagent. The subagent allows you to define your own MIB variables, which areuseful in your environment, and register them with the SNMP agent. Whenrequests for these variables are received by the SNMP agent, the agent passes therequest to the subagent. The subagent then returns a response to the agent. TheSNMP agent creates an SNMP response packet and sends the response to theremote network management station that initiated the request. The existence of thesubagent is transparent to the network management station.To allow the subagents to perform these functions, the SNMP agent binds to anarbitrarily chosen <strong>TCP</strong> port and listens for connection requests. A well-known portis not used. Every invocation of the SNMP agent potentially results in a different<strong>TCP</strong> port being used.A subagent of the SNMP agent determines the port number by sending a GETrequest for the MIB variable, which represents the value of the <strong>TCP</strong> port. Thesubagent is not required to create and parse SNMP packets, because the DPI Clanguage application program interface (API) has a library routinequery_DPI_port(). This routine handles the GET request and response calledProtocol Data Units (PDUs) necessary to obtain the port number of the <strong>TCP</strong> portused by the agent for DPI requests. After the subagent obtains the value of the DPI<strong>TCP</strong> port, it should make a <strong>TCP</strong> connection to the appropriate port. After asuccessful connect(), the subagent registers the set of variables it supports with theSNMP agent. When all variable classes are registered, the subagent waits forrequests from the SNMP agent.Note: Although <strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong> V2R4 supports SNMP DPI 1.0 subagents, youshould recompile and link-edit the SNMP DPI subagents when upgrading toDPI 1.1.© Copyright <strong>IBM</strong> Corp. 1987, 2001 325


SNMP Agent Distributed Program InterfaceProcessing DPI RequestsThe SNMP agent can initiate three DPI requests: GET, SET, and GET-NEXT. Theserequests correspond to the three SNMP requests that a network managementstation can make. The subagent responds to a request with a response packet. Theresponse packet can be created using the mkDPIresponse() library routine, which ispart of the DPI API library.The SNMP subagent can initiate only two requests: REGISTER and TRAP. For anoverview of the SNMP DPI, see Figure 33.┌─────────────────────────────────┐│ Network ││ Network Manager │││├─────────────────────────────────┤│ SNMP Protocol │└────────────┬────────────────────┘ | Get | | GetNext | GetResponseTrap | | Set || |┌─────┴────────────────────┴──────┐┌──────────────────────┐│ SNMP Protocol | | DPI Interface |├────────────────────────┬────────┤ Reply │ ┌─────────────────┤| | |◄───────────┤ | || SNMP Agent | | | | Client || ┌───────────┼─► | MIB query | | || | | Get/Set | ├───────────►| | or || Trap| | info | SNMP | | | |├─────┼──────┼───────┐ | | trap | | SNMP || │ | | DPI |◄───────────┤ | Sub-Agent || <strong>TCP</strong>/<strong>IP</strong> layers, | | | | | || Kernel | | |◄───────────┤ | |└────────────────────┴───┴────────┘ Register └────┴─────────────────┘Figure 33. SNMP DPI overviewNotes:1. The SNMP agent communicates with the SNMP manager by the standardSNMP protocol.2. The SNMP agent communicates with the <strong>TCP</strong>/<strong>IP</strong> layers and kernel (operatingsystem) in an implementation-dependent manner. It implements the standardMIB II view.3. An SNMP Subagent, running as a separate process (potentially even on anothermachine), can register objects with the SNMP agent.4. The SNMP agent decodes SNMP Packets. If such a packet contains a Get,GetNext or Set request for an object registered by a subagent, it sends therequest to the subagent by a query packet.5. The SNMP subagent sends responses back by a reply packet.6. The SNMP agent then encodes the reply into an SNMP packet and sends itback to the requesting SNMP manager.7. If the subagent wants to report an important state change, it sends a trappacket to the SNMP agent, which encodes it into an SNMP trap packet andsends it to the manager(s).326 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Processing a GET RequestThe DPI packet is parsed, using the pDPIpacket() routine, to get the object ID ofthe requested variable. If the specified object ID of the requested variable is notsupported by the subagent, the subagent returns an error indication ofSNMP_NO_SUCH_NAME. Name, type, or value information is not returned. Forexample:unsigned char *cp;cp = mkDPIresponse(SNMP_NO_SUCH_NAME,0);If the object ID of the variable is supported, an error is not returned and the name,type, and value of the object ID are returned using the mkDPIset() andmkDPIresponse() routines. The following is an example of an object ID, whosetype is string, being returned.char *obj_id;unsigned char *cp;struct dpi_set_packet *ret_value;char *data;/* obj_id = object ID of variable, like 1.3.6.1.2.1.1.1 *//* should be identical to object ID sent in GET request */data = a string to be returned;ret_value = mkDPIset(obj_id,SNMP_TYPE_STRING,strlen(data)+1,data);cp = mkDPIresponse(0,ret_value);SNMP Agent Distributed Program InterfaceProcessing a SET RequestProcessing a SET request is similar to processing a GET request, but you must passadditional information to the subagent. This additional information consists of thetype, length, and value to be set.If the object ID of the variable is not supported, the subagent returns an errorindication of SNMP_NO_SUCH_NAME. If the object ID of the variable issupported, but cannot be set, an error indication of SNMP_READ_ONLY isreturned. If the object ID of the variable is supported, and is successfully set, themessage SNMP_NO_ERROR is returned.Processing a GET_NEXT RequestParsing a GET_NEXT request yields two parameters: the object ID of the requestedvariable and the reason for this request. This allows the subagent to return thename, type, and value of the next supported variable, whose namelexicographically follows that of the passed object ID.Subagents can support several different groups of the MIB tree. However, thesubagent cannot jump from one group to another. You must first determine thereason for the request to then determine the path to traverse in the MIB tree. Thesecond parameter contains this reason and is the group prefix of the MIB tree thatis supported by the subagent.If the object ID of the next variable supported by the subagent does not match thisgroup prefix, the subagent must return SNMP_NO_SUCH_NAME. If required, theSNMP agent will call on the subagent again and pass a different group prefix.Chapter 9. SNMP Agent Distributed Program Interface 327


SNMP Agent Distributed Program InterfaceFor example, if you have two subagents, the first subagent registers two groupprefixes, A and C, and supports variables A.1, A.2, and C.1. The second subagentregisters the group prefix B, and supports variable B.1.When a remote management station begins dumping the MIB, starting from A, thefollowing sequence of queries is performed.Subagent 1 is called:get_next(A,A) == A.1get_next(A.1,A) == A.2get_next(A.2,A) == error(no such name)Subagent 2 is then called:get_next(A.2,B) == B.1get_next(B.1,B) == error(no such name)Subagent 1 is then called:get_next(B.1,C) == C.1get_next(C.1,C) == error(no such name)Processing a REGISTER RequestA subagent must register the variables that it supports with the SNMP agent.Packets can be created using the mkDPIregister() routine.For example:unsigned char *cp;cp = mkDPIregister(’1.3.6.1.2.1.1.2.’);Note: Object IDs are registered with a trailing dot (“.”). Although DPI 1.0 level didaccept an Object ID without a trailing dot, the new level (DPI 1.1) does not.Processing a TRAP RequestA subagent can request that the SNMP agent generate a TRAP for it. The subagentmust provide the desired values for the generic and specific parameters of theTRAP. The subagent can optionally provide a name, type, and value parameter.The DPI API library routine mkDPItrap() can be used to generate the TRAP packet.Compiling and LinkingTo compile your program, you must include the SNMP_DPI.H header file.To compile and link your applications, use the following procedures:1. To set up the C environment, enter the following commands:SET LDRTBLS nnGLOBAL LOADLIB SCEERUNGLOBAL TXTLIB SCEELKED2. To compile your program, enter one of the following commands:v Place compile options on the CC command:CC filename (def(<strong>VM</strong>)v Place #define <strong>VM</strong> in the first line of all user’s C source files:CC filename3. To generate an executable module, enter the following command:328 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


SNMP DPI <strong>Reference</strong><strong>TCP</strong>LOAD load_list control_file c(TXTLIB DPILIBNotes:1. It is necessary to global CMSLIB TXTLIB only when running in 370 mode.2. Make sure you have access to the <strong>IBM</strong> C for <strong>VM</strong>/ESA Compiler and to the<strong>TCP</strong>MAINT 592 minidisk.3. For the syntax of the <strong>TCP</strong>LOAD EXEC, see “<strong>TCP</strong>LOAD EXEC” on page 2 andfor the syntax of the SET LDRTBLS command, see “SET LDRTBLS Command”on page 4.The following table provides a reference for SNMP DPI. Table 71 describes eachSNMP DPI routine supported by <strong>TCP</strong>/<strong>IP</strong>, and identifies the page in the bookwhere you can find more information.Table 71. SNMP DPI <strong>Reference</strong>SNMP DPI Routine Description pageDPIdebug()Used to turn some DPI internal329tracing on or off.fDPIparse()Frees a parse tree previously created 330by a call to pDPIpacket().mkDPIlist()Creates the portion of the parse treethat represents a list of name andvalue pairs.330mkDPIregister()Creates a register request packet and 331returns a pointer to a static buffer.mkDPIresponse() Creates a response packet. 331mkDPIset()Creates a representation of a parse 332tree name and value pair.mkDPItrap() Creates a trap request packet. 333mkDPItrape()Creates an extended trap. Basicallythe same as the mkDPItrap() routinebut allows you to pass a list ofvariables and an enterprise object ID.334pDPIpacket()query_DPI_port()SNMP Agent Distributed Program InterfaceParses a DPI packet and returns aparse tree representation.Determines what <strong>TCP</strong> port isassociated with DPI.335336DPI Library RoutinesDPIdebug()This section provides the syntax, parameters, and other appropriate information foreach DPI routine supported by <strong>TCP</strong>/<strong>IP</strong> Level 310 for <strong>VM</strong>.#include #include void DPIdebug(onoff)int *onoff;Chapter 9. SNMP Agent Distributed Program Interface 329


DPIdebug()fDPIparse()Parameter Descriptiononoff Specifies an integer. A value of 0 turns tracing off and a value of 1(or nonzero) turns tracing on.Description: The DPIdebug() routine can be used to turn DPI internal tracing on oroff.#include #include void fDPIparse(hdr)struct snmp_dpi_hdr *hdr;ParameterhdrDescriptionSpecifies a parse tree.mkDPIlist()Description: The fDPIparse() routine frees a parse tree that was previously createdby a call to pDPIpacket(). After calling fDPIparse(), no further references to theparse tree can be made.#include #include struct dpi_set_packet *mkDPIlist(packet, oid_name, type, len, value)struct dpi_set_packet *packet;char *oid_name;int type;int len;char *value;Parameterpacketoid_nametypelenvalueDescriptionSpecifies a pointer to a structure dpi_set_packet.Specifies the object identifier of the variable.Specifies the type of the value.Specifies the length of the value.Specifies a pointer to the value.Description: The mkDPIlist() routine can be used to create the portion of the parsetree that represents a list of name and value pairs. Each entry in the list representsa name and value pair (as would normally be returned in a response packet). If thepointer packet is NULL, then a new dpi_set_packet structure is dynamicallyallocated and the pointer to that structure is returned. The structure contains thenew name and value pair. If the pointer packet is not NULL, then a newdpi_set_packet structure is dynamically allocated and chained to the list. The newstructure contains the new name and value pair. The pointer packet is returned tothe caller. If an error is detected, a NULL pointer is returned.The value of type can be the same as for mkDPIset(). These values are defined inthe snmp_dpi.h header file.330 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


As a result, the structure dpi_set_packet has changed and now has a next pointer(zero in case of a mkDPIset() call and also zero upon the first mkDPIlist() call). Thefollowing is the format of dpi_set_packet:struct dpi_set_packet {char*object_id;unsigned char type;unsigned short value_len;char*value;struct dpi_set_packet *next;};A subagent writer would normally look only at the dpi_set_packet structure whenreceieving a SNMP_DPI_SET request and after having issued a pDPIpacket() call.mkDPIregister()#include #include unsigned char *mkDPIregister(oid_name)char *oid_name;mkDPIlist()Parameteroid_nameDescriptionSpecifies the object identifier of the variable to be registered. Objectidentifiers are registered with a trailing dot (“.”).Description: The mkDPIregister() routine creates a register request packet andreturns a pointer to a static buffer, which holds the packet contents. The length ofthe remaining packet is stored in the first two bytes of the packet.Return Values: If successful, returns a pointer to a static buffer containing thepacket contents. A NULL pointer is returned if an error is detected during thecreation of the packet.Example:unsigned char *packet;int len;The following is an example of the mkDPIregister() routine./* register sysDescr variable */packet = mkDPIregister(“1.3.6.1.2.1.1.1.“);len = *packet * 256 + *(packet + 1);len += 2; /* include length bytes */mkDPIresponse()#include #include unsigned char *mkDPIresponse(ret_code, value_list)int ret_code;struct dpi_set_packet *value_list;Parameterret_codevalue_listDescriptionDetermines the error code to be returned.Points to a parse tree containing the name, type, and valueinformation to be returned.Chapter 9. SNMP Agent Distributed Program Interface 331


mkDPIresponse()Description: The mkDPIresponse() routine creates a response packet. The firstparameter, ret_code, is the error code to be returned. Zero indicates no error.Possible errors include the following:v SNMP_NO_ERRORv SNMP_TOO_BIGv SNMP_NO_SUCH_NAMEv SNMP_BAD_VALUEv SNMP_READ_ONLYv SNMP_GEN_ERRSee the SNMP_DPI.H header file for a description of these messages.If ret_code does not indicate an error, then the second parameter is a pointer to aparse tree created by mkDPIset(), which represents the name, type, and valueinformation being returned. If an error is indicated, the second parameter is passedas a NULL pointer.The length of the remaining packet is stored in the first two bytes of the packet.Note: mkDPIresponse() always frees the passed parse tree.Return Values: If successful, mkDPIresponse() returns a pointer to a static buffercontaining the packet contents. This is the same buffer used by mkDPIregister(). ANULL pointer is returned if an error is detected during the creation of the packet.Example:mkDPIset()unsigned char *packet;The following is an example of the mkDPIresponse() routine.int error_code;struct dpi_set_packet *ret_value;packet = mkDPIresponse(error_code, ret_value);len = *packet * 256 + *(packet + 1);len += 2; /* include length bytes */#include #include struct dpi_set_packet *mkDPIset(oid_name, type, len, value)char *oid_name;int type;int len;char *value;Parameteroid_nametypelenvalueDescriptionSpecifies the object identifier of the variable.Specifies the type of the object identifier.Indicates the length of the value.Points to the first byte of the value of the object identifier.Description: The mkDPIset() routine can be used to create the portion of a parsetree that represents a name and value pair (as would normally be returned in aresponse packet). It returns a pointer to a dynamically allocated parse treerepresenting the name, type, and value information. If there is an error detectedwhile creating the parse tree, a NULL pointer is returned.332 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


mkDPItrap()The value of type can be one of the following (which are defined in theSNMP_DPI.H header file):v SNMP_TYPE_NUMBERv SNMP_TYPE_STRINGv SNMP_TYPE_OBJECTv SNMP_TYPE_INTERNETv SNMP_TYPE_COUNTERv SNMP_TYPE_GAUGEv SNMP_TYPE_TICKSThe value parameter is always a pointer to the first byte of the object ID’s value.Note: The parse tree is dynamically allocated, and copies are made of the passedparameters. After a successful call to mkDPIset(), the application can disposeof the passed parameters without affecting the contents of the parse tree.Return Values: Returns a pointer to a parse tree containing the name, type, andvalue information.#include #include unsigned char *mkDPItrap(generic, specific, value_list)int generic;int specific;struct dpi_set_packet *value_list;mkDPIset()Parametergenericspecificvalue_listDescriptionSpecifies the generic field in the SNMP TRAP packet.Identifies the specific field in the SNMP TRAP packet.Passes the name and value pair to be placed into the SNMPpacket.Description: The mkDPItrap() routine creates a TRAP request packet. Theinformation contained in value_list is passed as the set_packet portion of the parsetree.The length of the remaining packet is stored in the first two bytes of the packet.Note: mkDPItrap() always frees the passed parse tree.Return Values: If the packet can be created, a pointer to a static buffer containingthe packet contents is returned. This is the same buffer that is used bymkDPIregister(). If an error is encountered while creating the packet, a NULLpointer is returned.Example:The following is an example of the mkDPItrap() routine.struct dpi_set_packet *if_index_value;unsigned long data;unsigned char *packet;int len;data = 3; /* interface number =3*/if_index_value = mkDPIset(“1.3.6.1.2.1.2.2.1.1“, SNMP_TYPE_NUMBER,Chapter 9. SNMP Agent Distributed Program Interface 333


mkDPItrap()sizeof(unsigned long), &data);packet = mkDPItrap(2, 0, if_index_value);len = *packet * 256 + *(packet + 1);len += 2; /* include length bytes */write(fd,packet,len);mkDPItrape()#include #include unsigned char *mkDPItrape(generic, specific, value_list, enterprise_oid)long int generic; /* 4 octet integer */long int specific;struct dpi_set_packet *value_list;char *enterprise_oid;Parametergenericspecificvalue_listDescriptionSpecifies the generic field for the SNMP TRAP packet.Specifies the specific field for the SNMP TRAP packet.Specifies a pointer to a structure dpi_set_packet, which containsone or more variables to be sent with the SNMP TRAP packet. OrNULL if no variables are to be send.enterprise_oid Specifies a pointer to a character string representing the enterpriseobject ID (in ASN.1 notation, for example, 1.3.6.1.4.1.2.2.1.4).Specifies NULL if you want the SNMP agent to use its ownenterprise object ID.Description: The mkDPItrape() routine can be used to create an extended trap. Anextended trap resembles the mkDPItrap() routine, but it allows you to pass a list ofvariables and an enterprise-object ID.The structure for dpi_trap_packet has changed, but this structure is not exposed tosubagent writers.Example of an Extended TrapThe following is a piece of sample code to send an extended trap. No errorchecking is done.struct dpi_set_packet *set;intlen;long int num = 15; /* 4 octet integer */unsigned long int ctr = 1234;charstr][ = "a string";unsigned char *packet;set=0;set = mkDPIlist(set,"1.3.6.1.4.1.2.2.1.4.1",SNMP_TYPE_NUMBER,sizeof(num),&num);set = mkDPIlist(set,"1.3.6.1.4.1.2.2.1.4.2",SNMP_TYPE_STRING,strlen(str),str);set = mkDPIlist(set,"1.3.6.1.4.1.2.2.1.4.6",SNMP_TYPE_COUNTER,sizeof(ctr),&ctr);packet = mkDPItrape(6L, 37L, set, "1.3.6.1.4.1.2.2.1.4");len = *packet * 256 + *(packet+1);len += 2;write(fd, packet, len) /* use send on OS/2 */334 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


You can use a mkDPIset() call to create an initial dpi_set_packet for the first nameand value pair. So the following sample is equivalent to the one above.struct dpi_set_packet *set;intlen;long int num = 15; /* 4 octet integer */unsigned long int ctr = 1234;charstr][ = "a string";unsigned char *packet;pDPIpacket()set = mkDPIset("1.3.6.1.4.1.2.2.1.4.1",SNMP_TYPE_NUMBER,sizeof(num),&num);set = mkDPIlist(set,"1.3.6.1.4.1.2.2.1.4.2",SNMP_TYPE_STRING,strlen(str),str);set = mkDPIlist(set,"1.3.6.1.4.1.2.2.1.4.6",SNMP_TYPE_COUNTER,sizeof(ctr),&ctr);packet = mkDPItrape(6L, 37L, set, "1.3.6.1.4.1.2.2.1.4");len = *packet * 256 + *(packet+1);len += 2;write(fd, packet, len) /* use send on OS/2 */If the high order bit must be on for the specific trap type, then a negative integermust be passed.#include #include struct snmp_dpi_hdr *pDPIpacket(packet)unsigned char *packet;mkDPItrape()ParameterpacketDescriptionSpecifies the DPI packet to be parsed.Description: The pDPIpacket() routine parses a DPI packet and returns a parse treerepresenting its contents. The parse tree is dynamically allocated and containscopies of the information within the DPI packet. After a successful call topDPIpacket(), the packet can be disposed of in any manner the applicationchooses, without affecting the contents of the parse tree.Return Values: If pDPIpacket() is successful, a parse tree is returned. If an error isencountered during the parse, a NULL pointer is returned.Note: The parse tree structures are defined in the SNMP_DPI.H header file.Example: The following is an example of the mkDPItrap() routine. The root of theparse tree is represented by an snmp_dpi_hdr structure.struct snmp_dpi_hdr {unsigned char proto_major;unsigned char proto_minor;unsigned char proto_release;};unsigned char packet_type;union {struct dpi_get_packetstruct dpi_next_packetstruct dpi_set_packetstruct dpi_resp_packetstruct dpi_trap_packet} packet_body;*dpi_get;*dpi_next;*dpi_set;*dpi_response;*dpi_trap;Chapter 9. SNMP Agent Distributed Program Interface 335


pDPIpacket()The packet_type field can have one of the following values, which are defined in theSNMP_DPI.H header file:v SNMP_DPI_GETv SNMP_DPI_GET_NEXTv SNMP_DPI_SETThe packet_type field indicates the request that is made of the DPI client. For eachof these requests, the remainder of the packet_body is different. If a GET request isindicated, the object ID of the desired variable is passed in a dpi_get_packetstructure.struct dpi_get_packet {char *object_id;};A GET-NEXT request is similar, but the dpi_next_packet structure also contains theobject ID prefix of the group that is currently being traversed.struct dpi_next_packet {char *object_id;char *group_id;};If the next object, whose object ID lexicographically follows the object ID indicatedby object_id, does not begin with the suffix indicated by the group_id, the DPI clientmust return an error indication of SNMP_NO_SUCH_NAME.A SET request has the most data associated with it, and this is contained in adpi_set_packet structure.struct dpi_set_packet {char *object_id;unsigned char type:unsigned short value_len;char *value;};The object ID of the variable to be modified is indicated by object_id. The type ofthe variable is provided in type and can have one of the following values:v SNMP_TYPE_NUMBERv SNMP_TYPE_STRINGv SNMP_TYPE_OBJECTv SNMP_TYPE_EMPTYv SNMP_TYPE_INTERNETv SNMP_TYPE_COUNTERv SNMP_TYPE_GAUGEv SNMP_TYPE_TICKSThe length of the value to be set is stored in value_len and value contains a pointerto the value.Note: The storage pointed to by value is reclaimed when the parse tree is freed.The DPI client must make provision for copying the value contents.query_DPI_port()336 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


query_DPI_port()#include int query_DPI_port (host_name, community_name)char *host_name;char *community_name;Parameter Descriptionhost_name Points to the SNMP agent’s host name or internet address.community_namePoints to the community name to be used when making a request.Description: The query_DPI_port() routine is used by a DPI client to determine the<strong>TCP</strong> port number that is associated with the DPI. This port number is needed toconnect() to the SNMP agent. The port number is obtained through an SNMP GETrequest. community_name and host_name are the arguments that are passed to thequery_DPI_port() routine.Return Values: An integer representing the <strong>TCP</strong> port number is returned ifsuccessful; a −1 is returned if the port cannot be determined.Sample SNMP DPI Client ProgramThis section provides an example of an SNMP DPI agent program. You can run thedpisample program against the SNMP agents that support the SNMP-DPIinterface, as described in RFC 1228.The sample can be used to test agent DPI implementations because it providesvariables of all types and also allows you to generate traps of all types.The DPISAMPLE program implements a set of variables in the DPISAMPLE tablewhich consists of a set of objects in the <strong>IBM</strong> Research tree (1.4.1.2.2.1.4). SeeFigure 34 on page 339 for the object type and objectID.The DPISAMPLE Program (Sample DPI Subagent)The DPISAMPLE program accepts the following arguments:►►DPISAMPLE?-d0-d n►Chapter 9. SNMP Agent Distributed Program Interface 337


The DPISAMPLE Program (Sample DPI Subagent)►-trap gtype stype data►◄-trape gtype stype enterprise ▼ data n-ent_traps-ent_trapse-std_traps-all_traps-iucv-uSNMPD-iucv -u agent_useridLOOPBACK-inetagent_hostnamePUBLICcommunityParameter Description? Invokes output with an explanation about how the dpisamplecommand is used. This option should be used in a C-shellenvironment.-d n Sets the debug level. The level, n, has a range from 0—4,0issilent and 4 is most verbose. The default level is 0.-trapGenerates a trap with the following options:gtype Specifies the type as generic. The available ranges are 0 —6.stype Specifies the type as specific.data Passes data as an additional value for the variabledpiSample.stype.0. Data is interpreted depending on stype.The following list describes the available values for thestype parameter and their data descriptions:1 number2 octet string3 object id4 empty (ignored)5 internet address6 counter7 gauge8 time ticks9 display stringother octet string-trapeGenerates an extended trap (available with DPI 1.1 level) with thefollowing defined options:gtype Specifies the trap as generic. The available ranges are 0 —6.stype Specifies the type as specific.enterpriseProvides the object ID for the extended trap.dataPasses data values for additional variables. Data is passedas octet strings. Instances of data can be 1-n.338 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


-ent_traps Generates nine enterprise-specific traps with stype values of 1—9,using the internal dpiSample variables as data.-ent_trapse Generates nine enterprise-specific traps with stype values of 11 —19, using the internal dpiSample variables as data.-std_traps-all_trapsGenerates and simulates the standard five SNMP traps (generictypes 1—5)including the link-down trap.Generates both the standard traps (-std_traps) and theenterprise-specific traps with stype of1—9(-ent_traps).-iucv Specifies that an AF_IUCV socket is to be used to connect to theSNMP agent. The -iucv parameter is the default.-u agent_userid Specifies the user ID where the SNMP agent (SNMPD) is running.The default is SNMPD.-inetSpecifies that an AF_INET socket is to be used to connect to theSNMP agent.agent_hostname Specifies the host name of the system where an SNMP-DPI capableagent is running. The default, if -inet is specified, is LOOPBACK.community_nameSpecifies the community name to get the dpiPort. The default isPUBLIC.DPISAMPLE TABLEThe DPISAMPLE Program (Sample DPI Subagent)# DPISAMPLE.C supports these variables as an SNMP DPI sample sub-agent# it also generates enterprise specific traps via DPI with these objects.DPISample 1.3.6.1.4.1.2.2.1.4. table 0DPISampleNumber 1.3.6.1.4.1.2.2.1.4.1. number 10# next one is to be able to send a badValue with a SET requestDPISampleNumberString 1.3.6.1.4.1.2.2.1.4.1.1. string 10DPISampleOctetString 1.3.6.1.4.1.2.2.1.4.2. string 10DPISampleObjectID 1.3.6.1.4.1.2.2.1.4.3. object 10# XGMON/SQESERV does not allow to specify empty (so use empty string)DPISampleEmpty 1.3.6.1.4.1.2.2.1.4.4. string 10DPISampleInetAddress 1.3.6.1.4.1.2.2.1.4.5. internet 10DPISampleCounter 1.3.6.1.4.1.2.2.1.4.6. counter 10DPISampleGauge 1.3.6.1.4.1.2.2.1.4.7. gauge 10DPISampleTimeTicks 1.3.6.1.4.1.2.2.1.4.8. ticks 10DPISampleDisplayString 1.3.6.1.4.1.2.2.1.4.9. display 10DPISampleCommand 1.3.6.1.4.1.2.2.1.4.10. display 1Client Sample ProgramFigure 34. DPISAMPLE Table MIB descriptionsThe following is an example of a SNMP-DPI subagent program./*********************************************************************//* *//* SNMP-DPI - SNMP Distributed Programming Interface *//* *//* May 1991 - Version 1.0 - SNMP-DPI Version 1.0 (RFC1228) *//* Created by <strong>IBM</strong> Research. *//* Feb 1992 - Version 1.1 - Allow enterpriseID to be passed with *//* a (enterprise specific) trap *//* - allow multiple variables to be passed *//* - Use 4 octets (INTEGER from RFC1157) *//* for generic and specific type. */Chapter 9. SNMP Agent Distributed Program Interface 339


Client Sample Program/* Jun 1992 - Make it run on OS/2 as well *//* Note: dpisample = dpisampl on OS/2 *//* *//* Copyright None *//* *//* dpisample.c - a sample SNMP-DPI subagent *//* - can be used to test agent DPI implementations. *//* *//* For testing with XGMON and/or SQESERV (SNMP Query Engine) *//* it is best to keep the following define for OID in sync *//* with the dpiSample objectID in the MIB description file *//* (mib_desc for XGMON, MIB_DESC DATA for SQESERV on <strong>VM</strong> and *//* MIB@DESC.DATA for SQESERV on MVS, MIB2TBL on OS/2). *//* *//*********************************************************************/#define OID "1.3.6.1.4.1.2.2.1.4."#define ENTERPRISE_OID "1.3.6.1.4.1.2.2.1.4" /* dpiSample */#define ifIndex "1.3.6.1.2.1.2.2.1.1.0"#define egpNeighAddr "1.3.6.1.2.8.5.1.2.0"#define PUBLIC_COMMUNITY_NAME "public"#if defined(<strong>VM</strong>) || defined(MVS)#define SNMPAGENTUSERID "SNMPD"#define SNMPIUCVNAME"SNMP_DPI"#pragma csect(CODE, "$DPISAMP")#pragma csect(STATIC,"#DPISAMP")#include /* <strong>VM</strong> specific things */#include "snmpnms.h" /* short external names for <strong>VM</strong>/MVS */#include "snmp_vm.h" /* more of those short names */#include #include #include #include #include #include #include extern char ebcdicto][, asciitoe][;#pragma linkage(cmxlate,OS)#define DO_ETOA(a) cmxlate((a),ebcdictoascii,strlen((a)))#define DO_ATOE(a) cmxlate((a),asciitoebcdic,strlen((a)))#define DO_ERROR(a) tcperror((a))#define LOOPBACK "loopback"#define IUCV TRUE#define max(a,b) (((a) > (b)) ? (a) : (b))#define min(a,b) (((a) < (b)) ? (a) : (b))#else /* we are not on <strong>VM</strong> or MVS */#ifdef OS2#define INCL_DOSPROCESS#include #include //#include /* GKS */#include /* GKS */#ifndef sleep#define sleep(a) DosSleep(1000L * (a)) /*GKS*/#endif#define close soclose/*char * malloc(); *//*unsigned long strtoul(); */#endif//#include /* GKS */#include #include 340 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Client Sample Program#include #include // #include #define DO_ETOA(a) ; /* no need for this */#define DO_ATOE(a) ; /* no need for this */#define DO_ERROR(a) perror((a))#define LOOPBACK "localhost"#define IUCV FALSE#ifdef AIX221#define isdigit(c) (((c) >= ’0’) && ((c)


Client Sample Programstatic void issue_std_traps(void);static void issue_ent_traps(void);static void issue_ent_trapse(void);static void do_register(void);static void dump_bfr(const char *buf, const int len);static struct dpi_set_packet *addtoset(struct dpi_set_packet *data,int stype);static unsigned long lookup_host(const char *hostname);#endif /* _NO_PROTO */#define OSTRING"hex01-04:"#define DSTRING"Initial Display String"#define COMMAND"None"#define BUFSIZE 4096#define TIMEOUT 3#define PACKET_LEN(packet) (((unsigned char)*(packet)) * 256 + \((unsigned char)*((packet) + 1)) + 2)/* We have the following instances for OID.x variables *//* 0 - table */static long number = 0; /* 1-anumber */static unsigned char *ostring = 0; /* 2 - octet string */static int ostring_len = 0; /* and its length */static unsigned char *objectID = 0; /* 3 - objectID */static int objectID_len= 0; /* and its length *//* 4 - some empty variable */static unsigned long ipaddr = 0; /* 5 - ipaddress */static unsigned long counter = 1; /* 6-acounter */static unsigned long gauge = 1; /* 7-agauge */static unsigned long ticks = 1; /* 8 - time ticks */static unsigned char *dstring = 0; /* 9 - display string */static unsigned char *command = 0; /* 10 - command */static char *DPI_var][ = {"dpiSample","dpiSampleNumber","dpiSampleOctetString","dpiSampleObjectID","dpiSampleEmpty","dpiSampleInetAddress","dpiSampleCounter","dpiSampleGauge","dpiSampleTimeTicks","dpiSampleDisplayString","dpiSampleCommand"};static short int valid_types][ ={/*SNMP_TYPEs accepted on SET */-1, /* 0 do not check type */SNMP_TYPE_NUMBER, /* 1 number */SNMP_TYPE_STRING, /* 2 octet string */SNMP_TYPE_OBJECT, /* 3 object identifier */-1, /* SNMP_TYPE_EMPTY */ /* 4 do not check type */SNMP_TYPE_INTERNET, /* 5 internet address */SNMP_TYPE_COUNTER, /* 6 counter */SNMP_TYPE_GAUGE, /* 7 gauge */SNMP_TYPE_TICKS, /* 8 time ticks */SNMP_TYPE_STRING, /* 9 display string */SNMP_TYPE_STRING /* 10 command (display string) */#define OID_COUNT_FOR_TRAPS 9#define OID_COUNT 10};static char *packet = NULL; /* ptr to send packet. */static char inbuf]BUFSIZE[; /* buffer for receive packets */static int dpi_fd; /* fd for socket to DPI agent */342 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


static short int dpi_port; /* DPI_port at agent */static unsigned long dpi_ipaddress; /* <strong>IP</strong> address of DPI agent */static char *dpi_hostname; /* hostname of DPI agent */static char *dpi_userid; /* userid of DPI agent <strong>VM</strong>/MVS */static char *var_gid; /* groupID received */static char *var_oid; /* objectID received */static int var_index; /* OID variable index */static unsigned char var_type; /* SET value type */static char *var_value; /* SET value */static short int var_value_len; /* SET value length */static int debug_lvl = 0; /* current debug level */static int use_iucv = IUCV; /* optional use of AF_IUCV */static int do_quit = FALSE;/* Quit in await loop */static int trap_gtype = 0; /* trap generic type */static int trap_stype = 0; /* trap specific type */static char *trap_data = NULL;/* trap data */static int do_trap = 0; /* switch for traps */#define ONE_TRAP 1#define ONE_TRAPE 2#define STD_TRAPS 3#define ENT_TRAPS 4#define ENT_TRAPSE 5#define ALL_TRAPS 6#define MAX_TRAPE_DATA 10 /* data for extended trap */static long trape_gtype = 6; /* trap generic type */static long trape_stype = 11; /* trap specific type */static char *trape_eprise = NULL; /* enterprise id */static char *trape_data]MAX_TRAPE_DATA[; /* pointers to data values */static int trape_datacnt; /* actual number of values */#ifdef _NO_PROTO /* for classic K&R C */main(argc, argv) /* main line */int argc;char *argv][;#else /* _NO_PROTO */ /* for ANSI-C compiler */main(const int argc, char *argv][) /* main line */#endif /* _NO_PROTO */{check_arguments(argc, argv); /* check callers arguments */dpi_ipaddress = lookup_host(dpi_hostname); /* get ip address */init_connection(); /* connect to specified agent */init_variables(); /* initialize our variables */if (do_trap) { /* we just need to do traps */issue_traps(); /* issue the trap(s) */sleep(WAIT_FOR_AGENT); /* sleep a bit, so agent can */close(dpi_fd); /* read data before we close */exit(0);/* and that’s it*/} /* end if (do_trap) */do_register(); /* register our objectIDs */printf("%s ready and awaiting queries from agent\n",argv]0[);while (do_quit == FALSE) { /* forever until quit or error */await_and_read_packet(); /* wait for next packet */handle_packet(); /* handle it */if (do_trap) issue_traps(); /* request to issue traps */} /* while loop */sleep(WAIT_FOR_AGENT); /* allow agent to read response */printf("Quitting, %s set to: quit\n",DPI_var]10[);exit(2); /* sampleDisplayString == quit */}#ifdef _NO_PROTO /* for classic K&R C */static void issue_traps()#else /* _NO_PROTO */ /* for ANSI-C compiler */static void issue_traps(void)#endif /* _NO_PROTO */{switch (do_trap) { /* let’s see which one(s) */Client Sample ProgramChapter 9. SNMP Agent Distributed Program Interface 343


Client Sample Program}case ONE_TRAP: /* only need to issue one trap */issue_one_trap(); /* go issue the one trap */break;case ONE_TRAPE: /* only need to issue one trape */issue_one_trape(); /* go issue the one trape */break;case STD_TRAPS: /* only need to issue std traps */issue_std_traps(); /* standard traps gtypes 0-5 */break;case ENT_TRAPS: /* only need to issue ent traps */issue_ent_traps(); /* enterprise specific traps */break;case ENT_TRAPSE: /* only need to issue ent trapse */issue_ent_trapse(); /* enterprise specific trapse */break;case ALL_TRAPS: /* only need to issue std traps */issue_std_traps(); /* standard traps gtypes 0-5 */issue_ent_traps(); /* enterprise specific traps */issue_ent_trapse(); /* enterprise specific trapse */break;default:break;} /* end switch (do_trap) */do_trap = 0; /* reset do_trap switch */#ifdef _NO_PROTO /* for classic K&R C */static void await_and_read_packet() /* await packet from DPI agent */#else /* _NO_PROTO */ /* for ANSI-C compiler */static void await_and_read_packet(void)/* await packet from DPI agent */#endif /* _NO_PROTO */{int len, rc, bytes_to_read, bytes_read = 0;#ifdef OS2int socks]5[;#elsefd_set read_mask;#endifstruct timeval timeout;#ifdef OS2socks]0[ = dpi_fd;rc = select(socks, 1, 0, 0, -1L);#elseFD_ZERO(&read_mask);FD_SET(dpi_fd, &read_mask); /* wait for data */rc = select(dpi_fd+1, &read_mask, NULL, NULL, NULL);#endifif (rc != 1) { /* exit on error */DO_ERROR("await_and_read_packet:close(dpi_fd);exit(1);select");}#ifdef OS2len = recv(dpi_fd, inbuf, 2, 0); /* read 2 bytes first */#elselen = read(dpi_fd, inbuf, 2); /* read 2 bytes first */#endifif (len


Client Sample Programclose(dpi_fd);exit(1);}while (bytes_to_read > 0) { /* while bytes to read */#ifdef OS2socks]0[ = dpi_fd;len = select(socks, 1, 0, 0, 3000L);#elsetimeout.tv_sec = 3; /* wait max 3 seconds */timeout.tv_usec = 0;FD_SET(dpi_fd, &read_mask); /* check for data */len = select(dpi_fd+1, &read_mask, NULL, NULL, &timeout);#endifif (len == 1) { /* select returned OK */#ifdef OS2len = recv(dpi_fd, &inbuf]2[ + bytes_read, bytes_to_read, 0);#elselen = read(dpi_fd, &inbuf]2[ + bytes_read, bytes_to_read);#endif} /* end if (len == 1) */if (len 0) */}#ifdef _NO_PROTO /* for classic K&R C */static void handle_packet() /* handle DPI packet from agent */#else /* _NO_PROTO */ /* for ANSI-C compiler */static void handle_packet(void) /* handle DPI packet from agent */#endif /* _NO_PROTO */{struct snmp_dpi_hdr *hdr;if (debug_lvl > 2) {printf("Received following SNMP-DPI packet:\n");dump_bfr(inbuf, PACKET_LEN(inbuf));}hdr = pDPIpacket(inbuf); /* parse received packet */if (hdr == 0) { /* ignore if can’t parse */printf("Ignore received packet, could not parse it!\n");return;}packet = NULL;var_type = 0;var_oid = "";var_gid = "";switch (hdr->packet_type) {/* extract pointers and/or data from specific packet types, *//* such that we can use them independent of packet type. */case SNMP_DPI_GET:if (debug_lvl > 0) printf("SNMP_DPI_GET for ");var_oid = hdr->packet_body.dpi_get->object_id;break;case SNMP_DPI_GET_NEXT:if (debug_lvl > 0) printf("SNMP_DPI_GET_NEXT for ");var_oid = hdr->packet_body.dpi_next->object_id;var_gid = hdr->packet_body.dpi_next->group_id;break;case SNMP_DPI_SET:if (debug_lvl > 0) printf("SNMP_DPI_SET for ");Chapter 9. SNMP Agent Distributed Program Interface 345


Client Sample Programvar_value_len = hdr->packet_body.dpi_set->value_len;var_value = hdr->packet_body.dpi_set->value;var_oid = hdr->packet_body.dpi_set->object_id;var_type = hdr->packet_body.dpi_set->type;break;default: /* Return a GEN_ERROR */if (debug_lvl > 0) printf("Unexpected packet_type %d, genErr\n",hdr->packet_type);packet = mkDPIresponse(SNMP_GEN_ERR, NULL);fDPIparse(hdr); /* return storage allocated by pDPIpacket() */send_packet(packet);return;break;} /* end switch(hdr->packet_type) */if (debug_lvl > 0) printf("objectID: %s \n",var_oid);}if (strlen(var_oid) packet_type == SNMP_DPI_GET_NEXT) var_index = 0; /* OK */else { /* cannot handle */if (debug_lvl>0) printf("...Ignored %s, noSuchName\n",var_oid);packet = mkDPIresponse(SNMP_NO_SUCH_NAME, NULL);fDPIparse(hdr); /* return storage allocated by pDPIpacket() */send_packet(packet);return;}} else { /* Extract our variable index (from OID.index.instance) *//* We handle any instance the same (we only have one instance) */var_index = atoi(&var_oid]strlen(OID)[);}if (debug_lvl > 1) {printf("...The groupID=%s\n",var_gid);printf("...Handle as if objectID=%s%d\n",OID,var_index);}switch (hdr->packet_type) {case SNMP_DPI_GET:do_get(); /* do a get to return response */break;case SNMP_DPI_GET_NEXT:{ char toid]256[; /* space for temporary objectID */var_index++; /* do a get for the next variable */sprintf(toid,"%s%d",OID,var_index); /* construct objectID */var_oid = toid; /* point to it */do_get(); /* do a get to return response */} break;case SNMP_DPI_SET:if (debug_lvl > 1) printf("...value_type=%d\n",var_type);do_set(); /* set new value first */if (packet) break; /* some error response was generated */do_get(); /* do a get to return response */break;}fDPIparse(hdr); /* return storage allocated by pDPIpacket() */#ifdef _NO_PROTO /* for classic K&R C */static void do_get() /* handle SNMP_GET request */#else /* _NO_PROTO */ /* for ANSI-C compiler */static void do_get(void) /* handle SNMP_GET request */#endif /* _NO_PROTO */{struct dpi_set_packet *data = NULL;switch (var_index) {case 0: /* table, cannot be queried by itself */printf("...Should not issue GET for table %s.0\n", OID);break;case 1: /* a number */346 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Client Sample Programdata = mkDPIset(var_oid,SNMP_TYPE_NUMBER,sizeof(number),&number);break;case 2: /* an octet_string (can have binary data) */data = mkDPIset(var_oid,SNMP_TYPE_STRING,ostring_len,ostring);break;case 3: /* object id */data = mkDPIset(var_oid,SNMP_TYPE_OBJECT,objectID_len,objectID);break;case 4: /* some empty variable */data = mkDPIset(var_oid,SNMP_TYPE_EMPTY,0,NULL);break;case 5: /* internet address */data = mkDPIset(var_oid,SNMP_TYPE_INTERNET,sizeof(ipaddr),&ipaddr);break;case 6: /* counter (unsigned) */data =mkDPIset(var_oid,SNMP_TYPE_COUNTER,sizeof(counter),&counter);break;case 7: /* gauge (unsigned) */data = mkDPIset(var_oid,SNMP_TYPE_GAUGE,sizeof(gauge),&gauge);break;case 8: /* time ticks (unsigned) */data = mkDPIset(var_oid,SNMP_TYPE_TICKS,sizeof(ticks),&ticks);break;case 9: /* a display_string (printable ascii only) */DO_ETOA(dstring);data = mkDPIset(var_oid,SNMP_TYPE_STRING,strlen(dstring),dstring);DO_ATOE(dstring);break;case 10: /* a command request (command is a display string) */DO_ETOA(command);data = mkDPIset(var_oid,SNMP_TYPE_STRING,strlen(command),command);DO_ATOE(command);break;default: /* Return a NoSuchName */if (debug_lvl > 1)printf("...GET]NEXT[ for %s, not found\n", var_oid);break;} /* end switch (var_index) */}if (data) {if (debug_lvl > 0) {printf("...Sending response oid: %s type: %d\n",var_oid, data->type);printf("......Current value: ");print_val(var_index); /* prints \n at end */}packet = mkDPIresponse(SNMP_NO_ERROR,data);} else { /* Could have been an error in mkDPIset though */if (debug_lvl > 0) printf("...Sending response noSuchName\n");packet = mkDPIresponse(SNMP_NO_SUCH_NAME,NULL);} /* end if (data) */if (packet) send_packet(packet);#ifdef _NO_PROTO /* for classic K&R C */static void do_set() /* handle SNMP_SET request */#else /* _NO_PROTO */ /* for ANSI-C compiler */static void do_set(void) /* handle SNMP_SET request */#endif /* _NO_PROTO */{unsigned long *ulp;long *lp;if (valid_types]var_index[ != var_type &&valid_types]var_index[ != -1) {printf("...Ignored set request with type %d, expect type %d,",var_type, valid_types]var_index[);Chapter 9. SNMP Agent Distributed Program Interface 347


Client Sample Programprintf(" Returning badValue\n");packet = mkDPIresponse(SNMP_BAD_VALUE, NULL);if (packet) send_packet(packet);return;}switch (var_index) {case 0: /* table, cannot set table. */if (debug_lvl > 0) printf("...Ignored set TABLE, noSuchName\n");packet = mkDPIresponse(SNMP_NO_SUCH_NAME,NULL);break;case 1: /* a number */lp = (long *)var_value;number = *lp;break;case 2: /* an octet_string (can have binary data) */free(ostring);ostring = (char *)malloc(var_value_len + 1);bcopy(var_value, ostring, var_value_len);ostring_len = var_value_len;ostring]var_value_len[ = ’\0’; /* so we can use it as a string */break;case 3: /* object id */free(objectID);objectID = (char *)malloc(var_value_len + 1);bcopy(var_value, objectID, var_value_len);objectID_len = var_value_len;if (objectID]objectID_len -1[) {objectID]objectID_len++[ = ’\0’; /* a valid one needs a null */if (debug_lvl > 0)printf("...added a terminating null to objectID\n");}break;case 4: /* an empty variable, cannot set */if (debug_lvl > 0) printf("...Ignored set EMPTY, readOnly\n");packet = mkDPIresponse(SNMP_READ_ONLY,NULL);break;case 5: /* Internet address */ulp = (unsigned long *)var_value;ipaddr = *ulp;break;case 6: /* counter (unsigned) */ulp = (unsigned long *)var_value;counter = *ulp;break;case 7: /* gauge (unsigned) */ulp = (unsigned long *)var_value;gauge = *ulp;break;case 8: /* time ticks (unsigned) */ulp = (unsigned long *)var_value;ticks = *ulp;break;case 9: /* a display_string (printable ascii only) */free(dstring);dstring = (char *)malloc(var_value_len + 1);bcopy(var_value, dstring, var_value_len);dstring]var_value_len[ = ’\0’; /* so we can use it as a string */DO_ATOE(dstring);break;case 10: /* a request to execute a command */free(command);command = (char *)malloc(var_value_len + 1);bcopy(var_value, command, var_value_len);command]var_value_len[ = ’\0’; /* so we can use it as a string */DO_ATOE(command);if (strcmp("all_traps",command) == 0) do_trap = ALL_TRAPS;else if (strcmp("std_traps",command) == 0) do_trap = STD_TRAPS;348 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


else if (strcmp("ent_traps",command) == 0) do_trap = ENT_TRAPS;else if (strcmp("ent_trapse",command) == 0) do_trap = ENT_TRAPSE;else if (strcmp("all_traps",command) == 0) do_trap = ALL_TRAPS;else if (strcmp("quit",command) == 0) do_quit = TRUE;else break;if (debug_lvl > 0)printf("...Action requested: %s set to: %s\n",DPI_var]10[, command);break;default: /* NoSuchName */if (debug_lvl > 0)printf("...Ignored set for %s, noSuchName\n", var_oid);packet = mkDPIresponse(SNMP_NO_SUCH_NAME,NULL);break;} /* end switch (var_index) */if (packet) send_packet(packet);}#ifdef _NO_PROTO /* for classic K&R C */static void issue_std_traps()#else /* _NO_PROTO */ /* for ANSI-C compiler */static void issue_std_traps(void)#endif /* _NO_PROTO */{trap_stype = 0;trap_data = dpi_hostname;for (trap_gtype=0; trap_gtype


Client Sample Program}sprintf(temp_string,"%lu",ticks);break;case 9 :trap_data = dstring;break;} /* end switch (trap_stype) */issue_one_trap();}/* issue a set of extended traps, pass enterprise ID and multiple* variable (assume octect string) as passed by caller*/#ifdef _NO_PROTO /* for classic K&R C */static void issue_ent_trapse()#else /* _NO_PROTO */ /* for ANSI-C compiler */static void issue_ent_trapse(void)#endif /* _NO_PROTO */{int i, n;struct dpi_set_packet *data = NULL;unsigned char *packet = NULL;unsigned long ipaddr, ulnum;char oid]256[;char *cp;trape_gtype = 6;trape_eprise = ENTERPRISE_OID;for (n=11; n < (11+OID_COUNT_FOR_TRAPS); n++) {data = 0;trape_stype = n;for (i=1; i 0) && (packet)) {printf("sending trape packet: %lu %lu enterprise=%s\n",trape_gtype, trape_stype, trape_eprise);}if (packet) send_packet(packet);else printf("Could not make trape packet\n");}}/* issue one extended trap, pass enterprise ID and multiple* variable (assume octect string) as passed by caller*/#ifdef _NO_PROTO /* for classic K&R C */static void issue_one_trape()#else /* _NO_PROTO */ /* for ANSI-C compiler */static void issue_one_trape(void)#endif /* _NO_PROTO */{struct dpi_set_packet *data = NULL;unsigned char *packet = NULL;char oid]256[;char *cp;int i;for (i=0; i


if (data == 0) {printf("Could not make dpiset_packet\n");} else if (debug_lvl > 0) {printf("Preparing: ]oid=%s[ value: ", oid);printf("’");for (cp = trape_data]i[; *cp; cp++) /* loop through data */printf("%2.2x",*cp); /* hex print one byte */printf("’H\n");}}packet = mkDPItrape(trape_gtype,trape_stype,data,trape_eprise);if ((debug_lvl > 0) && (packet)) {printf("sending trape packet: %lu %lu enterprise=%s\n",trape_gtype, trape_stype, trape_eprise);}if (packet) send_packet(packet);else printf("Could not make trape packet\n");}#ifdef _NO_PROTO /* for classic K&R C */static void issue_one_trap()#else /* _NO_PROTO */ /* for ANSI-C compiler */static void issue_one_trap(void)#endif /* _NO_PROTO */{long int num; /* must be 4 bytes */struct dpi_set_packet *data = NULL;unsigned char *packet = NULL;unsigned long ipaddr, ulnum;char oid]256[;char *cp;Client Sample Programswitch (trap_gtype) {/* all traps are handled more or less the same sofar. *//* could put specific handling here if needed/wanted. */case 0: /* simulate cold start */case 1: /* simulate warm start */case 4: /* simulate authentication failure */strcpy(oid,"none");break;case 2: /* simulate link down */case 3: /* simulate link up */strcpy(oid,ifIndex);num=1;data = mkDPIset(oid, SNMP_TYPE_NUMBER, sizeof(num), &num);break;case 5: /* simulate EGP neighbor loss */strcpy(oid,egpNeighAddr);ipaddr = lookup_host(trap_data);data = mkDPIset(oid, SNMP_TYPE_INTERNET, sizeof(ipaddr), &ipaddr);break;case 6: /* simulate enterprise specific trap */sprintf(oid,"%s%d.0",OID, trap_stype);switch (trap_stype) {case 1: /* a number */num = strtol(trap_data,(char **)0,10);data = mkDPIset(oid, SNMP_TYPE_NUMBER, sizeof(num), &num);break;case 2: /* an octet_string (could have hex data) */data = mkDPIset(oid,SNMP_TYPE_STRING,strlen(trap_data),trap_data);break;case 3: /* object id */data = mkDPIset(oid,SNMP_TYPE_OBJECT,strlen(trap_data) + 1,trap_data);break;case 4: /* an empty variable value */data = mkDPIset(oid, SNMP_TYPE_EMPTY, 0, 0);Chapter 9. SNMP Agent Distributed Program Interface 351


Client Sample Programbreak;case 5: /* internet address */ipaddr = lookup_host(trap_data);data = mkDPIset(oid, SNMP_TYPE_INTERNET, sizeof(ipaddr), &ipaddr);break;case 6: /* counter (unsigned) */ulnum = strtoul(trap_data,(char **)0,10);data = mkDPIset(oid, SNMP_TYPE_COUNTER, sizeof(ulnum), &ulnum);break;case 7: /* gauge (unsigned) */ulnum = strtoul(trap_data,(char **)0,10);data = mkDPIset(oid, SNMP_TYPE_GAUGE, sizeof(ulnum), &ulnum);break;case 8: /* time ticks (unsigned) */ulnum = strtoul(trap_data,(char **)0,10);data = mkDPIset(oid, SNMP_TYPE_TICKS, sizeof(num), &ulnum);break;case 9: /* a display_string (ascii only) */DO_ETOA(trap_data);data = mkDPIset(oid,SNMP_TYPE_STRING,strlen(trap_data),trap_data);DO_ATOE(trap_data);break;default: /* handle as string */printf("Unknown specific trap type: %s, assume octet_string\n",trap_stype);data = mkDPIset(oid,SNMP_TYPE_STRING,strlen(trap_data),trap_data);break;} /* end switch (trap_stype) */break;default: /* unknown trap */printf("Unknown general trap type: %s\n", trap_gtype);return;break;} /* end switch (trap_gtype) */packet = mkDPItrap(trap_gtype,trap_stype,data);if ((debug_lvl > 0) && (packet)) {printf("sending trap packet: %u %u ]oid=%s[ value: ",trap_gtype, trap_stype, oid);if (trap_stype == 2) {printf("’");for (cp = trap_data; *cp; cp++) /* loop through data */printf("%2.2x",*cp); /* hex print one byte */printf("’H\n");} else printf("%s\n", trap_data);}if (packet) send_packet(packet);else printf("Could not make trap packet\n");}#ifdef _NO_PROTO /* for classic K&R C */static void send_packet(packet) /* DPI packet to agent */char *packet;#else /* _NO_PROTO */ /* for ANSI-C compiler */static void send_packet(const char *packet) /* DPI packet to agent */#endif /* _NO_PROTO */{int rc;if (debug_lvl > 2) {printf("...Sending DPI packet:\n");dump_bfr(packet, PACKET_LEN(packet));}#ifdef OS2rc = send(dpi_fd,packet,PACKET_LEN(packet),0);#elserc = write(dpi_fd,packet,PACKET_LEN(packet));352 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


#endifif (rc != PACKET_LEN(packet)) DO_ERROR("send_packet: write");/* no need to free packet (static buffer in mkDPI.... routine) */}#ifdef _NO_PROTO /* for classic K&R C */static void do_register() /* register our objectIDs with agent */#else /* _NO_PROTO */ /* for ANSI-C compiler */static void do_register(void) /* register our objectIDs with agent */#endif /* _NO_PROTO */{int i, rc;char toid]256[;if (debug_lvl > 0) printf("Registering variables:\n");for (i=1; i


Client Sample Program}data = mkDPIlist(data, var_oid, SNMP_TYPE_INTERNET,sizeof(ipaddr), &ipaddr);break;case 6: /* counter (unsigned) */data =mkDPIlist(data, var_oid, SNMP_TYPE_COUNTER,sizeof(counter), &counter);break;case 7: /* gauge (unsigned) */data = mkDPIlist(data, var_oid, SNMP_TYPE_GAUGE,sizeof(gauge), &gauge);break;case 8: /* time ticks (unsigned) */data = mkDPIlist(data, var_oid, SNMP_TYPE_TICKS,sizeof(ticks), &ticks);break;case 9: /* a display_string (printable ascii only) */DO_ETOA(dstring);data = mkDPIlist(data, var_oid, SNMP_TYPE_STRING,strlen(dstring), dstring);DO_ATOE(dstring);break;} /* end switch (stype) */return(data);#ifdef _NO_PROTO /* for classic K&R C */static void print_val(index)int index;#else /* _NO_PROTO */ /* for ANSI-C compiler */static void print_val(const int index)#endif /* _NO_PROTO */{char *cp;struct in_addr display_ipaddr;switch (index) {case 1 :printf("%ld\n",number);break;case 2 :printf("’");for (cp = ostring; cp < ostring + ostring_len; cp++)printf("%2.2x",*cp);printf("’H\n");break;case 3 :printf("%*s\n", objectID_len, objectID);break;case 4 :printf("no value (EMPTY)\n");break;case 5 :display_ipaddr.s_addr = (u_long) ipaddr;printf("%s\n",inet_ntoa(display_ipaddr));/* This worked on <strong>VM</strong>, MVS and AIX, but not on OS/2* printf("%d.%d.%d.%d\n", (ipaddr >> 24), ((ipaddr > 24),* ((ipaddr > 24), ((ipaddr > 24));*/break;case 6 :printf("%lu\n",counter);break;case 7 :printf("%lu\n",gauge);break;case 8 :printf("%lu\n",ticks);354 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Client Sample Program}break;case 9 :printf("%s\n",dstring);break;case 10 :printf("%s\n",command);break;} /* end switch(index) */#ifdef _NO_PROTO /* for classic K&R C */static void check_arguments(argc, argv) /* check arguments */int argc;char *argv][;#else /* _NO_PROTO */ /* for ANSI-C compiler */static void check_arguments(const int argc, char *argv][)#endif /* _NO_PROTO */{char *hname, *cname;int i, j;dpi_userid = hname = cname = NULL;for (i=1; argc > i; i++) {if (strcmp(argv]i[,"-d") == 0) {i++;if (argc > i) {debug_lvl = atoi(argv]i[);if (debug_lvl >= 5) {DPIdebug(1);}}} else if (strcmp(argv]i[,"-trap") == 0) {if (argc > i+3) {trap_gtype = atoi(argv]i+1[);trap_stype = atoi(argv]i+2[);trap_data = argv]i+3[;i=i+3;do_trap = ONE_TRAP;} else usage(argv]0[, 1);} else if (strcmp(argv]i[,"-trape") == 0) {if (argc > i+4) {trape_gtype = strtoul(argv]i+1[,(char**)0,10);trape_stype = strtoul(argv]i+2[,(char**)0,10);trape_eprise = argv]i+3[;for(i=i+4,j=0;(argc > i) && (j < MAX_TRAPE_DATA);i++, j++) {trape_data]j[= argv]i[;}trape_datacnt = j;do_trap = ONE_TRAPE;break; /* -trape must be last option */} else usage(argv]0[, 1);} else if (strcmp(argv]i[,"-all_traps") == 0) {do_trap = ALL_TRAPS;} else if (strcmp(argv]i[,"-std_traps") == 0) {do_trap = STD_TRAPS;} else if (strcmp(argv]i[,"-ent_traps") == 0) {do_trap = ENT_TRAPS;} else if (strcmp(argv]i[,"-ent_trapse") == 0) {do_trap = ENT_TRAPSE;#if defined(<strong>VM</strong>) || defined(MVS)} else if (strcmp(argv]i[,"-inet") == 0) {use_iucv = 0;} else if (strcmp(argv]i[,"-iucv") == 0) {use_iucv = TRUE;} else if (strcmp(argv]i[,"-u") == 0) {Chapter 9. SNMP Agent Distributed Program Interface 355


Client Sample Programuse_iucv = TRUE; /* -u implies -iucv */i++;if (argc > i) {dpi_userid = argv]i[;}#endif} else if (strcmp(argv]i[,"?") == 0) {usage(argv]0[, 0);} else {if (hname == NULL) hname = argv]i[;else if (cname == NULL) cname = argv]i[;else usage(argv]0[, 1);}}if (hname == NULL) hname = LOOPBACK; /* use default */if (cname == NULL) cname = PUBLIC_COMMUNITY_NAME; /* use default */#if defined(<strong>VM</strong>) || defined(MVS)if (dpi_userid == NULL) dpi_userid = SNMPAGENTUSERID;if (debug_lvl > 2)printf("hname=%s, cname=%s, userid=%s\n",hname,cname,dpi_userid);#elseif (debug_lvl > 2)printf("hname=%s, cname=%s\n",hname,cname);#endifif (use_iucv != TRUE) {DO_ETOA(cname); /* for <strong>VM</strong> or MVS */dpi_port = query_DPI_port(hname,cname);DO_ATOE(cname); /* for <strong>VM</strong> or MVS */if (dpi_port == -1) {printf("No response from agent at %s(%s)\n",hname,cname);exit(1);}} else dpi_port == -1;dpi_hostname = hname;}#ifdef _NO_PROTO /* for classic K&R C */static void usage(pname, exit_rc)char *pname;int exit_rc;#else /* _NO_PROTO */ /* for ANSI-C compiler */static void usage(const char *pname, const int exit_rc)#endif /* _NO_PROTO */{printf("Usage: %s ]-d debug_lvl[ ]-trap g_type s_type data[", pname);printf(" ]-all_traps[\n");printf("%*s]-trape g_type s_type enterprise data1 data2 .. datan[\n",strlen(pname)+8,"");printf("%*s]-std_traps[ ]-ent_traps[ ]-ent_trapse[\n",strlen(pname)+8,"");#if defined(<strong>VM</strong>) || defined(MVS)printf("%*s]-iucv[ ]-u agent_userid[\n",strlen(pname)+8, "");printf("%*s", strlen(pname)+8, "");printf("]-inet[ ]agent_hostname ]community_name[[\n");printf("default: -d 0 -iucv -u %s\n", SNMPAGENTUSERID);printf(" -inet %s %s\n", LOOPBACK, PUBLIC_COMMUNITY_NAME);#elseprintf("%*s]agent_hostname ]community_name[[\n",strlen(pname)+8,"");printf("default: -d 0 %s %s\n", LOOPBACK, PUBLIC_COMMUNITY_NAME);#endifexit(exit_rc);}#ifdef _NO_PROTO /* for classic K&R C */static void init_variables() /* initialize our variables */#else /* _NO_PROTO */ /* for ANSI-C compiler */static void init_variables(void) /* initialize our variables */356 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Client Sample Program#endif /* _NO_PROTO */{char ch, *cp;}ostring = (char *)malloc(strlen(OSTRING) +4+1);bcopy(OSTRING,ostring,strlen(OSTRING));ostring_len = strlen(OSTRING);for (ch=1;ch


Client Sample Program}DO_ERROR("init_connection: socket");exit(1);}rc = connect(dpi_fd, sa, sasize); /* connect to agent */if (rc != 0) { /* exit on error */DO_ERROR("init_connection: connect");close(dpi_fd);exit(1);}#ifdef _NO_PROTO /* for classic K&R C */static void dump_bfr(buf, len) /* hex dump buffer */char *buf;int len;#else /* _NO_PROTO */ /* for ANSI-C compiler */static void dump_bfr(const char *buf, const int len)#endif /* _NO_PROTO */{register int i;}if (len == 0) printf(" empty buffer\n"); /* buffer is empty */for (i=0;i= ’0’) && (*hostname h_addr_list]0[);ret_addr = addr->s_addr;}return(ret_addr);Compiling and Linking the DPISAMPLE.C Source CodeWhen compiling the Sample DPI Subagent program you may specify the followingcompile time flags:NO_PROTOThe DPISAMPLE.C code assumes that it is compiled with an ANSI-Ccompliant compiler. It can be compiled without ANSI-C by defining thisflag.<strong>VM</strong>Indicates that compilation id for <strong>VM</strong> and uses <strong>VM</strong>-specific includes. Some<strong>VM</strong>/MVS specific code is compiled.358 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Chapter 10. SMTP Virtual Machine InterfacesSMTP TransactionsElectronic mail (e-mail) is prepared using local mail preparation facilities (or, useragents) such as the CMS NOTE and SENDFILE commands; these facilities are notdiscussed here. This chapter describes the interfaces to the SMTP virtual machineitself, and may be of interest to users who implement electronic mail programs thatcommunicate with the <strong>IBM</strong> z/<strong>VM</strong> implementation of SMTP.The interfaces to the SMTP virtual machine are:v The <strong>TCP</strong>/<strong>IP</strong> networkSMTP commands and replies can be sent and received interactively over a <strong>TCP</strong>network connection. Mail from <strong>TCP</strong> network sites destined for local <strong>VM</strong> users(or users on an RSCS network attached to the local z/<strong>VM</strong> system) arrives overthis interface. All commands and data received and transmitted through thisinterface must be composed of ASCII characters.v The local z/<strong>VM</strong> system (and systems attached to the local z/<strong>VM</strong> system by anRSCS network)SMTP commands can be written to a batch file and then spooled to the virtualreader of the SMTP virtual machine. SMTP processes each of the commands inthis file, in order, as if they had been transmitted over a <strong>TCP</strong> connection. This ishow mail is sent from local z/<strong>VM</strong> users (or users on an RSCS network attachedto the local z/<strong>VM</strong> system) to recipients on the <strong>TCP</strong> network. Batch SMTP (or,BSMTP) files must contain commands and data composed of EBCDIC characters.Electronic mail is sent by a series of request/response transactions between aclient, the sender-SMTP, and a server, the receiver-SMTP. These transactions pass (1)the message proper, which is composed of a header and a body (which by definition,are separated by the first blank line present in this information), and (2) SMTPcommands, which are referred to as (and comprise) the mail envelope. Thesecommands contain additional information about the mail, such as the host sendingthe mail and its source and destination addresses. Envelope addresses may bederived from information in the message header, supplied by the user interface, orderived from local configuration information.The SMTP envelope is constructed at the sender-SMTP site. If this is the originatingsite, the information is typically provided by the user agent when the message isfirst queued for the sender-SMTP program. Each intermediate site receives the pieceof mail and resends it on to the next site using an envelope that it creates. Thecontent of the new envelope may be different from that of the one it received.The envelope contains, at a minimum, the HELO or EHLO, MAIL FROM:, RCPTTO:, DATA, and QUIT commands. These, and other commands that can optionallyappear in the envelope, are described in the next section. Some of these commandscan appear more than once in an envelope. Also, more than one piece of mail canbe sent using a given envelope.© Copyright <strong>IBM</strong> Corp. 1987, 2001 359


SMTP Virtual Machine InterfacesSMTP CommandsThis section describes SMTP commands that are recognized by the z/<strong>VM</strong> SMTPimplementation. These commands are used to interface with user agent mailfacilities (such as the CMS NOTE and SENDFILE commands) as well as with otherSMTP servers.For more complete information about SMTP and the commands that can be usedwith this protocol, it is suggested that you review the following RFCs:v RFC 821, Simple Mail Transfer Protocolv RFC 822, Standard for the Format of ARPA Internet Text Messagesv RFC 1869, SMTP Service Extensionsv RFC 1870, SMTP Service Extension for Message Size Declarationv RFC 1652, SMTP Service Extension for 8bit-MIME transportThese RFCs are the basis for modern naming specifications associated with theSMTP protocol.Note: The SMTP commands SEND, SOML, SAML, and TURN are not supportedby the z/<strong>VM</strong> SMTP implementation, so are not described here.HELOThe HELO command is used to identify the domain name of the sending host toSMTP. This command is used to initiate a mail transaction, and must be sent (once)before a MAIL FROM: command is used.►► HELO domain_name ►◄Parameterdomain_nameDescriptionSpecifies the domain name of the sending host. The domain_namemay be specified as either:v a domain namevvan <strong>IP</strong> address in decimal integer form that is prefixed by thenumber or (US) pound sign (“#” or X'7B')an <strong>IP</strong> address in dotted-decimal form, enclosed in brackets.When HELO commands are received over a <strong>TCP</strong> connection, SMTP replies withthe message 250 SMTP_server_domain is my domain name. The SMTP server clientverification exit or built-in client verification function can be used to determine ifthe provided domain_name matches the client <strong>IP</strong> address and to include the resultof that determination in the mail headers. See <strong>TCP</strong>/<strong>IP</strong> Planning and Customizationfor detailed information about configuring SMTP to use this support.When HELO commands are received over a batch SMTP connection, SMTP replieswith the message 250 SMTP_server_domain is my domain name. Additional text isincluded with this message that indicates whether the provided domain_name doesor does not match the host name of the spool file origination point. The 250 replycode indicates the HELO command is accepted and that SMTP commands cancontinue to be sent and received.360 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


EHLOSMTP Virtual Machine InterfacesThe EHLO command operates and can be used in the same way as the HELOcommand. However, it additionally requests that the returned reply shouldidentify specific SMTP service extensions that are supported by the SMTP server.►► EHLO domain_name ►◄Parameterdomain_nameDescriptionSpecifies the domain name of the sending host. The domain_namemay be specified as either:v a domain namev an <strong>IP</strong> address in decimal integer form that is prefixed by thenumber or (US) pound sign (“#” or X'7B')v an <strong>IP</strong> address in dotted-decimal form, enclosed in brackets.If a server does not support SMTP service extensions, the client receives a negativereply to its EHLO command. When this occurs, the client should either supply aHELO command, if the mail being delivered can be processed without the use ofSMTP service extensions, or it should end the current mail transaction.If a client receives a positive response to an EHLO command, the server is thenknown to support one or more SMTP service extensions. This reply then can befurther used by the client to determine whether certain kinds of mail can beeffectively processed by that server.For example, if the positive response includes the SIZE keyword, the serversupports the SMTP service extension for Message Size Declaration. Whereas, if thisresponse includes the 8BITMIME keyword, the server supports the SMTP serviceextension for 8-bit MIME transport.SMTP supports the following service extensions:EXPN HELP SIZE 8BITMIMEFollowing is an example of a positive reply to a client (c) EHLO command from anSMTP server (s) that supports these service extensions:s: (wait for connection on <strong>TCP</strong> port 25)c: (open connection to server)s: 220 HOSTA.<strong>IBM</strong>.COM running <strong>IBM</strong> <strong>VM</strong> SMTP Level 320 on Sat, 1 May 99 ...c: EHLO HOSTB.<strong>IBM</strong>.COMs: 250-HOSTA.<strong>IBM</strong>.COM is my domain name.s: 250-EXPNs: 250-HELPs: 250-8BITMIMEs: 250 SIZE 524288...The hyphen (-), when present as the fourth character of a response, indicates theresponse is continued on the next line.MAIL FROMThe MAIL FROM: command is used (once), after a HELO or EHLO command, toidentify the sender of a piece of mail.Chapter 10. SMTP Virtual Machine Interfaces 361


SMTP Virtual Machine Interfaces►►MAIL FROM: SIZE=number_of_bytesBODY=7BITBODY=8BITMIME►◄Parametersender_path_addressSIZE=number_of_bytesBODY=7BITBODY=8BITMIMEDescriptionSpecifies the full path address of the sender of themail. Definitions for valid sender_path_addressspecifications can be obtained from the RFCs thatdefine the naming conventions used throughoutthe Internet. For detailed information, consult theRFCs listed in the section “SMTP Commands” onpage 360.Specifies the size of the mail, in bytes, includingcarriage return/line feed (CRLF, X'0D0A') pairs. TheSIZE parameter has a range from 0 to 2,147,483,647.Specifies that the message is encoded using sevensignificant bits per 8-bit octet (byte). In practice,however, the body is typically encoded using alleight bits.Specifies that the message is encoded using alleight bits of each octet (byte) and may containMIME headers.Note: The SIZE, BODY=7BIT, and BODY=8BITMIME options of the MAIL FROM:command should be used only if an EHLO command was used to initiate amail transaction. If an EHLO command was not used for this purpose,SMTP ignores these parameters if they are present.If the SMTP server is known to support the SMTP service extension for MessageSize Declaration, the client sending the mail can specify the optional SIZE=parameter with its MAIL FROM: commands. The client then can use the responsesto these commands to determine whether the receiving SMTP server has sufficientresources available to process its mail before any data is transmitted to that server.When a MAIL FROM: command is received that includes the optional SIZE=parameter, the SMTP server compares the supplied number_of_bytes value to itsallowed maximum message size (defined by the MAXMAILBYTES statement in theSMTP CONFIG file) to determine if the mail should be accepted. If number_of_bytesexceeds the MAXMAILBYTES value, a reply code 552 is returned to the client.The SIZE= parameter is evaluated only for MAIL FROM: commands received overa <strong>TCP</strong> connection; this parameter and its value are ignored when they are receivedover a batch connection.RCPT TOThe RCPT TO: command specifies the recipient(s) of a piece of mail. Thiscommand can be repeated any number of times.►► RCPT TO: ►◄362 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


SMTP Virtual Machine InterfacesParameterrecipient_path_addressDescriptionSpecifies the full path address of a mail recipient.Definitions for valid recipient_path_addressspecifications can be obtained from the RFCs thatdefine the naming conventions used throughoutthe Internet. For detailed information, consult theRFCs listed in the section “SMTP Commands” onpage 360.A RCPT TO: command must be used after a MAIL FROM: command. If the hostsystem is not aware of the recipient’s host, a negative reply is returned in responseto the RCPT TO: command.DATAThe DATA command indicates that the next information provided by the clientshould be construed as the text of the mail being delivered (that is, the header andbody of the mail message).►► DATA ►◄The DATA command has no parameters.The DATA command is used after a HELO or EHLO command, a MAIL FROM:command, and at least one RCPT TO: command have been accepted. When theDATA command has been accepted, the following response (reply code 354) isreturned to indicate that the body of the mail can be transmitted:354 Enter mail body. End new line with just a ’.’The body of the mail is terminated by transmitting a single ASCII period (.) on aline by itself. When SMTP detects this “end of data” indicator, it returns thefollowing reply:250 Mail DeliveredWhen mail is received over a <strong>TCP</strong> connection, this ASCII period should befollowed by the ASCII CR-LF sequence (carriage return/line feed sequence, X'0D0A').If any record in the body of the mail begins with a period, the sending SMTPprogram must convert the period into a pair of periods (..). Then, when thereceiving SMTP encounters a record in the body of the mail that begins with twoperiods, it discards the leading period. This convention permits the mail body tocontain records that would otherwise be incorrectly interpreted as the “end ofdata” indicator. These rules must be followed over both <strong>TCP</strong> and batch SMTPconnections. The CMS NOTE and SENDFILE execs perform this period doublingon all mail spooled to SMTP. If the body of the mail in a batch SMTP commandfile is not explicitly terminated by a record with a single period, SMTP suppliesone.After the “end of data” indicator has been received, the SMTP connection is resetto its initial state (that is, the state before any sender or recipients have beenspecified). Additional MAIL FROM:, RCPT TO:, DATA, and other commands canagain be sent. If no further mail is to be delivered through this connection, theconnection should then be terminated with a QUIT command. If the QUITcommand is omitted from the end of a batch SMTP command file, the QUIT isimplicit — SMTP will proceed as if it had been provided.Chapter 10. SMTP Virtual Machine Interfaces 363


SMTP Virtual Machine InterfacesIf SMTP runs out of local mail storage space, it returns a 451 reply code to thesender-SMTP client. Local mail storage space is constrained by the size of theSMTP server A-disk (191 minidisk). For a large batch SMTP file, disk storageequivalent to four times the size of that file may be required for it to be processedby SMTP.If the body of the mail being delivered is found to exceed the MAXMAILBYTESvalue established in the SMTP CONFIG file, a reply code 552 is returned to theclient. See the <strong>TCP</strong>/<strong>IP</strong> Planning and Customization for more information about theMAXMAILBYTES configuration statement.When mail arrives over a batch SMTP connection from an RSCS network host, andthe REWRITE822HEADER configuration option was specified in the SMTPconfiguration file, then header fields are modified to ensure that all addresses arefully qualified domain names. See the <strong>TCP</strong>/<strong>IP</strong> Planning and Customization for moreinformation about the header rewriting.RSETThe RSET command resets an SMTP connection to an initial state. That is, allinformation about the current mail transaction is discarded, and the connection isready to process a new mail transaction.►► RSET ►◄The RSET command has no parameters.QUITThe QUIT command terminates an SMTP connection.►► QUIT ►◄NOOPThe QUIT command has no parameters.The NOOP command has no intrinsic function. However, it will cause thereceiver-SMTP to return an “OK” response (reply code 250).►► NOOP ►◄The NOOP command has no parameters.HELPThe HELP command returns brief information about one or more SMTPcommands.364 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


SMTP Virtual Machine Interfaces►►HELPcommand_name►◄QUEUParameter Descriptioncommand_name Identifies a specific SMTP command.The HELP command returns a multiple-line reply with brief help informationabout the SMTP commands supported by a host. If an SMTP command is specifiedfor command_name, information about that specific command is returned.The QUEU command returns a multiple-line reply with information about thecontent of the mail processing queues maintained within the SMTP server.►►QUEUDATE►◄ParameterDATEDescriptionCauses information about the age of any queued mail to beincluded in the QUEU command response. By default, ageinformation is not included in such responses.The z/<strong>VM</strong> SMTP server maintains various internal queues for handling mail, thatcan be generalized to two categories — the mail (delivery) queues, and the mailresolution (or, resolver) queues. The QUEU command returns a multiple-line replywith information about the content of these queues, which are described in moredetail here.Mail Delivery Queues:Queue Name DescriptionSpool Contains mail that is destined for recipients on the local z/<strong>VM</strong>system, or for recipients on an RSCS system attached to the localz/<strong>VM</strong> system. This queue is generally empty, because SMTP candeliver this mail quickly by spooling it directly to the localrecipient, or to the RSCS virtual machine for delivery to an RSCSnetwork recipient.Active Identifies mail that is currently being transmitted by SMTP to a<strong>TCP</strong> network destination. All mail queued for that samedestination is shown to be Active.Queued Identifies mail that has arrived over either a <strong>TCP</strong> or batch SMTPconnection that is to be forwarded to a <strong>TCP</strong> network destination(possibly because of source routing). When SMTP obtains sufficientresources from the <strong>TCP</strong><strong>IP</strong> virtual machine to process this mail, it istransferred to the Active queue.Retry Identifies mail for which SMTP has made one or more previousdelivery attempts that were not successful. Delivery attempts mayfail for a variety of reasons; two common reasons are:Chapter 10. SMTP Virtual Machine Interfaces 365


SMTP Virtual Machine InterfacesvThe SMTP server could not open a connection to deliver themail.v Delivery of the mail was interrupted for some reason, such as abroken connection or a temporary error condition at the targethost.After the RETRYINT interval (defined in the SMTP CONFIG file)has passed, mail in the Retry queue is promoted to the Queuedqueue (or state) for another delivery attempt. For more informationabout the RETRYINT configuration parameter, see the <strong>TCP</strong>/<strong>IP</strong>Planning and Customization.Undeliverable Identifies mail that SMTP cannot deliver to a local z/<strong>VM</strong> recipient,or to a recipient on the RSCS network attached to the local <strong>VM</strong>system, due to insufficient spooling resources on the local z/<strong>VM</strong>system. After spool space has been increased and SMTP has beenreinitialized, delivery of this mail is again attempted.Mail Resolution Queues:The mail resolution (or, resolver) queues are used to maintain the status of hostresolution queries — performed through DNS services — for mail host domains,originators, and recipients, when such resolution is necessary. If the SMTP server isconfigured to not use a name server, but only local host tables, these queues arenot used.Several notes regarding the response information associated with mail resolutionqueues follow:vvIf a queue is empty the word Empty appears in the response, to the right of thename of that queue.If a queue contains active queries, a line that identifies that queue will bepresent; information about the mail in that queue, and its associated query (orqueries) is provided immediately after this identification line.v Because of timing situations that can occur within the SMTP server, a queueidentification line may at times show that a queue is active (that is, Empty is notindicated), but no mail entries will be present.Queue Name DescriptionProcessSendWaitThis queue is generally empty, as it contains queries that have notyet been acted upon by the SMTP server. Once a query has beeninitially processed, it is placed in the Resolver Send queue.Identifies queries that are awaiting SMTP resolver processing.SMTP staggers the number of queries it submits to a name sever,to prevent overloading the network and the name server.Identifies queries for which the SMTP server is waiting a responsefrom a name server. Queries remain in this queue for a specificamount of time, within which a reply should be received from thename server.If a query is successful, that query is then placed in the ResolverCompleted queue.If a reply is not received for a query within the allotted time (thatis, the resolver time-out has expired), that query is removed fromthis queue and placed in the Resolver Retry queue.366 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


SMTP Virtual Machine InterfacesNote: The duration of the resolver time-out period can becontrolled using the <strong>TCP</strong><strong>IP</strong> DATA file RESOLVERTIMEOUTconfiguration statement. See the <strong>TCP</strong>/<strong>IP</strong> Planning andCustomization for more information about this statement.RetryIdentifies queries that have previously failed, possibly because:v a name server response was not received for a query (within thedesignated time-out period), orv the name server returned a temporary error that has forced theSMTP server to retry a query. A temporary error occurs if, forexample, the name server truncates a packet, or if the nameserver detects a processing error.Note: Mail for which queries are present in this queue can besignificantly affected by the values defined for theRESOLVERRETRYINT and RETRYAGE configurationstatements in the SMTP CONFIG file. See the <strong>TCP</strong>/<strong>IP</strong>Planning and Customization for more information about thesestatements.CompletedErrorIdentifies queries that have been resolved and are waiting to berecorded by SMTP (and, possibly incorporated within a piece ofmail). After the resolved information has been recorded, SMTPattempts to deliver the mail.Identifies queries for which a name server response was obtained,but for which no answer was obtained. Mail that corresponds tosuch queries is returned to the originator as undeliverable, with anunknown recipient error indicated.VRFYThe VRFY (“verify”) command determines if a given mailbox or user ID exists onthe host where SMTP is running.►► VRFYverify_string ►◄Parameterverify_stringDescriptionSpecifies the name of a mailbox or user ID whose existence is to beverified.The z/<strong>VM</strong> implementation of SMTP responds to the VRFY command and theEXPN command (see the EXPN command below) in the same manner. Thus, theVRFY command can be used with z/<strong>VM</strong> systems to expand a mailing list definedon such system; when this is done, a multiple-line reply may be returned inresponse to the VRFY command.The VRFY command can also be used to verify the existence of the POSTMASTERmailbox or mailboxes defined for a system.On z/<strong>VM</strong> systems, mailing lists are defined by the site administrator and arestored in the SMTP NAMES file; POSTMASTER mailboxes are defined by thePOSTMASTER configuration statement in the SMTP CONFIG file. See the <strong>TCP</strong>/<strong>IP</strong>Planning and Customization for more information about defining mailing lists andspecifying POSTMASTER mailboxes.Chapter 10. SMTP Virtual Machine Interfaces 367


SMTP Virtual Machine InterfacesSome example VRFY commands (issued against an SMTP server running on hostTEST<strong>VM</strong>1 at “somewhere.com”) and their corresponding responses follow:vrfy tcpmaint 250 vrfy tcpadmin-list 250-250-250-250 vrfy postmaster 250-250-250 The hyphen (-), when present as the fourth character of a response, indicates theresponse is continued on the next line.EXPNThe EXPN (“expand”) command expands a mailing list defined on the host whereSMTP is running.►► EXPNexpand_string ►◄Parameterexpand_stringDescriptionSpecifies the name of the mailing list to be expanded.The EXPN command operates and can be used in the same way as the VRFYcommand.VERBThe VERB command is used to enable or disable “verbose” mode for batch SMTPconnections.►►VERBOFFON►◄ParameterONOFFDescriptionSpecifies that verbose mode is to be enabled (turned on). Whenverbose mode is enabled for a batch SMTP connection, SMTPcommands and their associated replies are recorded in a batchSMTP response file; this file is sent back to the origination point ofthe batch SMTP command file when the batch transaction iscomplete.Specifies that verbose mode is to be disabled (turned off); this isthe default. When verbose mode is disabled for a batch SMTPconnection, only SMTP replies are recorded in the batch SMTPresponse file; this file is not returned to the origination point of thebatch SMTP command file.See “SMTP Command Responses” on page 369 for more information about thebatch SMTP response file, how this file is handled, and how origination points aredetermined.368 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


SMTP Virtual Machine InterfacesNote: The VERB command has no effect when issued over a <strong>TCP</strong> connection.TICKThe TICK command can be used (in conjunction with the VERB ON command) tocause an identifier string to be inserted into a batch SMTP response file.►► TICK identifier ►◄ParameteridentifierDescriptionSpecifies an identification string to be included in a batch SMTPresponse file.SMTP Command ExampleSMTP Command ResponsesThis command can be useful for some mail systems that keep track of batch SMTPresponse files and their content.Note: The TICK command has no effect when it is issued over a <strong>TCP</strong> connection.The following is an example of an SMTP envelope and its contained piece of mail.The SMTP commands that comprise the envelope are in upper case boldface text.The information after the DATA command, and before the single ASCII period (the“end of data” indicator) is the message header and body. The body is distinguishedfrom the header by the blank line that follows the “Subject: Update” line of text.HELO yourhost.yourdomain.eduMAIL FROM: RCPT TO: RCPT TO: DATADate: Sun, 30 Nov 98 nn:nn:nn ESTFrom: Carol To: Cc: Subject: UpdateMike: Cindy stubbed her toe. Bobby went tobaseball camp. Marsha made the cheerleading team.Jan got glasses. Peter has an identity crisis.Greg made dates with 3 girls and couldn'tremember their names..QUITThe z/<strong>VM</strong> SMTP server can accept SMTP commands that arrive over a <strong>TCP</strong>connection or over a batch SMTP (BSMTP) connection. With either type ofconnection, a response (or, reply) is generated for each command received bySMTP. Each reply is prefixed with a three-digit number, or code. The nature ofeach response can be determined by inspecting the first digit of this reply code;possible values for this digit are:Digit Description0 Echo reply; used only in batch SMTP response files. Receivedcommands are “echoed” in these files to provide contextualinformation for other reply codes.Chapter 10. SMTP Virtual Machine Interfaces 369


SMTP Virtual Machine InterfacesPath Address Modifications1 Positive Preliminary reply. SMTP does not use a1asthefirst digitof a reply code, because there are no SMTP commands for whichsuch a reply is applicable.2 Positive Completion reply; command accepted.3 Positive Intermediate reply; data associated with the commandshould now be provided.4 Temporary Negative Completion reply; try the command again,but at a later time.5 Permanent Negative Completion reply; the command has beenrejected.For SMTP commands that arrive over a <strong>TCP</strong> connection, all responses (positive ornegative) are returned over that <strong>TCP</strong> connection.Similarly, for SMTP commands that arrive over a batch SMTP connection, allresponses are written to a batch SMTP response file. If verbose mode is enabled fora batch SMTP connection (through use of the VERB ON command), SMTP returnsthis response file to the origination point of the spool file. The origination point isdetermined either from the ORIGINID field of the spool file (if the spool file wasgenerated on the same z/<strong>VM</strong> system as the SMTP virtual machine) or from thespool file TAG field (if the spool file arrived from a remote system through theRSCS network). If the batch SMTP connection is not in verbose mode, the batchSMTP response file is not returned to the point of origin.If an error occurs during the processing of commands over a batch SMTPconnection, such as reception of a negative response (with a first digit of 4 or 5), anerror report is mailed back to the sender of the mail. The sender is determinedfrom the last valid MAIL FROM: command that was received by SMTP. If thesender cannot be determined from a MAIL FROM: command, the sender isassumed to be the origination point of the batch SMTP command file. The errorreport mailed to the sender includes the batch SMTP response file and the text ofthe undeliverable mail.Note: All SMTP commands and data that arrive over <strong>TCP</strong> or batch SMTPconnections are subject to the restrictions imposed by both SMTPconventions and constants defined in either the SMTPGLOB COPY file, orwithin other SMTP source files. Any changes made to these files toovercome a restriction will require the affected source files to be recompiled,and the SMTP module to be rebuilt. Several significant restrictions, therelevant constants, and their default values are:v Command lines must not exceed MaxCommandLine (552 characters).v Data lines longer than MaxDataLine (1024 characters) are wrapped.v Path addresses must not exceed MaxPathLength (256 characters).v Domain names must not exceed MaxDomainName (256 characters).vUser names, the local part of a mailbox specification, must not exceedMaxUserName (256 characters).When SMTP processes MAIL FROM: and RCPT TO: commands, the path addressesspecified with these commands may be modified by SMTP due to use of theSOURCEROUTES configuration statement, or based on the content of the pathaddresses themselves. See the <strong>TCP</strong>/<strong>IP</strong> Planning and Customization for more370 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Batch SMTP Command FilesBatch SMTP Examplesinformation about the SOURCEROUTES statement and its affect on path addresses.For content-based changes, certain path addresses will be rewritten by SMTP asfollows:1. If the local part of a mailbox name includes a percent sign (%) and the domainof the mailbox is that of the host system where SMTP is running, the givendomain name is eliminated, and the portion of the “local part” to the right ofthe percent sign (%) is used as the destination domain. For example, the pathaddress:john%yourvm@ourvm.our.eduis rewritten by SMTP running at “ourvm.our.edu” as:john@yourvm2. Path addresses with source routes are accepted and rewritten to remove thedomain name of the host system where SMTP is running. For example, thepath address:@ourvm.our.edu,@next.host.edu:john@yourvmis rewritten by SMTP running at “ourvm.our.edu” as:@next.host.edu:john@yourvmDefinitions for “valid path format” specifications can be obtained from the RFCsthat define the naming conventions used throughout the Internet. For detailedinformation, consult the RFCs listed in the section “SMTP Commands” onpage 360.Batch SMTP command files are files that contain an SMTP envelope (as describedin “SMTP Transactions” on page 359) which are sent to the virtual reader of theSMTP virtual machine using the CMS PUNCH, DISK DUMP, SENDFILE, orNETDATA SEND commands. For a description of these commands, see the z/<strong>VM</strong>:CMS Command <strong>Reference</strong>. These files are encoded using EBCDIC.Batch SMTP command files can be sent by users on the same z/<strong>VM</strong> system, or anysystem connected through an RSCS network. For information about RSCSnetworks, see the RSCS General Information.Batch SMTP files may be modified when they are processed by the SMTP server, asfollows:vvSMTP Virtual Machine InterfacesAll trailing blanks are removed from each record of a file sent in PUNCHformat. Trailing blanks are preserved for files send in NETDATA or DISK DUMPformat.A record that is entirely blank will be treated as a record with a single blank.The following sections contain examples that demonstrate batch SMTP capabilities.Sending Mail to a <strong>TCP</strong> Network RecipientThe example that follows shows the content of a batch SMTP file used to send mailfrom a CMS user (CAROL at YOURHOST) to two <strong>TCP</strong> network recipients. The VERBON command will cause a batch SMTP response file to be returned to the CMSuser CAROL. The text included with the TICK command will appear in this file aswell, so that the nature of the response file will be evident when it is returned.Chapter 10. SMTP Virtual Machine Interfaces 371


SMTP Virtual Machine InterfacesVERB ONTICK Carol's Batch Test FileHELO yourhost.yourdomain.eduMAIL FROM: RCPT TO: RCPT TO: DATADate: Sun, 30 Nov 98 nn:nn:nn ESTFrom: Carol To: Cc: Subject: UpdateMike: Cindy stubbed her toe. Bobby went tobaseball camp. Marsha made the cheerleading team.Jan got glasses. Peter has an identity crisis.Greg made dates with 3 girls and couldn'tremember their names..QUITWith the exception of the VERB and TICK commands, this sample batch SMTP filecontains commands that are identical to those shown in “SMTP CommandExample” on page 369.Following is the batch SMTP response file (BSMTP REPLY) produced for theprevious command file:220-YOURHOST.YOURDOMAIN.EDU running <strong>IBM</strong> <strong>VM</strong> SMTP Level 320 on Sun, 30 Nov 1998 nn220 :nn:n EST050 VERB ON250 Verbose Mode On050 TICK Carol's Batch Test File250 OK050 HELO yourhost.yourdomain.edu250 YOURHOST.YOURDOMAIN.EDU is my domain name. Yours too, I see!050 MAIL FROM: 250 OK050 RCPT TO: 250 OK050 RCPT TO: 250 OK050 DATA354 Enter mail body. End by new line with just a '.'250 Mail Delivered050 QUIT221YOURHOST.YOURDOMAIN.EDU running <strong>IBM</strong> <strong>VM</strong> SMTP Level 320 closing connectionQuerying SMTP Delivery QueuesThe SMTP delivery queues can be queried by sending a file that contains VERBON and QUEU commands to the SMTP virtual machine. A batch SMTP responsefile that contains the QUEU command results is then returned to the originatinguser ID.The SMTPQUEU EXEC (supplied with <strong>TCP</strong>/<strong>IP</strong> Function Level 320 on the<strong>TCP</strong>MAINT 592 “Client-code” minidisk) generates such a file and sends it to theSMTP virtual machine.Sample content for a BSMTP REPLY file returned in response to an SMTPQUEUcommand follows:372 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


SMTP Exit RoutinesClient Verification ExitSMTP Virtual Machine Interfaces220-YOURHOST.YOURDOMAIN.EDU running <strong>IBM</strong> <strong>VM</strong> SMTP Level 320 on Sun, 30 Nov 1998 nn220 :nn:n EST050-VERB ON050250 Verbose Mode On050-QUEU050250-Queues on YOURHOST.YOURDOMAIN.EDU at nn:nn:nn EST on 11/30/98250-Spool Queue: Empty250-Queue for Site: 123.45.67.89 RETRY QUEUE Last Tried: nn:nn:nn250-Note 00000005 to 250-Queue for Site: 98.76.54.32 RETRY QUEUE Last Tried: nn:nn:nn250-Placeholder...no files queued for this site250-Undeliverable Queue: Empty250-Resolution Queues:250-Resolver Process Queue: Empty250-Resolver Send Queue: Empty250-Resolver Wait Queue:250-00000013 250-Resolver Retry Queue: Empty250-Resolver Completed Queue: Empty250-Resolver Error Pending Queue: Empty250 OKThe SMTP user exits described in the next sections allow you greater control overeach piece of mail that is processed by the SMTP server. To effectively use theseexits and their parameters, it is necessary to understand SMTP transactions. Referto the previous sections in this chapter for information about the commands,messages, and replies that are used to facilitate e-mail transactions between thesender and receiver of a piece of mail.When a client connects to SMTP, the originating mail domain must be provided.The client verification exit can be used to verify that the domain name provided bya client matches that client’s <strong>IP</strong> address. Thus, this exit allows flexibility on actionsyou can take to deal with spoofing problems. In spoofing, the client provides afalsified domain in order to cause mail to appear to have come from someone (orsomewhere) else. When client verification is performed, you might choose toinclude the verification results in mail headers, or possibly reject futurecommunications on a connection.With the client verification exit, you can perform any or all of the following:v Reject mail from a particular host.v Mark certain trusted sites as verified, but perform verification on all others.v Control which users can use a particular SMTP server.The exit can be further customized to perform additional actions that are unique orrequired for your environment.Note: The client verification exit is called for each HELO or EHLO commandprocessed for each mail item received from the network. Client verificationis not performed for mail items received from the SMTP virtual reader.Built-in Client Verification FunctionIn addition to the exit, SMTP can be configured to perform client verificationthrough internal processing. When this support is enabled, this “built-in” clientChapter 10. SMTP Virtual Machine Interfaces 373


SMTP Virtual Machine Interfacesverification function will be called for each HELO or EHLO processed for eachmail item. See the <strong>TCP</strong>/<strong>IP</strong> Planning and Customization for detailed information aboutconfiguring SMTP to use this support.The built-in client verification function of the SMTP server can be used todetermine if a client host name and client <strong>IP</strong> address match, and to include theresult of that determination in the mail headers. This function will perform a DNSlookup against the HELO or EHLO command data provided by a client, and willthen insert a message into the mail header that reflects the result of this lookup.Client verification performed using the built-in function has three possibleoutcomes:SuccessThe data the client provided in the HELO or EHLO command corresponds to theclient address. The following line is inserted into the mail header:X-Comment: localhost: Mail was sent by hostFailureThe data the client provided in the HELO or EHLO command is not associatedwith the client <strong>IP</strong> address. In this case, a reverse name lookup is done against theclient <strong>IP</strong> address to determine the actual host name. The following line is insertedinto the mail header:X-Comment: localhost: Host host claimed to be helodataUnknownThe validation could not be performed. This situation could occur if the nameserver is not responding, or the verification could not be performed in the allottedtime (as controlled by the VERIFYCLIENTDELAY statement). The following line isinserted into the mail header:X-Warning: localhost: Could not confirm that host [ipaddr] ishelodataThe terms used in the previously listed mail header messages are described inmore detail here:localhostthe local <strong>VM</strong> host namehelodatathe data the client provided with the HELO or EHLO commandhost the host name determined by the reverse DNS lookup; if a host name isnot found, “unknown host” will be usedipaddrthe client <strong>IP</strong> address.Client Verification Exit Parameter ListsThe parameter lists passed to the REXX and the assembler exit routines follow.When you customize either of these exits, keep in mind the following:vvBecause an identical exit parameter list definition is used for all of the SMTPuser exits, not all parameters may be meaningful for this exit. Parameters thatare not used by this exit are indicated in the exit parameter lists; their valuesshould be ignored.For the REXX exit, the value of an unused parameter will be such that anyparsing will not be affected.374 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Parameter descriptions that pertain to both the REXX and assembler exits areprovided on page 376.REXX Parameter ListInputs:Table 72. Client Verification REXX Exit Parameter ListArgumentDescriptionSMTP Virtual Machine InterfacesARG(1)ARG(2)ARG(3)ARG(4-6)Parameter list defined as follows:v Exit typev Version numberv Mail record IDv Port number of SMTP serverv <strong>IP</strong> address of SMTP serverv Port number of clientv <strong>IP</strong> address of clientv Filename of note on diskv Verify Client statusv Maximum length of Return StringSMTP command stringHELO/EHLO nameNot usedOutputs:The following are returned to the caller in the RESULT variable via a REXXRETURN statement:┌────────┬──────────────────────────────┐│ RC │ Return String │└────────┴──────────────────────────────┘ArgumentRCReturn StringDescriptionThe exit return code; this must be a 4-byte binary value.An exit-specified string; the returned value must have a length lessthan or equal to the maximum length passed to the exit.Assembler Parameter ListFollowing is the parameter list that is passed to the assembler exit routine. GeneralRegister 1 points to the parameter list.Table 73. Client Verificaiton ASSEMBLER Exit Parameter ListOffset inDecimalLen In/Out Type Description+0 4 Input Char Exit type+4 4 Input Int Version number+8 4 Input Int Mail record ID+12 4 Input Int Port number of SMTP server+16 4 Input Int <strong>IP</strong> address of SMTP server+20 4 Input Int Port number of client+24 4 Input Int <strong>IP</strong> address of client+28 4 Input Ptr Address of SMTP command string+32 4 Input Int Length of SMTP command stringChapter 10. SMTP Virtual Machine Interfaces 375


SMTP Virtual Machine InterfacesTable 73. Client Verificaiton ASSEMBLER Exit Parameter List (continued)Offset inDecimalLen In/Out Type Description+36 4 Input Ptr Address of HELO/EHLO name+40 4 Input Int Length of HELO/EHLO name+44 24 Not used+68 4 Input Int Verify Client status+72 4 Output Ptr Address of Return String+76 4 Output Int Length of Return String+80 4 Input Int Maximum length of Return String+84 8 Not used+92 4 Input/ Output Char User Word 1+96 4 Input/ Output Char User Word 2+100 4 Output Int Return code from exitParameter DescriptionsExit typeA four-character field that indicates the type of exit called. For the clientverification exit, this is VERX.Version numberThe parameter list version number; if the parameter list format is changed, theversion number will change. Your exit should verify it has received theexpected version number. The current version number is 1.Mail record IDA number that uniquely identifies a piece of mail so that multiple exit calls canbe correlated to the same piece of mail. A value of 0 indicates a mail record IDis not available.Port number of SMTP serverThe port number used by the SMTP server for this connection.<strong>IP</strong> address of SMTP serverFor the REXX exit, a dotted-decimal format <strong>IP</strong> address is provided; for theassembler exit, this is an <strong>IP</strong> address in decimal integer form. For multi-homedhosts, this address can be compared with the client <strong>IP</strong> address to determine inwhich part of the network the client host resides.Port number of clientIf the connection no longer exists, -1 is supplied. Otherwise, this is the portnumber used by the foreign host for this connection.<strong>IP</strong> address of clientFor the REXX exit, a dotted-decimal format <strong>IP</strong> address is provided; for theassembler exit, this is an <strong>IP</strong> address in decimal integer form.SMTP command stringContains the HELO/EHLO command and the domain specified for thiscommand. The string has been converted to uppercase (for example, “HELODOMAIN1”).HELO/EHLO nameA string that contains the name specified on the HELO or EHLO command;this string may be either:v a domain name376 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


v an <strong>IP</strong> address in decimal integer form that is prefixed by the number or (US)pound sign (“#” or X'7B')v an <strong>IP</strong> address in dotted-decimal form, enclosed in brackets.For example, if the command HELO #123456 is provided by an SMTP client, thisparameter would contain #123456.The name has already been verified to have the correct syntax.Verify Client statusA number that indicates client verification results. For this exit, clientverification results are unknown when the exit receives control; thus, this fieldwill contain a 3. Possible values and their meanings are:0 Client verification passed.1 Client verification failed.2 Client verification was not performed.3 Client verification results are unknown.Return StringWhen the exit returns a return code of 3, this value is appended to theX-Comment that is inserted in the mail header. When the exit returns a returncode of 5, the Return String value is appended to the 550 reply code.Maximum length of Return StringThe current maximum is 512 bytes; ensure the Return String length is less thanthis value. If the returned string is longer than the indicated maximum, thereturn string is truncated and the following message is displayed on the SMTPsever console:Return data from exit exitname exittype too long, data truncatedNormal processing continues.User Word 1Provided for use by the assembler exit only. The user word specified uponreturn from this exit will be passed back in this field for any future calls; 0 isthe initial value. The SMTP server does not use this value in any way.User Word 2Provided for use by the assembler exit only. The user word specified uponreturn from this exit will be passed back in this field for any future calls; 0 isthe initial value. The SMTP server does not use this value in any way.Return Codes from the Client Verification Exit RoutineFollowing are the return codes recognized by SMTP for this exit.Table 74. Client Verification Exit Return CodesSMTP Virtual Machine InterfacesReturn Code Explanation0 Do not verify client. A comment will not be inserted in the mail header.1 Perform verification using the built-in client verification function.2 Mark as verified. The following comment will be inserted in the mailheader:X-Comment: localhost: Mail was sent by host3 The following comment will be inserted in the mail header:X-Comment: Return Stringwhere the value for Return String can be specified by the exit.Chapter 10. SMTP Virtual Machine Interfaces 377


SMTP Virtual Machine InterfacesTable 74. Client Verification Exit Return Codes (continued)Return Code Explanation4 Disable the exit. The following message will be displayed on the SMTPconsole:VERIFYCLIENT EXIT function disabledThe exit will no longer be called. The client will not be verified and nocomment will be inserted in the mail header.5 Reject this command with: 550 Return StringIf a return string is not provided by the exit, then the default message willbe displayed:550 Access deniedOtherAll future communications on this connection will be rejected with this 550message.Any return code other than the above causes SMTP to issue this message:Unexpected return from user exit exitname exittype, RC=rcSMTP treats this return code as if it were a return code of 0.||||||||||||||Client Verification Sample ExitsSample Client Verification exit routines are supplied with <strong>TCP</strong>/<strong>IP</strong> on the<strong>TCP</strong>MAINT 591 disk. The supplied samples are:SMTPVERX SEXECREXX exit routine that contains a sample framework for performing clientverification actions. Your customized exit should be stored on the<strong>TCP</strong>MAINT 198 disk as SMTPVERX EXEC.SMTPVERX SAMPASMThe assembler exit routine called by the SMTP server; the exit is used tocall SMTPVERX EXEC and to pass results back to the SMTP server. Yourcustomized exit should be stored on the <strong>TCP</strong>MAINT 198 disk as fileSMTPVERX ASSEMBLE. The customized ASSEMBLE file must beassembled (by using the <strong>VM</strong>FHLASM SMTPVERX DMS<strong>VM</strong> command), and theresulting text deck placed on the <strong>TCP</strong>MAINT 198 disk.These samples are for illustrative purposes only. They should be modified to meetthe needs of your installation before placing them in a production environment.The assembler exit will have better performance characteristics than the REXX exit.For best performance, EXECLOAD any REXX exits.Using the Mail Forwarding ExitWhen SMTP clients use the <strong>VM</strong> SMTP server to send mail to hosts that theirworkstations cannot reach directly, this is an instance of mail forwarding. The mailforwarding exit provides a mechanism to control this activity. When SMTPdetermines the addressee specified on a RCPT TO: command is not “defined on” thelocal system, it has detected mail forwarding, and it will call this exit routine.The phrase “defined on” in the previous paragraph is meant to convey that SMTPconsiders a user to be a local user, in addition to any other criteria, if that user isdefined in the SMTP NAMES file — regardless of whether mail delivery to thatuser is performed via spooling (RSCS services) or through a network <strong>TCP</strong>378 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


connection. Also, keep in mind that the determination of whether mail forwardingis occurring is made on a recipient-by-recipient basis, not on other aspects of agiven piece of mail. A piece of mail with multiple recipients can containoccurrences of both mail forwarding and local delivery.With the mail forwarding exit, you can perform any or all of the following:v Allow mail forwarding and mail delivery to proceed without interruption.v Disallow mail forwarding from a known sender of “junk” mail, and possiblyreject future communications on a connection used for this purpose.v Intercept mail from specific clients and forward that mail to a local <strong>VM</strong> user IDfor further analysis.v Restrict the ability to forward mail to a particular set of hosts.The exit can be further customized to perform additional actions that are requiredfor your environment.Note: The mail forwarding exit is only called for mail items received from thenetwork; it is not called for mail items generated on the <strong>VM</strong> system orreceived via RSCS.This exit can also be used to control spamming. Spamming is the act of sendingmail to a large number of e-mail addressees and is often compared to the term“junk mail”, used to describe similar activities performed via postal services. Spamis a piece of mail that is perceived by the recipients to be unsolicited andunwanted. There are two aspects to consider when trying to control spammingproblems:vIs your system being used to relay spam messages to recipients throughout theinternet?v Are incoming spam messages to your local users seriously taxing or overloadingyour system?The relaying of spam messages may be treated like any other type of mailforwarding. The exit can prevent delivery of all forwarded mail, prevent deliveryof mail from particular sites known for spamming, or only allow delivery of mailfrom particular trusted sites. Handling spam messages directed to your local userswill require the use of the SMTP command exit. When you address spammingproblems, it’s important to realize that one person may consider a piece of mail tobe a spam, while the same piece of mail may be valuable to someone else. Thereare no explicit rules that determine what is and is not spam.In addition to the exit, SMTP can be configured to enable or disable mailforwarding for all mail. If mail forwarding is disabled in this manner and SMTPdetermines the recipient specified on a RCPT TO: record is not defined on the localsystem, it has detected mail forwarding, and it will reject the delivery of the mailto that recipient. See the <strong>TCP</strong>/<strong>IP</strong> Planning and Customization for more informationabout configuring SMTP to accept or reject all forwarded mail.Mail Forwarding Exit Parameter ListsThe parameter lists passed to the REXX and the assembler exit routines follow.When you customize either of these exits, keep in mind the following:vSMTP Virtual Machine InterfacesBecause an identical exit parameter list definition is used for all of the SMTPuser exits, not all parameters may be meaningful for this exit. Parameters thatare not used by this exit are indicated in the exit parameter lists; their valuesshould be ignored.Chapter 10. SMTP Virtual Machine Interfaces 379


SMTP Virtual Machine Interfacesv For the REXX exit, the value of an unused parameter will be such that anyparsing will not be affected.Parameter descriptions that pertain to both the REXX and assembler exits areprovided on page 381.REXX Parameter ListInputs:Table 75. Mail Forwarding REXX Exit Parameter ListArgumentDescriptionARG(1)ARG(2)ARG(3)ARG(4)ARG(5)ARG(6)Parameter list defined as follows:v Exit typev Version numberv Mail record IDv Port number of SMTP serverv <strong>IP</strong> address of SMTP serverv Port number of clientv <strong>IP</strong> address of clientv Filename of note on diskv Verify Client statusv Maximum length of Return StringSMTP command stringHELO/EHLO nameMAIL FROM: stringClient domain nameNot usedOutputs:The following are returned to the caller in the RESULT variable via a REXXRETURN statement:┌────────┬──────────────────────────────┐│ RC │ Return String │└────────┴──────────────────────────────┘ArgumentRCReturn StringDescriptionThe exit return code; this must be a 4-byte binary value.An exit-specified string; the returned value must have a length lessthan or equal to the maximum length passed to the exit.Assembler Parameter ListFollowing is the parameter list that is passed to the assembler exit routine. GeneralRegister 1 points to the parameter list.Table 76. Mail Forwarding ASSEMBLER Exit Parameter ListOffset inDecimalLen In/Out Type Description+0 4 Input Char Exit type+4 4 Input Int Version number+8 4 Input Int Mail record ID+12 4 Input Int Port number of SMTP server+16 4 Input Int <strong>IP</strong> address of SMTP server380 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


SMTP Virtual Machine InterfacesTable 76. Mail Forwarding ASSEMBLER Exit Parameter List (continued)Offset inDecimalLen In/Out Type Description+20 4 Input Int Port number of client+24 4 Input Int <strong>IP</strong> address of client+28 4 Input Ptr Address of SMTP command string+32 4 Input Int Length of SMTP command string+36 4 Input Ptr Address of HELO/EHLO name+40 4 Input Int Length of HELO/EHLO name+44 4 Input Ptr Address of client domain name+48 4 Input Int Length of client domain name+52 4 Input Ptr Address of MAIL FROM: string+56 4 Input Int Length of MAIL FROM: string+60 8 Input Char File name of note on disk+68 4 Input Int Verify Client status+72 4 Output Ptr Address of Return String+76 4 Output Int Length of Return String+80 4 Input Int Maximum length of Return String+84 8 Not used+92 4 Input/ Output Char User Word 1+96 4 Input/ Output Char User Word 2+100 4 Output Int Return code from exitParameter Descriptions:Exit typeA four-character field that indicates the type of exit called. For the mailforwarding exit, this is FWDX.Version numberThe parameter list version number; if the parameter list format is changed, theversion number will change. Your exit should verify it has received theexpected version number. The current version number is 1.Mail record IDA number that uniquely identifies a piece of mail so that multiple exit calls canbe correlated to the same piece of mail. A value of 0 indicates a mail record IDis not available.Port number of SMTP serverThe port number used by the SMTP server for this connection.<strong>IP</strong> address of SMTP serverFor the REXX exit, a dotted-decimal format <strong>IP</strong> address is provided; for theassembler exit, this is an <strong>IP</strong> address in decimal integer form. For multi-homedhosts, this address can be compared with the client <strong>IP</strong> address to determine inwhich part of the network the client host resides.Port number of clientIf the connection no longer exists, -1 is supplied. Otherwise, this is the portnumber used by the foreign host for this connection.<strong>IP</strong> address of clientFor the REXX exit, a dotted-decimal format <strong>IP</strong> address is provided; for theassembler exit, this is an <strong>IP</strong> address in decimal integer form.SMTP command stringContains the name specified on the RCPT TO: command. The recipient path,Chapter 10. SMTP Virtual Machine Interfaces 381


SMTP Virtual Machine Interfaces382 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>enclosed in angle brackets (< and >), is included. The recipient path may be inany valid path format; it has already been verified to have the correct syntax.Because the recipient address has been resolved, this string may not exactlymatch the data provided with the RCPT TO: command.For example, if the following has been specified by the SMTP client:RCPT TO: the SMTP command string might contain: HELO/EHLO nameA string that contains the name specified on the HELO or EHLO command;this string may be either:v a domain namev an <strong>IP</strong> address in decimal integer form that is prefixed by the number or (US)pound sign (“#” or X'7B')v an <strong>IP</strong> address in dotted-decimal form, enclosed in brackets.For example, if the command HELO #123456 is provided by an SMTP client, thisparameter would contain: #123456.The name has already been verified to have the correct syntax.Client domain nameThe domain name that corresponds to the client <strong>IP</strong> address. The length of thisfield will be zero if:v client verification was not performedv the results of client verification are unknownv a reverse lookup failedIn all other cases, this will be a domain name.MAIL FROM: stringContains the name specified on the MAIL FROM: command. The sender path,enclosed in angle brackets (< and >), is included. The sender path may be inany valid path format; it has already been verified to have the correct syntax.Because the sender address has been resolved, this string may not exactlymatch the data provided with the MAIL FROM: command.For example, if the following has been specified by the SMTP client:MAIL FROM: the SMTP command string might contain: File name of note on diskName of the file created after the “end of data” (EOD) condition, a period (.),is received. Prior to either of these conditions, the file name is not defined; inthis case, an asterisk (*) will be supplied.Verify Client statusA number that indicates client verification results. Possible values and theirmeanings are:0 Client verification passed.1 Client verification failed.2 Client verification was not performed.3 Client verification results are unknown.Return StringWhen the exit returns a return code of 1 or 5, this value is appended to the 551or 550 reply code. When the exit returns a return code of 2, the Return Stringvalue should contain a <strong>VM</strong> user ID to which mail should be transferred.


Maximum length of Return StringThe current maximum is 512 bytes; ensure the Return String length is less thanthis value. If the returned string is longer than the indicated maximum, thereturn string is truncated and the following message is displayed on the SMTPsever console:Return data from exit exitname exittype too long, data truncatedNormal processing continues.User Word 1Provided for use by the assembler exit only. The user word specified uponreturn from this exit will be passed back in this field for any future calls; 0 isthe initial value. The SMTP server does not use this value in any way.User Word 2Provided for use by the assembler exit only. The user word specified uponreturn from this exit will be passed back in this field for any future calls; 0 isthe initial value. The SMTP server does not use this value in any way.Return Codes from the Mail Forwarding Exit RoutineFollowing are the return codes recognized by SMTP for this exit.Table 77. Mail Forwarding Exit Return CodesReturn Code Explanation0 Accept and attempt mail delivery.1 Reject mail with: 551 Return StringSMTP Virtual Machine InterfacesIf a return string is not provided by the exit, the following default messagewill be used:551 User not local; please try user@otherhostIf the server has already responded to the command, this return code willresult in error mail being sent back to the sender.2 Accept and forward to the local <strong>VM</strong> user ID specified by Return String. Ifthe <strong>VM</strong> user ID is null or is not valid, the mail will be delivered to the localpostmaster; the mail will not be delivered to the addressee.4 Disable the exit. The following message will be displayed on the SMTPconsole:FORWARD MAIL EXIT function disabledThe exit will no longer be called. SMTP will attempt to deliver this mail.5 Reject this command with: 550 Return StringIf a return string is not provided by the exit, then the default message willbe displayed:550 Access deniedOtherAll future communications on this connection will be rejected with this 550message.Any return code other than the above causes SMTP to issue this message:Unexpected return from user exit exitname exittype, RC=rcSMTP treats this return code as if it were a return code of 0.Chapter 10. SMTP Virtual Machine Interfaces 383


||||||||||||||SMTP Virtual Machine InterfacesMail Forwarding Sample ExitsSample Mail Forwarding exit routines are supplied with <strong>TCP</strong>/<strong>IP</strong> on the<strong>TCP</strong>MAINT 591 disk. The supplied samples are:SMTPFWDX SEXECREXX exit routine that contains a sample framework for handlingforwarded mail items. Your customized exit should be stored on the<strong>TCP</strong>MAINT 198 disk as file SMTPFWDX EXEC.SMTPFWDX SAMPASMThe assembler exit routine called by the SMTP server; the exit is used tocall SMTPFWDX EXEC and to pass results back to the SMTP server. Yourcustomized exit should be stored on the <strong>TCP</strong>MAINT 198 disk as fileSMTPFWDX ASSEMBLE. The customized ASSEMBLE file must beassembled (by using the <strong>VM</strong>FHLASM SMTPFWDX DMS<strong>VM</strong> command), and theresulting text deck placed on the <strong>TCP</strong>MAINT 198 disk.These samples are for illustrative purposes only. They should be modified to meetthe needs of your installation before placing them in a production environment.The assembler exit will have better performance characteristics than the REXX exit.For best performance, EXECLOAD any REXX exits.Using the SMTP Command ExitThe SMTP server can be configured to call an exit routine whenever certain SMTPcommands are received, through use of the SMTP command exit. This exit can bedefined such that is invoked for any or all the commands that follow:HELOThe SMTP 'HELO' command.EHLOThe SMTP 'EHLO' command.MAILThe SMTP 'MAIL FROM:' command.RCPTThe SMTP 'RCPT TO:' command.DATAThe SMTP 'DATA' command.EOD The “end of data” condition. This occurs when a period (.) is received bythe server, usually after all data has been transmitted.VRFYThe SMTP 'VRFY' command.EXPNThe SMTP 'EXPN' command.RSETThe SMTP 'RSET' command.PUNCHThe point in time when the server is about to deliver mail to a localdestination on the same node or RSCS network; this command is unique tothe <strong>VM</strong> <strong>TCP</strong>/<strong>IP</strong> SMTP server.384 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Notes:1. The person responsible for creating or maintaining programs that exploit thiscapability should be knowledgeable of the protocol(s) related to the SMTPcommands that are processed using this exit.2. Only one SMTP command exit can be active at a time.The SMTP command exit could be used for a wide variety of purposes; severalpossible uses are included here:v Reject particular SMTP commands. For example, you may not want your serverto support the VRFY and EXPN commands.v Handle the delivery of local mail in a specific manner.v Screen and reject mail that contains offensive language, or fails to meet othercriteria defined by your installation.Note: Scanning the content of a message will severely degrade server performance.SMTP Command Exit Parameter ListsThe parameter lists passed to the REXX and the assembler exit routines follow.When you customize either of these exits, keep in mind the in mind the following:vBecause an identical exit parameter list definition is used for all of the SMTPuser exits, not all parameters may be meaningful for this exit. Parameters thatare not used by this exit are indicated in the exit parameter lists; their valuesshould be ignored.v For the REXX exit, the value of an unused parameter will be such that anyparsing will not be affected.Parameter descriptions that pertain to both the REXX and assembler exits areprovided on page 386.REXX Parameter ListInputs:Table 78. SMTP Commands REXX Exit Parameter ListArgumentDescriptionSMTP Virtual Machine InterfacesARG(1)ARG(2)ARG(3)ARG(4)ARG(5)ARG(6)Parameter list defined as follows:v Exit typev Version numberv Mail record IDv Port number of SMTP serverv <strong>IP</strong> address of SMTP serverv Port number of clientv <strong>IP</strong> address of clientv Filename of note on diskv Verify Client statusv Maximum length of Return StringSMTP command stringHELO/EHLO nameMAIL FROM: stringClient domain nameBatch <strong>VM</strong> user IDChapter 10. SMTP Virtual Machine Interfaces 385


SMTP Virtual Machine InterfacesOutputs: The following are returned to the caller in the RESULT variable via aREXX RETURN statement:┌────────┬──────────────────────────────┐│ RC │ Return String │└────────┴──────────────────────────────┘ArgumentRCReturn StringDescriptionThe exit return code; this must be a 4-byte numeric value.An exit-specified string; the returned value must have a length lessthan or equal to the maximum length passed to the exit.Assembler Parameter ListFollowing is the parameter list that is passed to the assembler exit routine. GeneralRegister 1 points to the parameter list.Table 79. SMTP Commands ASSEMBLER Exit Parameter ListOffset inDecimalLen In/Out Type Description+0 4 Input Char Exit type+4 4 Input Int Version number+8 4 Input Int Mail record ID+12 4 Input Int Port number of SMTP server+16 4 Input Int <strong>IP</strong> address of SMTP server+20 4 Input Int Port number of client+24 4 Input Int <strong>IP</strong> address of client+28 4 Input Ptr Address of SMTP command string+32 4 Input Int Length of SMTP command string+36 4 Input Ptr Address of HELO/EHLO name+40 4 Input Int Length of HELO/EHLO name+44 4 Input Ptr Address of client domain name+48 4 Input Int Length of client domain name+52 4 Input Ptr Address of MAIL FROM: string+56 4 Input Int Length of MAIL FROM: string+60 8 Input Char File name of note on disk+68 4 Input Int Verify client status+72 4 Output Ptr Address of Return String+76 4 Output Int Length of Return String+80 4 Input Int Maximum length of Return String+84 8 Input Char Batch <strong>VM</strong> User ID+92 4 Input/ Output Char User Word 1+96 4 Input/ Output Char User Word 2+100 4 Output Int Return code from exitParameter Descriptions:Exit typeA four-character field that indicates the type of exit called. For the SMTPcommand exit, this is CMDX.Version numberThe parameter list version number; if the parameter list format is changed, theversion number will change. Your exit should verify it has received theexpected version number. The current version number is 1.386 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


SMTP Virtual Machine InterfacesMail record IDA number that uniquely identifies a piece of mail so that multiple exit calls canbe correlated to the same piece of mail. A value of 0 indicates a mail record IDis not available.Port number of SMTP serverThe port number used by the SMTP server for this connection.<strong>IP</strong> address of SMTP serverFor the REXX exit, a dotted-decimal format <strong>IP</strong> address is provided; for theassembler exit, this is an <strong>IP</strong> address in decimal integer form. For multi-homedhosts, this address can be compared with the client <strong>IP</strong> address to determine inwhich part of the network the client host resides.Port number of clientIf the connection no longer exists, or if the command was received over a batch(BSMTP) connection, -1 is supplied. Otherwise, this is the port number used bythe foreign host for this connection.<strong>IP</strong> address of clientFor the REXX exit, a dotted-decimal format <strong>IP</strong> address is provided; for theassembler exit, this is an <strong>IP</strong> address in decimal integer form. If the relevantSMTP command was received over a batch SMTP (BSMTP) connection, thisfield is 0.File name of note on diskName of the file created after the “end of data” (EOD) condition, a period (.),is received. Prior to either of these conditions, the file name is not defined; inthis case, an asterisk (*) will be supplied.Verify Client statusA number that indicates client verification results. Possible values and theirmeanings are:0 Client verification passed.1 Client verification failed.2 Client verification was not performed.3 Client verification results are unknown.SMTP command stringContains the current command and parameters; the string has been convertedto uppercase. For example, if this exit was called for the MAIL FROM:command, this string might contain: MAIL FROM: .HELO/EHLO nameA string that contains the name specified on the HELO or EHLO command;this string may be either:v a domain namev an <strong>IP</strong> address in decimal integer form that is prefixed by the number or (US)pound sign (“#” or X'7B')v an <strong>IP</strong> address in dotted-decimal form, enclosed in brackets.For example, if the command HELO #123456 is provided by an SMTP client, thisparameter would contain: #123456.The name has already been verified to have the correct syntax.MAIL FROM: stringContains the name specified on the MAIL FROM: command. The sender path,enclosed in angle brackets (< and >), is included. The sender path may be inany valid path format; it has already been verified to have the correct syntax.Chapter 10. SMTP Virtual Machine Interfaces 387


SMTP Virtual Machine InterfacesBecause the sender address has been resolved, this string may not exactlymatch the data provided with the MAIL FROM: command.For example, if the following has been specified by the SMTP client:MAIL FROM: the SMTP command string might contain: Client domain nameThe domain name that corresponds to the client <strong>IP</strong> address. This field will be anull string if:v client verification was not performedv the results of client verification are unknownv a reverse lookup failedIn all other cases, this will be a domain name.Batch <strong>VM</strong> user IDThis field is only used when SMTP commands arrive over a batch SMTP(BSMTP) connection. If this exit is called for batch SMTP connections, this fieldwill contain the <strong>VM</strong> User ID that originated the mail. Otherwise, this field isnot defined and will contain nulls.User Word 1Provided for use by the assembler exit only. The user word specified uponreturn from this exit will be passed back in this field for any future calls; 0 isthe initial value. The SMTP server does not use this value in any way.User Word 2Provided for use by the assembler exit only. The user word specified uponreturn from this exit will be passed back in this field for any future calls; 0 isthe initial value. The SMTP server does not use this value in any way.Return StringWhen the exit returns a return code of 1 or 5, this value is appended to the 550reply code.Maximum length of Return StringThe current maximum is 512 bytes; ensure the Return String length is less thanthis value. If the returned string is longer than the indicated maximum, thereturn string is truncated and the following message is displayed on the SMTPsever console:Return data from exit exitname exittype too long, data truncatedNormal processing continues.Return Codes from the SMTP Command Exit RoutineFollowing are the return codes recognized by SMTP for this exit.Table 80. SMTP Command Exit Return CodesReturn Code Explanation0 Accept command, and continue normal processing.388 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Table 80. SMTP Command Exit Return Codes (continued)Return Code Explanation1 Reject mail with: 551 Return StringSMTP Virtual Machine InterfacesIf a return string is not provided by the exit, the following default messagewill be used:550 Command RejectedThis return code is valid for only the PUNCH command; if 1 is retuned fora PUNCH command exit call, it will be handled as an invalid exit returncode.2 The PUNCH command has been handled by the exit routine; therefore,bypass file delivery. This return code is valid for only the PUNCHcommand; if 1 is retuned for a PUNCH command exit call, it will behandled as an invalid exit return code.4 Disable the exit. The following message will be displayed on the SMTPconsole:SMTPCMDS EXIT function disabledThe exit will no longer be called. The command will be attempted, andprocessing will continue.5 Reject this command with: 550 Return StringIf a return string is not provided by the exit, then the default message willbe displayed:550 Access deniedOtherAll future communications on this connection will be rejected with this 550message. This return code is valid for only the PUNCH command; if 1 isretuned for a PUNCH command exit call, it will be handled as an invalidexit return code.Any return code other than the above causes SMTP to issue this message:Unexpected return from user exit exitname exittype, RC=rcSMTP treats this return code as if it were a return code of 0.||||||||||||||Sample SMTP Command ExitsSample SMTP Command exit routines are supplied with <strong>TCP</strong>/<strong>IP</strong> on the<strong>TCP</strong>MAINT 591 disk. The supplied samples are:SMTPCMDX SEXECREXX exit routine that contains a sample framework for SMTP commandprocessing. Your customized exit should be stored on the <strong>TCP</strong>MAINT 198disk as file SMTPCMDX EXEC.SMTPCMDX SAMPASMThe assembler exit routine called by the SMTP server; the exit is used tocall SMTPCMDX EXEC and to pass results back to the SMTP server. Yourcustomized exit should be stored on the <strong>TCP</strong>MAINT 198 disk as fileSMTPCMDX ASSEMBLE. The customized ASSEMBLE file must beassembled (by using the <strong>VM</strong>FHLASM SMTPCMDX DMS<strong>VM</strong> command), and theresulting text deck placed on the <strong>TCP</strong>MAINT 198 disk.These samples are for illustrative purposes only. They should be modified to meetthe needs of your installation before placing them in a production environment.Chapter 10. SMTP Virtual Machine Interfaces 389


SMTP Virtual Machine InterfacesThe assembler exit will have better performance characteristics than the REXX exit.For best performance, EXECLOAD any REXX exits.390 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Chapter 11. Telnet ExitsThe Telnet server exits described in the sections that follow provide CP commandsimulation, TN3270E printer management, and system access control when Telnetconnections are established with your host.While the SCEXIT or PMEXIT is running, the <strong>TCP</strong>/<strong>IP</strong> service machine cannotservice any other requests. Therefore, it is advised that processing performedwithin these exits should be minimized.|||||||||Also, in environments with a high rate of TN3270 and/or TN3270E sessioncreation and termination, the use of a REXX exec could adversely affectperformance. While calling such an exec may be useful for designing and testing aprototype, a production-level exit should be written in assembler. For suchenvironments, the supplied sample Telnet session connection exit (SCEXITSAMPASM) and printer management exit (PMEXIT SAMPASM) should be used asa basis for assemble files which directly perform any actions appropriate for yourenvironment. It is recommended that execs be used only for designing and testingan exit prototype; for best performance, such execs should be EXECLOADed.Telnet Session Connection ExitWhen a Telnet client establishes a session with <strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong> andInternalClientParms ConnectExit has been specified, the exit routine receivescontrol using standard OS linkage conventions. Register 1 points to a parameterlist to be used by the exit.© Copyright <strong>IBM</strong> Corp. 1987, 2001 391


Telnet Session Connection ExitTelnet Exit Parameter ListTable 81. Telnet Session Connection Exit Parameter ListOffset Len Name In/Out Description+0 1 SCREASON Input Reason Exit was calledX'01' - Client connect+1 1 SCFLAG1 Output Flags1... .... - Hide <strong>VM</strong> logo from client.1.. .... - Hide command simulation..xx xxxx - Reserved+2 2 Reserved+4 4 SC<strong>IP</strong>ADDR Input <strong>IP</strong> address of client+8 2 SCPORT Input Telnet server port number+10 2 SCCMDL InputOutputLength of command bufferLength of command placed in buffer+12 4 SCCPCMD Input Address of command buffer+16 4 SCRC Output Return code0 = Give client <strong>VM</strong> logo4 = Reject client, no message8 = Perform command in SCCPCMD;SCCMDL must be non-zero12 = Same as 0, and disable exit16 = Same as 4, and disable exit20 = Same as 8, and disable exit|All others will reject the client, and a message isdisplayed on the <strong>TCP</strong><strong>IP</strong> virtual machine console.+20 2 SCFPORT Input Client foreign port number+22 2 Reserved+24 16 SCLUNAME Input Client-provided LU name+40 4 SCL<strong>IP</strong>ADD Input Local <strong>IP</strong> address to which client connected||||||||||||||Sample ExitSample Telnet connection exit routines are supplied with <strong>TCP</strong>/<strong>IP</strong> on the<strong>TCP</strong>MAINT 591 minidisk. The supplied samples are:SCEXIT SEXECREXX exit routine that contains the logic for allowing or denying access byTelnet clients. Your customized exit should be stored on the <strong>TCP</strong>MAINT198 disk as file SCEXIT EXEC.SCEXIT SAMPASMThe assembler exit routine called by the Telnet server; the exit is used tocall SCEXIT EXEC and to pass results back to the Telnet server. Yourcustomized exit should be stored on the <strong>TCP</strong>MAINT 198 disk as fileSCEXIT ASSEMBLE. The customized ASSEMBLE file must be assembled(by using the <strong>VM</strong>FHLASM SCEXIT DMS<strong>VM</strong> command), and the resulting textdeck placed on the <strong>TCP</strong>MAINT 198 disk.The sample exit is enabled by including the following in PROFILE <strong>TCP</strong><strong>IP</strong>:InternalClientParmsConnectExit SCEXITEndInternalClientParms392 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Telnet Printer Management ExitWhen a client establishes a TN3270E printer session with <strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong> andInternalClientParms TN3270EExit has been specified, the exit routine receivescontrol when a printer session is established or terminated. The exit is called usingstandard CMS linkage conventions. General Register 1 points to a paramater listthat the exit may use.Telnet Printer Management Exit Parameter ListTable 82. Telnet Exit Parameter ListOffset Len Name In/Out DescriptionTelnet Printer Management Exit+0 1 PMXVERSN Input Parameter list version numberX'01' - Version 1+1 1 PMXREASN Input Reason exit calledX'00' - Printer connectedX'01' - Printer disconnected+2 2 Reserved+4 4 PMX<strong>IP</strong>ADD Input Client <strong>IP</strong> address+8 2 PMXFPORT Input Client port number+A 2 PMXLPORT Input Telnet server port number+C 4 PMXLDEV Input Logical device number+10 8 PMXLUNAM Input Logical unit name specified by client+18 8 PMXUSER Input Associated user identifier. If no matchingTN3270E configuration statement exists, contains “?”+20 4 PMXVDEV Input Associated virtual device address. If no matchingTN3270E configuration statement exists, contains “?”+24 4 PMXRC Output Return code0 = Accept client4 = Reject client8 = Same as 0, and disable exit12 = Same as 4, and disable exitAll others will reject client, and a message isdisplayed on the <strong>TCP</strong><strong>IP</strong> virtual machine console.||||||||||||||Sample ExitSample printer management exit routines are supplied with <strong>TCP</strong>/<strong>IP</strong> on the<strong>TCP</strong>MAINT 591 minidisk. The supplied samples are:PMEXIT SEXECREXX exit routine that contains the logic for allowing or denying access byTN3270 clients. Your customized exit should be stored on the <strong>TCP</strong>MAINT198 disk as file PMEXIT EXEC.PMEXIT SAMPASMThe assembler exit routine called by the Telnet server; the exit is used tocall PMEXIT EXEC and to pass results back to the Telnet server. Yourcustomized exit should be stored on the <strong>TCP</strong>MAINT 198 disk as filePMEXIT ASSEMBLE. The customized ASSEMBLE file must be assembled(by using the <strong>VM</strong>FHLASM PMEXIT DMS<strong>VM</strong> command, and the resulting textdeck placed on the <strong>TCP</strong>MAINT 198 disk.Enable the sample exit by including the following in PROFILE <strong>TCP</strong><strong>IP</strong>:Chapter 11. Telnet Exits 393


Telnet Printer Management ExitInternalClientParmsTN3270EExit PMEXITEndInternalClientParms394 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Chapter 12. FTP Server ExitThe FTP Server ExitThe FTP server user exits described in the next sections allow you greater controlover commands received by the FTP server and allows for auditing of FTP logins,logouts and file transfers.The exit is enabled using the FTAUDIT, FTCHKCMD, and FTCHKDIR startupparameters on the SRVRFTP command or by using the FTP SMSG commands. Thestartup parameters and SMSG commands are documented in <strong>TCP</strong>/<strong>IP</strong> Planning andCustomization.Since the use of the FTP exits adversely affects performance, it is advised thatprocessing performed within the exit should be minimized. While calling a REXXexec is useful for designing an exit prototype, a production-level exit should bewritten entirely in assembler. For best performance, any REXX execs should beEXECLOADed.Sample ExitSample FTP server exit routines are supplied with <strong>TCP</strong>/<strong>IP</strong> on the <strong>TCP</strong>MAINT 591minidisk. The supplied samples are:|||||||||||FTPEXIT SEXECREXX exit routine that contains sample logic for login and directorycontrol, and FTP command processing. Your customized exit should bestored on the <strong>TCP</strong>MAINT 198 disk as file FTPEXIT EXEC.FTPEXIT SAMPASMThe assembler exit routine called by the FTP server; the exit is used to callFTPEXIT EXEC and to pass results back to the FTP server. Yourcustomized exit should be stored on the <strong>TCP</strong>MAINT 198 disk as fileFTPEXIT ASSEMBLE. The customized ASSEMBLE file must be assembled(by using the <strong>VM</strong>FHLASM FTPEXIT DMS<strong>VM</strong> command), and the resulting textdeck placed on the <strong>TCP</strong>MAINT 198 disk.Audit ProcessingThese samples are for illustrative purposes only. They should be modified to meetthe needs of your installation before placing them in a production environment.With the FTP server exit enabled for audit processing, the FTP Exit will be calledfor each of the following events:v LOGINAuditing occurs following FTP user login validationv LOGOUTLogout occurs when a:– user enters a QUIT command– user enters a new USER command while already logged in– connection is dropped by an SMSG DROP command– client aborts the connection© Copyright <strong>IBM</strong> Corp. 1987, 2001 395


FTP Server Exitv– connection is closed because the server is shutting down– connection times outDATA TRANSFERData transfers include the following commands:– APPE (client append command)– STOR, STOU (client put command)– RETR (client get command)– LIST, NLST (client dir, ls commands)Note: Audit exit processing is enabled with the FTAUDIT startup parameter orwith the SMSG command to enable exits.Audit Processing Parameter ListTable 83. FTP Exit Audit Parameter ListOffset inDecimalLen In/Out Type Description+0 4 Input Char Exit type (AUDX)+4 4 Input Int Version number+8 8 Input Char FTP server command+16 4 Input Ptr Address of command argument string;the first halfword contains the length.+20 8 Input Char Login user ID+28 8 Input Char LOGONBY user ID+36 4 Input Int <strong>IP</strong> address of client+40 4 Input Ptr Address of current workingdirectory name; the first halfwordcontains the length.+44 4 Input Ptr Address of target directory or file;the first halfword contains the length.+48 4 Input Int Number of bytes transferred.+52 2 Input Int Port number of FTP server+54 2 Input Int Port number of FTP client+56 8 Input Char Event date (yyyymmdd)+64 8 Input Char Event time (hh:mm:ss)+72 8 Not used+80 4 Output Int Return code from exitAudit Processing Parameter DescriptionsExit TypeA 4 character field that indicates the type of exit processing to be performed.For audit processing, this is AUDX.Version numberIf the parameter list format is changed, then the version number will change.Your exit should verify it has received the expected version number. Thecurrent version number is 1.FTP server commandThis field contains one of the following commands: LOGIN, LOGOUT, XFER.FTP command argument string396 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


vvFTP Server ExitFor data transfer (XFER) commands, this string indicates the transferdirection. SENDING indicates data is being transferred to a client;RECEIVING indicates data is being received from a client.For login commands, this string indicates the command that initiated loginvalidation processing (USER for anonymous logins or PASS)v For logout commands, this string indicates the command or function whichinitiated the logout (QUIT, USER, DROPPED, TIMEOUT, SHUTDOWN,ABORTED).Login user IDThe <strong>VM</strong> user identifier associated with this FTP session. All FTP clientauthorization checks are made using the login user ID.LOGONBY user IDThe alternate logon name whose password is used for login authorizationchecking. A user ID will be present in this field only when the client has issueda USER subcommand that includes the userid/BY/byuserid operands; otherwise,a hyphen (-) will be present.<strong>IP</strong> address of clientThe <strong>IP</strong> address in decimal integer form.Current working directory nameThis field is not used for login or logout processing and will contain a hyphen(-). For data transfers, this field contains the type of directory in use, followedby the working directory name. For example:Directory TypeMinidiskShared File SystemByte File SystemVirtual ReaderWorking Directory passed to FTPEXITDSK TERI.191SFS SERVK1:TERI.BFS /../<strong>VM</strong>BFS:BFS:TERI/RDR TERI.RDRTarget fileTarget file for data transfer. Minidisk, SFS, or RDR files are identified in uppercase using the filename.filetype format. BFS files are identified using a mixedcase filename, that can be up to 255 characters long. This field is not used forlogin and logout processing and will contain a hyphen (-).Number of bytes transferredv For data transfer (XFER) commands, this field contains the number of bytestransferred on the data connection.v For login commands, this field contains a zero.v For logout commands, this field contains a zero.Port number of FTP serverThe port number used by the FTP server for this control connection.Port number of clientThe port number used by the foreign host for this control connection.Event dateThe date format for this parameter is yyyymmdd.Event timeThe time format for this parameter is hh:mm:ss.Chapter 12. FTP Server Exit 397


FTP Server ExitReturn code from exitAn integer return code. For a list of return codes recognized by the FTP serversee “Return Codes from Audit Processing”.Return Codes from Audit ProcessingReturn Code Use / Description0 Continue processing.8 Continue processing, but disable audit exit. The following message isdisplayed on the FTP server console: “FTP AUDX exit has been disabled”.Other Any return code other than the above causes FTP to issue the message:“Unexpected return from user exit FTPEXIT AUDX, RC = rc”. The serverwill treat this return code as if it were a return code of 0.General Command ProcessingWith the FTP server exit enabled for general command exit processing, the FTP exitwill be called to perform command validation for every received FTP command.Commands that may be passed to this exit follow:ABOR ACCT ALLO APPE CDUP CWDDELE HELP LIST MKD MODE NLSTNOOP PASS PASV PORT PWD QUITREIN REST RETR RMD RNFR RNTOSITE SYST STAT STOR STOU STRUTYPE USER XCWD XMKD XPWD UNKNOWNNote: See RFC 959 for details about each command.The general command exit can be used to perform additional security checkingand then take an appropriate action, such as the following:v Reject commands from a particular <strong>IP</strong> address, user ID or LOGONBY user IDv Reject a subset of commands for anonymous usersv Reject transfer requests for specific filesv Reject all users from issuing store (APPE, STOR, STOU) commandsNote: General command exit processing is enabled with the FTCHKCMD startupparameter or with the SMSG command to enable exits.General Command Processing Parameter ListTable 84. FTP Exit Parameter ListOffset inDecimalLen In/Out Type Description+0 4 Input Char Exit type (CMDX)+4 4 Input Int Version number+8 8 Input Char FTP server command+16 4 Input Ptr Address of command argument string;the first halfword contains the length.398 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


FTP Server ExitTable 84. FTP Exit Parameter List (continued)Offset inDecimalLen In/Out Type Description+20 8 Input Char Login user ID+28 8 Input Char LOGONBY user ID+36 4 Input Int <strong>IP</strong> address of client+40 4 Input Ptr Address of current workingdirectory name; The first halfwordcontains the length.+44 8 - - Not used+52 2 Input Int Port number of FTP server+54 2 Input Int Port number of FTP client+56 16 - - Not used+72 4 Input Int Maximum length of return string+76 4 Output Int Address of return string (message text)+80 4 Output Int Return code from exitGeneral Command Processing Parameter DescriptionsExit TypeA 4 character field that indicates the type of exit processing to be performed.For command exit processing, this is CMDX.Version numberIf the parameter list format is changed, then the version number will change.Your exit should verify it has received the expected version number. Thecurrent version number is 1.FTP server commandCommands received by the server such as USER, STOR, and DELE.FTP command argument stringThe argument string provided by the client. For ACCT and PASS commands,the argument string will contain all asterisks (********).Login user IDThe <strong>VM</strong> user identifier associated with this FTP session. All FTP clientauthorization checks are made using the login user ID.LOGONBY user IDThe alternate logon name (userid) whose password is used for loginauthorization checking. A user ID will be present in this field only when theclient has issued a USER subcommand that includes the userid/BY/byuseridoperands; otherwise, a hyphen (-) will be present.<strong>IP</strong> address of clientThe <strong>IP</strong> address in decimal integer form.Current working directory nameThis field contains the type of directory, followed by the working directoryname. For example:Directory TypeMinidiskShared File SystemByte File SystemWorking Directory passed to FTPEXITDSK TERI.191SFS SERVK1:TERI.BFS /../<strong>VM</strong>BFS:BFS:TERI/Chapter 12. FTP Server Exit 399


FTP Server ExitDirectory TypeWorking Directory passed to FTPEXITVirtual readerRDR TERI.RDRNo directory defined -Port number of FTP serverThe port number used by the FTP server for this control connection.Port number of clientThe port number used by the foreign host for this control connection.Maximum length of return stringThe current maximum is 1000 bytes. If the returned string is longer than themaximum, the return string is truncated.Return stringA return string is to be included as part of the server reply to an FTP client.This string is used only when a return code of 4 or 12 is returned by the exit.Return code from exitAn integer return code. For a list of return codes recognized by the FTP serversee “Return Codes from General Command Processing”.ExampleIf the FTP client provides the command “PUT PROFILE.EXEC”, the parametervalues provided to the FTPEXIT might be:Exit Type: AUDXFTP command: XFERClient <strong>IP</strong> Address : 9.111.32.29UserID: TERIByUserID : -Bytes transferred : 2141Server Port : 1021Client Port : 21400Event Date : 19990309Event Time : 14:44:34Working Directory: SFS SERVK1:TERI.Command args: RECEIVINGTarget File: PROFILE.EXECReturn Codes from General Command ProcessingReturn Code Use / Description0 Accept command and continue processing4 Reject client command with “502 return_string”. If return string is notprovided, return the default message “502 command rejected”.8 Accept command, continue normal processing, but disable command exitprocessing. The following message is displayed on the FTP server console:“FTP CMDX exit has been disabled”.12 Same as 4 and disable command exit processing. The following message isdisplayed on the FTP server console: “FTP CMDX exit has been disabled”.400 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


FTP Server ExitReturn CodeOtherUse / DescriptionAny return code other than the above causes FTP to issue the message:“Unexpected return from user exit FTPEXIT CMDX, RC = rc”. The serverwill treat this return code as if it were a return code of 0.||Change Directory ProcessingWith the FTP server the exit will be called to validate FTP directory changes andprovide greater control over access to system resources by selectively honoring orrefusing a client change directory request. The exit is called when an FTP clientprovides one of the following commands:v CWD or CD to change the working directoryv CDUP to change the working directory to the parent directoryv PASS with a default directory defined in CHK<strong>IP</strong>ADR EXECvUSER for an anonymous login with a default directory defined in CHK<strong>IP</strong>ADREXECv APPE, DELE, LIST, NLST, RETR, SIZE, STOR, and STOU commands thatinvolve an explicit change in directory.Notes:1. CD command exit processing is enabled with the FTCHKDIR startupparameter or with the SMSG command to enable exits.2. The CD command exit cannot be used to alter the directory name provided bythe client.Change Directory Processing Parameter ListTable 85. FTP Exit Parameter ListOffsetinDecimalLen In/Out Type Description+0 4 Input Char Exit type (DIRX)+4 4 Input Int Version number+8 8 Input Char FTP server command+16 4 Input Ptr Address of command argument string;the first halfword contains the length.+20 8 Input Char Login user ID+28 8 Input Char LOGONBY user ID+36 4 Input Int <strong>IP</strong> address of client+40 4 Input Ptr Address of current workingdirectory name; the first halfwordcontains the length.+44 4 Input Ptr Address of target directory or file;the first halfword contains the length.+48 4 - - Not used+52 2 Input Int Port number of FTP server+54 2 Input Int Port number of FTP client+56 16 - - Not used+72 4 Input Int Maximum length of return string+76 4 Output Int Address of return string (message text)+80 4 Output Int Return code from exitChapter 12. FTP Server Exit 401


||FTP Server ExitChange Directory Processing Parameter DescriptionsExit TypeA 4 character field that indicates the type of exit processing to be performed.For CD command exit processing, this is DIRX.Version numberIf the parameter list format is changed, then the version number will change.Your exit should verify it has received the expected version number. Thecurrent version number is 1.FTP server commandThis field will contain APPE, CWD, CDUP, DELE, LIST, NLST, PASS, RETR,SIZE, STOR, STOU, or USER.FTP command argument stringThe argument string entered by the client. For PASS commands, the argumentstring will contain asterisks (********).Login user IDThe <strong>VM</strong> user identifier associated with this FTP session. All FTP clientauthorization checks are made using the login user ID.LOGONBY user IDThe alternate logon name (userid) whose password is used for loginauthorization checking. A user ID will be present in this field only when theclient has issued a USER subcommand that includes the userid/BY/byuseridoperands; otherwise, a hyphen (-) will be present.<strong>IP</strong> address of clientThe <strong>IP</strong> address in decimal integer form.Current working directory nameThis field contains the type of directory, followed by the working directoryname. For example:Directory TypeWorking Directory Passed to FTPEXITMinidiskDSK TERI.191Shared File System SFS SERVK1:TERI.Byte File SystemBFS /../<strong>VM</strong>BFS:BFS:TERI/Virtual readerRDR TERI.RDRNo directory defined -Target directoryThis field contains the fully-qualified target directory for the command. Formatof the target directory is similar to the current working directory name format.The following examples show representative values that would be passed tothe exit for certain actions or requests made by a client user.For user login:FTP command: PASSWorking Directory : -Command args : ********Target Directory: DSK TERI.191402 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


FTP Server ExitFor a CD to a BFS directory request:FTP commandWorking DirectoryCommand argsTarget Directory: CWD: DSK TERI.191: /../<strong>VM</strong>BFS:BFS:SCOTT/: BFS /../<strong>VM</strong>BFS:BFS:SCOTT/For a CD to a BFS subdirectory request:FTP commandWorking DirectoryCommand argsTarget Directory: CWD: BFS /../<strong>VM</strong>BFS:BFS:SCOTT/: SUBDIR: BFS /../<strong>VM</strong>BFS:BFS:SCOTT/SUBDIR/Port number of FTP serverThe port number used by the FTP server for this control connection.Port number of clientThe port number used by the foreign host for this control connection.Maximum length of return stringThe current maximum is 1000 bytes. If the returned string is longer than themaximum, the return string is truncated.Return stringA return string is to be included as part of the server reply to an FTP client.This string is used only when a return code of 4 or 12 is returned by the exit.Return code from exitAn integer return code. For a list of return codes recognized by the FTP serversee “Return Codes from the FTPEXIT Routine for CD Command Processing”.Return Codes from the FTPEXIT Routine for CD CommandProcessingReturn Code Use / Description0 Accept command and continue normal processing4 Reject client command with “502 return_string”. If return string is notprovided, display the default message “502 command rejected”.8 Accept command, continue normal processing, but disable CD commandexit processing. The following message is displayed on the FTP serverconsole: “FTP DIRX exit has been disabled”.12 Same as 4 and disable CD command exit processing. The followingmessage is displayed on the FTP server console: “FTP DIRX exit has beendisabled”.Other Any return code other than the above causes FTP to issue the message:“Unexpected return from user exit FTPEXIT DIRX, RC = rc”. The serverwill treat this return code as if it were a return code of 0.Chapter 12. FTP Server Exit 403


404 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Appendix A. Pascal Return CodesWhen using Pascal procedure calls, check to determine whether the call has beencompleted successfully. Use the SayCalRe function (see “SayCalRe” on page 124) toconvert the ReturnCode parameter to a printable form.The SayCalRe function converts a return code value into a descriptive message. Forexample, if SayCalRe is invoked with the integer constant BADlengthARGUMENT,it returns the message buffer length specified. For a description of Pascal returncodes and their equivalent message text from SayCalRe, see Table 86.Most return codes are self-explanatory in the context where they occur. The returncodes you see as a result of issuing a <strong>TCP</strong>/UDP/<strong>IP</strong> request are in the range −128to 0. For more information, see the Explanatory Notes at the end of Table 86.Table 86. Pascal Language Return CodesReturn CodeNumeric Message TextValueOK 0 OK.ABNORMALcondition¹ −1 Abnormal condition duringinter−address communication.(<strong>VM</strong>CF. RC=nn User=xxxxxxxx)ALREADYclosing −2 Connection already closing.BADlengthARGUMENT −3 Invalid length specified.CANNOTsendDATA² −4 Cannot send data.CLIENTrestart −5 Client reinitialized <strong>TCP</strong>/<strong>IP</strong>service.CONNECTIONalreadyEXISTS −6 Connection already exists.DESTINATIONunreachable −7 Destination address isunreachable.ERRORinPROFILE −8 Error in profile file; details are inPROFILE.<strong>TCP</strong>ERROR.FATALerror³ −9 Fatal inter−addresscommunications error. (<strong>VM</strong>CF.RC=nn User=xxxxxxxx)HASnoPASSWORD −10 No password in RACF ® directory.INCORRECTpassword −11 <strong>TCP</strong><strong>IP</strong> not authorized to accessfile.INVALIDrequest −12 Invalid request.INVALIDuserID −13 Invalid user ID.INVALIDvirtualADDRESS −14 Invalid virtual address.KILLEDbyCLIENT −15 You aborted the connection.LOCALportNOTavailable −16 The requested local port is notavailable.MINIDISKinUSE −17 File is in use by someone else andcannot be accessed.MINIDISKnotAVAILABLE −18 File not available.© Copyright <strong>IBM</strong> Corp. 1987, 2001 405


Pascal Return CodesTable 86. Pascal Language Return Codes (continued)Return CodeNumeric Message TextValueNObufferSPACE⁴ −19 No more space for data currentlyavailable.NOmoreINCOMINGdata −20 The foreign host has closed thisconnection.NONlocalADDRESS −21 The internet address is not local tothis host.NOoutstandingNOTIFICATIONS −22 No outstanding notifications.NOsuchCONNECTION −23 No such connection.NOtcp<strong>IP</strong>service −24 No <strong>TCP</strong>/<strong>IP</strong> service available.NOTyetBEGUN −25 Not yet begun <strong>TCP</strong>/<strong>IP</strong> service.NOTyetOPEN −26 The connection is not yet open.OPENrejected −27 Foreign host rejected the openattempt.PARAMlocalADDRESS −28 TcpOpen error: invalid localaddress.PARAMstate −29 TcpOpen error: invalid initialstate.PARAMtimeout −30 Invalid time−out parameter.PARAMunspecADDRESS −31 TcpOpen error: unspecifiedforeign address in active open.PARAMunspecPORT −32 TcpOpen error: unspecifiedforeign port in active open.PROFILEnotFOUND −33 <strong>TCP</strong><strong>IP</strong> cannot read profile file.RECEIVEstillPENDING −34 Receive still pending on thisconnection.REMOTEclose −35 Foreign host unexpectedly closedthe connection.REMOTEreset −36 Foreign host aborted theconnection.SOFTWAREerror −37 Software error in <strong>TCP</strong>/<strong>IP</strong>!<strong>TCP</strong>ipSHUTDOWN −38 <strong>TCP</strong>/<strong>IP</strong> service is being shutdown.TIMEOUTconnection −39 Foreign host is no longerresponding.TIMEOUTopen −40 Foreign host did not respondwithin OPEN time−outTOOmanyOPENS −41 Too many open connectionsalready exist.UNAUTHORIZEDuser −43 You are not authorized to issuethis command.UNEXPECTEDsyn −44 Foreign host violated theconnection protocol.UNIMPLEMENTEDrequest −45 Unimplemented <strong>TCP</strong>/<strong>IP</strong> request.UNKNOWNhost −46 Destination host is not known.406 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Table 86. Pascal Language Return Codes (continued)Pascal Return CodesReturn CodeNumeric Message TextValueUNREACHABLEnetwork −47 Destination network isunreachable.UNSPECIFIEDconnection −48 Unspecified connection.VIRTUALmemoryTOOsmall −49 Client virtual machine has toolittle storage.WRONGsecORprc −50 Foreign host disagreed on securityor precedence.YOURend −55 Client has ended <strong>TCP</strong>/<strong>IP</strong> service.0resources −56 <strong>TCP</strong> cannot handle any moreconnections now.UDPlocalADDRESS −57 Invalid local address for UDP.UDPunspecADDRESS −59 Address unspecified whenspecification necessary.UDPunspecPORT −60 Port unspecified whenspecification necessary.UDPzeroRESOURCES −61 UDP cannot handle any moretraffic.FSENDstillPENDING −62 FSend still pending on thisconnection.DROPPEDbyOPERATOR −79 Connection dropped by operator.ERRORopeningORreadingFILE −80 Error opening or reading file.FILEformatINVALID −81 File format invalid.Explanatory Notes1. ABNORMALconditionThe actual <strong>VM</strong>CF return code is available in the external integer variableLastVmcfCode, and is included in the output of SayCalRe if calledimmediately after the error is detected.2. CANNOTsendDATACannot send data on this connection because the connection state is invalidfor sending data.3. FATALerrorThe actual <strong>VM</strong>CF return code is available in the external integer variableLastVmcfCode, and is included in the output of SayCalRe if calledimmediately after the error is detected.4. NObufferSPACEApplies to this connection only. Space may still be available for otherconnections.Appendix A. Pascal Return Codes 407


Explanatory Notes408 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Appendix B. C API System Return CodesThis appendix provides a reference for system calls. Table 87 provides thesystem-wide message numbers set by the system calls. These message numbers arecontained in the compiler file ERRNO.H and in the <strong>TCP</strong> file <strong>TCP</strong>ERRNO.H.Table 87. System Return CodesMessage Code DescriptionEPERM 1 Permission denied.ENOENT 2 No such file or directory.ESRCH 3 No such process.EINTR 4 Interrupted system call.EIO 5 I/O error.ENXIO 6 No such device or address.E2BIG 7 Argument list too long.ENOEXEC 8 Exec format error.EBADF 9 Bad file number.ECHILD 10 No children.EAGAIN 11 No more processes.ENOMEM 12 Not enough memory.EACCES 13 Permission denied.EFAULT 14 Bad address.ENOTBLK 15 Block device required.EBUSY 16 Device busy.EEXIST 17 File exists.EXDEV 18 Cross device link.ENODEV 19 No such device.ENOTDIR 20 Not a directory.EISDIR 21 Is a directory.EINVAL 22 Invalid argument.ENFILE 23 File table overflow.EMFILE 24 Too many open files.ENOTTY 25 Inappropriate device call.ETXTBSY 26 Text file busy.EFBIG 27 File too large.ENOSPC 28 No space left on device.ESP<strong>IP</strong>E 29 Illegal seek.EROFS 30 Read only file system.EMLINK 31 Too many links.EP<strong>IP</strong>E 32 Broken pipe.EDOM 33 Argument too large.© Copyright <strong>IBM</strong> Corp. 1987, 2001 409


C API System Return CodesTable 87. System Return Codes (continued)Message Code DescriptionERANGE 34 Result too large.EWOULDBLOCK 35 Operation would block.EINPROGRESS 36 Operation now in progress.EALREADY 37 Operation already in progress.ENOTSOCK 38 Socket operation on non-socket.EDESTADDRREQ 39 Destination address required.EMSGSIZE 40 Message too long.EPROTOTYPE 41 Protocol wrong type for socket.ENOPROTOOPT 42 Protocol not available.EPROTONOSUPPORT 43 Protocol not supported.ESOCKTNOSUPPORT 44 Socket type not supported.EOPNOTSUPP 45 Operation not supported onsocket.EPFNOSUPPORT 46 Protocol family not supported.EAFNOSUPPORT 47 Address family not supported byprotocol family.EADDRINUSE 48 Address already in use.EADDRNOTAVAIL 49 Cannot assign requested address.ENETDOWN 50 Network is down.ENETUNREACH 51 Network is unreachable.ENETRESET 52 Network dropped connection onreset.ECONNABORTED 53 Software caused connection abort.ECONNRESET 54 Connection reset by peer.ENOBUFS 55 No buffer space available.EISCONN 56 Socket is already connected.ENOTCONN 57 Socket is not connected.ESHUTDOWN 58 Cannot send after socketshutdown.ETOOMANYREFS 59 Too many references: cannotsplice.ETIMEDOUT 60 Connection timed out.ECONNREFUSED 61 Connection refused.ELOOP 62 Too many levels of symbolicloops.ENAMETOOLONG 63 File name too long.EHOSTDOWN 64 Host is down.EHOSTUNREACH 65 No route to host.ENOTEMPTY 66 Directory not empty.EPROCLIM 67 Too many processes.EUSERS 68 Too many users.EDQUOT 69 Disc quota exceeded.410 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Table 87. System Return Codes (continued)C API System Return CodesMessage Code DescriptionESTALE 70 Stale NFS file handle.EREMOTE 71 Too many levels of remote inpath.ENOSTR 72 Device is not a stream.ETIME 73 Timer expired.ENOSR 74 Out of streams resources.ENOMSG 75 No message of desired type.EBADMSG 76 Trying to read unreadablemessage.EIDRM 77 Identifier removed.EDEADLK 78 Deadlock condition.ENOLCK 79 No record locks available.ENONET 80 Machine is not on the network.ERREMOTE 81 Object is remote.ENOLINK 82 Link has been severed.EADV 83 Advertise error.ESRMNT 84 Srmount error.ECOMM 85 Communication error on send.EPROTO 86 Protocol error.EMULTIHOP 87 Multihop attempted.EDOTDOT 88 Cross mount point.EREMCHG 89 Remote address changed.Appendix B. C API System Return Codes 411


C API System Return Codes412 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Appendix C. Well-Known Port AssignmentsThis appendix lists the well-known port assignments for transport protocols <strong>TCP</strong>and UDP, and includes port number, keyword, and a description of the reservedport assignment. You can also find a list of these well-known port numbers in theETC SERVICES file.<strong>TCP</strong> Well-Known Port AssignmentsTable 88. <strong>TCP</strong> Well-Known Port AssignmentsTable 88 lists the well-known port assignments for <strong>TCP</strong>.Port Number Keyword Reserved for Services Description0 reserved5 rje remote job entry remote job entry7 echo echo echo9 discard discard sink null11 systat active users active users13 daytime daytime daytime15 netstat Netstat who is up or Netstat19 chargen ttytst source character generator21 ftp FTP File Transfer Protocol23 telnet Telnet Telnet25 smtp mail Simple Mail Transfer Protocol37 time timeserver timeserver39 rlp resource Resource Location Protocol42 nameserver name host name server43 nicname who is who is53 domain name server domain name server57 mtp private terminal access private terminal access69 tftp TFTP Trivial File Transfer Protocol77 rje netrjs any private RJE service79 finger finger finger87 link ttylink any private terminal link95 supdup supdup SUPDUP Protocol101 hostname hostname nic hostname server, usually from SRI-NIC109 pop postoffice Post Office Protocol111 sunrpc sunrpc Sun remote procedure call113 auth authentication authentication service115 sftp sftp Simple File Transfer Protocol117 uucp-path UUCP path service UUCP path service119 untp readnews untp USENET News Transfer Protocol© Copyright <strong>IBM</strong> Corp. 1987, 2001 413


Well-Known Port AssignmentsTable 88. <strong>TCP</strong> Well-Known Port Assignments (continued)Port Number Keyword Reserved for Services Description123 ntp NTP Network Time Protocol160–223 reserved512 REXEC REXEC Remote Execution Protocol514 RSH RSHELL Remote Shell Service712 vexec vice-exec Andrew File System authenticated service713 vlogin vice-login Andrew File System authenticated service714 vshell vice-shell Andrew File System authenticated service2001 filesrv Andrew File System service2106 venus.itc Andrew File System service, for the VenusprocessUDP Well-Known Port AssignmentsTable 89. UDP Well-Known Port AssignmentsTable 89 lists the well-known port assignments for UDP.Port Number Keyword Reserved for Services Description0 reserved5 rje remote job entry remote job entry7 echo echo echo9 discard discard sink null11 users active users active users13 daytime daytime daytime15 netstat Netstat Netstat19 chargen ttytst source character generator37 time timeserver timeserver39 rlp resource Resource Location Protocol42 nameserver name host name server43 nicname who is who is53 domain nameserver domain name server67 bootpd BOOTP BOOTP Daemon69 tftp TFTP Trivial File Transfer Protocol75 any private dial out service77 rje netrjs any private RJE service79 finger finger finger111 sunrpc sunrpc Sun remote procedure call123 ntp NTP Network Time Protocol160–223 reserved531 rvd-control rvd control port2001 rauth2 Andrew File System service, for theVenus process414 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Table 89. UDP Well-Known Port Assignments (continued)Well-Known Port AssignmentsPort Number Keyword Reserved for Services Description2002 rfilebulk Andrew File System service, for theVenus process2003 rfilesrv Andrew File System service, for theVenus process2018 console Andrew File System service2115 ropcons Andrew File System service, for theVenus process2131 rupdsrv assigned in pairs; bulk must be srv+12132 rupdbulk; assigned in pairs; bulk must be srv+12133 rupdsrv1 assigned in pairs; bulk must be srv+12134 rupdbulk1; assigned in pairs; bulk must be srv+1Appendix C. Well-Known Port Assignments 415


Well-Known Port Assignments416 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Appendix D. Related Protocol Specifications<strong>IBM</strong> is committed to industry standards. The internet protocol suite is still evolvingthrough Requests for Comments (RFC). New protocols are being designed andimplemented by researchers, and are brought to the attention of the internetcommunity in the form of RFCs. Some of these are so useful that they become arecommended protocol. That is, all future implementations for <strong>TCP</strong>/<strong>IP</strong> arerecommended to implement this particular function or protocol. These become thede facto standards, on which the <strong>TCP</strong>/<strong>IP</strong> protocol suite is built.Many features of <strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong> are based on the following RFCs:RFC Title Author768 User Datagram Protocol J.B. Postel791 Internet Protocol J.B. Postel792 Internet Control Message Protocol J.B. Postel793 Transmission Control Protocol J.B. Postel821 Simple Mail Transfer Protocol J.B. Postel822 Standard for the Format of ARPA Internet Text Messages D. Crocker823 DARPA Internet Gateway R.M. Hinden, A. Sheltzer826 Ethernet Address Resolution Protocol: or Converting Network Protocol Addresses D.C. Plummerto 48.Bit Ethernet Address for Transmission on Ethernet Hardware854 Telnet Protocol Specification J.B. Postel, J.K. Reynolds856 Telnet Binary Transmission J.B. Postel, J.K. Reynolds857 Telnet Echo Option J.B. Postel, J.K. Reynolds877 Standard for the Transmission of <strong>IP</strong> Datagrams over Public Data Networks J.T. Korb885 Telnet End of Record Option J.B. Postel903 Reverse Address Resolution Protocol R. Finlayson, T. Mann, J.C.Mogul, M. Theimer904 Exterior Gateway Protocol Formal Specification D.L. Mills919 Broadcasting Internet Datagrams J.C. Mogul922 Broadcasting Internet Datagrams in the Presence of Subnets J.C. Mogul950 Internet Standard Subnetting Procedure J.C. Mogul, J.B. Postel952 DoD Internet Host Table Specification K. Harrenstien, M.K. Stahl,E.J. Feinler959 File Transfer Protocol J.B. Postel, J.K. Reynolds974 Mail Routing and the Domain Name System C. Partridge1009 Requirements for Internet Gateways R.T. Braden, J.B. Postel1013 X Window System Protocol, Version 11: Alpha Update R.W. Scheifler1014 XDR: External Data Representation Standard Sun MicrosystemsIncorporated1027 Using ARP to Implement Transparent Subnet Gateways S. Carl-Mitchell, J.S.Quarterman1032 Domain Administrators Guide M.K. Stahl© Copyright <strong>IBM</strong> Corp. 1987, 2001 417


RFCs|RFC Title Author1033 Domain Administrators Operations Guide M. Lottor1034 Domain Names—Concepts and Facilities P.V. Mockapetris1035 Domain Names—Implementation and Specification P.V. Mockapetris1042 Standard for the Transmission of <strong>IP</strong> Datagrams over IEEE 802 Networks J.B. Postel, J.K. Reynolds1044 Internet Protocol on Network System’s HYPERchannel: Protocol Specification K. Hardwick, J.Lekashman1055 Nonstandard for Transmission of <strong>IP</strong> Datagrams over Serial Lines: SL<strong>IP</strong> J.L. Romkey1057 RPC: Remote Procedure Call Protocol Version 2 Specification Sun MicrosystemsIncorporated1058 Routing Information Protocol C.L. Hedrick1091 Telnet Terminal-Type Option J. VanBokkelen1094 NFS: Network File System Protocol Specification Sun MicrosystemsIncorporated1112 Host Extensions for <strong>IP</strong> Multicasting S. Deering1118 Hitchhikers Guide to the Internet E. Krol1122 Requirements for Internet Hosts-Communication Layers R.T. Braden1123 Requirements for Internet Hosts-Application and Support R.T. Braden1155 Structure and Identification of Management Information for <strong>TCP</strong>/<strong>IP</strong>-Based M.T. Rose, K. McCloghrieInternets1156 Management Information Base for Network Management of <strong>TCP</strong>/<strong>IP</strong>-based K. McCloghrie, M.T. RoseInternets1157 Simple Network Management Protocol (SNMP), J.D. Case, M. Fedor, M.L.Schoffstall, C. Davin1179 Line Printer Daemon Protocol The Wollongong Group, L.McLaughlin III1180 <strong>TCP</strong>/<strong>IP</strong> Tutorial, T. J. Socolofsky, C.J. Kale1183 New DNS RR Definitions (Updates RFC 1034, RFC 1035) C.F. Everhart, L.A.Mamakos, R. Ullmann, P.V.Mockapetris,1187 Bulk Table Retrieval with the SNMP M.T. Rose, K. McCloghrie,J.R. Davin1188 Proposed Standard for the Transmission of <strong>IP</strong> Datagrams over FDDI Networks D. Katz1198 FYI on the X Window System R.W. Scheifler1207 FYI on Questions and Answers: Answers to Commonly Asked ExperiencedInternet User QuestionsG.S. Malkin, A.N. Marine,J.K. Reynolds1208 Glossary of Networking Terms O.J. Jacobsen, D.C. Lynch1213 Management Information Base for Network Management of <strong>TCP</strong>/<strong>IP</strong>-Based K. McCloghrie, M.T. RoseInternets: MIB-II,1215 Convention for Defining Traps for Use with the SNMP M.T. Rose1228 SNMP-DPI Simple Network Management Protocol Distributed Program G.C. Carpenter, B. WijnenInterface1229 Extensions to the Generic-Interface MIB K. McCloghrie1230 IEEE 802.4 Token Bus MIB IEEE 802 4 Token Bus MIB K. McCloghrie, R. Fox1231 IEEE 802.5 Token Ring MIB IEEE 802.5 Token Ring MIB K. McCloghrie, R. Fox, E.Decker418 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


RFCs|RFC Title Author1267 A Border Gateway Protocol 3 (BGP-3) K. Lougheed, Y. Rekhter1268 Application of the Border Gateway Protocol in the Internet Y. Rekhter, P. Gross1269 Definitions of Managed Objects for the Border Gateway Protocol (Version 3) S. Willis, J. Burruss1293 Inverse Address Resolution Protocol T. Bradley, C. Brown1270 SNMP Communications Services F. Kastenholz, ed.1323 <strong>TCP</strong> Extensions for High Performance V. Jacobson, R. Braden, D.Borman1325 FYI on Questions and Answers: Answers to Commonly Asked New Internet G.S. Malkin, A.N. MarineUser Questions1350 TFTP Protocol K.R. Sollins1351 SNMP Administrative Model J. Davin, J. Galvin, K.McCloghrie1352 SNMP Security Protocols J. Galvin, K. McCloghrie, J.Davin1353 Definitions of Managed Objects for Administration of SNMP Parties K. McCloghrie, J. Davin, J.Galvin1354 <strong>IP</strong> Forwarding Table MIB F. Baker1356 Multiprotocol Interconnect on X.25 and ISDN in the Packet Mode A. Malis, D. Robinson, R.Ullmann1374 <strong>IP</strong> and ARP on H<strong>IP</strong>PI J. Renwick, A. Nicholson1381 SNMP MIB Extension for X.25 LAPB D. Throop, F. Baker1382 SNMP MIB Extension for the X.25 Packet Layer D. Throop1387 R<strong>IP</strong> Version 2 Protocol Analysis G. Malkin1389 R<strong>IP</strong> Version 2 MIB Extension G. Malkin1390 Transmission of <strong>IP</strong> and ARP over FDDI Networks D. Katz1393 Traceroute Using an <strong>IP</strong> Option G. Malkin1397 Default Route Advertisement In BGP2 And BGP3 Versions of the Border D. HaskinGateway Protocol1398 Definitions of Managed Objects for the Ethernet-like Interface Types F. Kastenholz1440 SIFT/UFT:Sender-Initiated/Unsolicited File Transfer R. Troth1483 Multiprotocol Encapsulation over ATM Adaptation Layer 5 J. Heinanen1540 IAB Official Protocol Standards J.B. Postel1583 OSPF Version 2 J.Moy1647 TN3270 Enhancements B. Kelly1700 Assigned Numbers J.K. Reynolds, J.B. Postel1723 R<strong>IP</strong> Version 2 — Carrying Additional Information G. Malkin1813 NFS Version 3 Protocol Specification B. Callaghan, B.Pawlowski, P. Stauback,Sun MicrosystemsIncorporated2225 Classical <strong>IP</strong> and ARP over ATM M. Laubach, J. HalpernThese documents can be obtained from:Appendix D. Related Protocol Specifications 419


RFCsGovernment Systems, Inc.Attn: Network Information Center14200 Park Meadow DriveSuite 200Chantilly, VA 22021Many RFCs are available online. Hard copies of all RFCs are available from theNIC, either individually or on a subscription basis. Online copies are availableusing FTP from the NIC at nic.ddn.mil. Use FTP to download the files, using thefollowing format:RFC:RFC-INDEX.TXTRFC:RFCnnnn.TXTRFC:RFCnnnn.PSWhere:nnnnTXTPSIs the RFC number.Is the text format.Is the PostScript format.You can also request RFCs through electronic mail, from the automated NIC mailserver, by sending a message to service@nic.ddn.mil with a subject line ofRFC nnnn for text versions or a subject line of RFC nnnn.PS for PostScript versions.To request a copy of the RFC index, send a message with a subject line ofRFC INDEX.For more information, contact nic@nic.ddn.mil. Information is also availablethrough http://www.internic.net.420 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Appendix E. Abbreviations and AcronymsThe following abbreviations and acronyms are used throughout this book.AIXAdvanced Interactive ExecutiveANSIAmerican National Standards InstituteAPIApplication Program InterfaceAPPCAdvanced Program-to-Program CommunicationsAPPN ® Advanced Peer-to-Peer Networking ®ARPAddress Resolution ProtocolASCIIAmerican National Standard Code for Information InterchangeASN.1Abstract Syntax Notation OneATMAsynchronous Transfer ModeAUIAttachment Unit InterfaceBFSByte File SystemBIOSBasic Input/Output SystemBNCBayonet Neill-ConcelmanCCITTComite Consultatif International Telegraphique et Telephonique.The International Telegraph and Telephone ConsultativeCommitteeCETIContinuously Executing Transfer InterfaceCLAWCommon Link Access to WorkstationCLISTCommand ListCMSConversational Monitor SystemCPControl ProgramCPICommon Programming InterfaceCRENCorporation for Research and Education NetworkingCSDCorrective Service DisketteCTCChannel-to-ChannelCUControl UnitCUA ® Common User Access ®DASDDirect Access Storage DeviceDBCSDouble Byte Character SetDLLDynamic Link LibraryDNSDomain Name SystemDOSDisk Operating SystemDPIDistributed Program InterfaceEBCDIC Extended Binary-Coded Decimal Interchange CodeELANS<strong>IBM</strong> Ethernet LAN SubsystemEISAEnhanced Industry Standard AdapterESCON ® Enterprise Systems Connection Architecture ®FATFile Allocation TableFDDIFiber Distributed Data InterfaceFTAMFile Transfer Access ManagementFTPFile Transfer ProtocolFTP API File Transfer Protocol Applications Programming InterfaceGCSGroup Control SystemGDDM ® Graphical Data Display ManagerGDDMXD Graphics Data Display Manager Interface for X Window SystemGDFGraphics Data FileHCHHYPERchannel device© Copyright <strong>IBM</strong> Corp. 1987, 2001 421


Abbreviations and Acronyms|H<strong>IP</strong>PIHigh Performance Parallel InterfaceHPFSHigh Performance File SystemICMPInternet Control Message ProtocolIEEEInstitute of Electrical and Electronic EngineersIETFInternet Engineering Task ForceIGMPInternet Group Management ProtocolILANS<strong>IBM</strong> Token-Ring LAN Subsystem<strong>IP</strong>Internet Protocol<strong>IP</strong>LInitial Program LoadISAIndustry Standard AdapterISDNIntegrated Services Digital NetworkISOInternational Organization for StandardizationIUCVInter-User Communication VehicleJESJob Entry SubsystemJISJapanese Institute of StandardsJCLJob Control LanguageLANLocal Area NetworkLAPSLAN Adapter Protocol SupportLCS<strong>IBM</strong> LAN Channel StationLPDLine Printer DaemonLPQLine Printer QueryLPRLine Printer ClientLPRMLine Printer RemoveLPRMON Line Printer MonitorLULogical UnitMACMedia Access ControlMbpsMegabits per secondMBpsMegabytes per secondMCAMicro Channel ® AdapterM<strong>IBM</strong>anagement Information BaseMIHMissing Interrupt HandlerMILNET Military NetworkMHSMessage Handling SystemMTUMaximum Transmission UnitMVSMultiple Virtual StorageMXMail ExchangeNCPNetwork Control ProgramNCSNetwork Computing SystemNDISNetwork Driver Interface SpecificationNFSNetwork File SystemNICNetwork Information CenterNLSNational Language SupportNSFNET National Science Foundation NetworkOS/2 ® Operating System/2 ®OSAOpen Systems AdapterOSFOpen Software Foundation, Inc.OSIOpen Systems InterconnectionOSIMF/6000 Open Systems Interconnection Messaging and Filing/6000OV/MVS OfficeVision/MVS OV/<strong>VM</strong> OfficeVision/<strong>VM</strong> PADPacket Assembly/DisassemblyPCPersonal ComputerPCAParallel Channel AdapterPDNPublic Data NetworkPDUProtocol Data Units422 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Abbreviations and AcronymsPINGPIOAMPOPPROFS ®PSCAPSDNPUP<strong>VM</strong>RACFRARPREXECREXXRFCR<strong>IP</strong>RISCRPCRSCSSAASBCSSDLCSFSSL<strong>IP</strong>SMILSMTPSNASNMPSOASPOOLSQL<strong>TCP</strong><strong>TCP</strong>/<strong>IP</strong>TFTPTSOTTLUDPVGA<strong>VM</strong><strong>VM</strong>CF<strong>VM</strong>/ESA<strong>VM</strong>SES/EVTAM ®WANXDRPacket Internet GroperParallel I/O Access MethodPost Office ProtocolProfessional Office SystemsPersonal System Channel AttachPacket Switching Data NetworkPhysical UnitPassthrough Virtual MachineResource Access Control FacilityReverse Address Resolution ProtocolRemote ExecutionRestructured Extended Executor LanguageRequest For CommentsRouting Information ProtocolReduced Instruction Set ComputerRemote Procedure CallRemote Spooling Communications SubsystemSystem Application ArchitectureSingle Byte Character SetSynchronous Data Link ControlShared File SystemSerial Line Internet ProtocolStructure for Management InformationSimple Mail Transfer ProtocolSystems Network ArchitectureSimple Network Management ProtocolStart of AuthoritySimultaneous Peripheral Operations Online<strong>IBM</strong> Structured Query LanguageTransmission Control ProtocolTransmission Control Protocol/Internet ProtocolTrivial File Transfer ProtocolTime Sharing OptionTime-to-LiveUser Datagram ProtocolVideo Graphic ArrayVirtual MachineVirtual Machine Communication FacilityVirtual Machine/Enterprise System ArchitectureVirtual Machine Serviceability Enhancements Staged/ExtendedVirtual Telecommunications Access MethodWide Area NetworkeXternal Data RepresentationAppendix E. Abbreviations and Acronyms 423


Abbreviations and Acronyms424 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


NoticesThis information was developed for products and services offered in the U.S.A.<strong>IBM</strong> may not offer the products, services, or features discussed in this document inother countries. Consult your local <strong>IBM</strong> representative for information on theproducts and services currently available in your area. Any reference to an <strong>IBM</strong>product, program, or service is not intended to state or imply that only that <strong>IBM</strong>product, program, or service may be used. Any functionally equivalent product,program, or service that does not infringe any <strong>IBM</strong> intellectual property right maybe used instead. However, it is the user’s responsibility to evaluate and verify theoperation of any non-<strong>IBM</strong> product, program, or service.<strong>IBM</strong> may have patents or pending patent applications covering subject matterdescribed in this document. The furnishing of this document does not give youany license to these patents. You can send license inquiries, in writing, to:<strong>IBM</strong> Director of Licensing<strong>IBM</strong> CorporationNorth Castle DriveArmonk, NY 10504-1785U.S.A.For license inquiries regarding double-byte (DBCS) information, contact the <strong>IBM</strong>Intellectual Property Department in your country or send inquiries, in writing, to:<strong>IBM</strong> World Trade Asia CorporationLicensing2-31 Roppongi 3-chome, Minato-kuTokyo 106, JapanThe following paragraph does not apply to the United Kingdom or any othercountry where such provisions are inconsistent with local law:INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THISPUBLICATION “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHEREXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESSFOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express orimplied warranties in certain transactions, therefore, this statement may not applyto you.This information could include technical inaccuracies or typographical errors.Changes are periodically made to the information herein; these changes will beincorporated in new editions of the publication. <strong>IBM</strong> may make improvementsand/or changes to the product(s) and/or the program(s) described in thispublication at any time without notice.Any references in this information to non-<strong>IBM</strong> Web sites are provided forconvenience only and do not in any manner serve as an endorsement of those Websites. The materials at those Web sites are not part of the materials for this <strong>IBM</strong>product and use of those Web sites is at your own risk.<strong>IBM</strong> may use or distribute any of the information you supply in any way itbelieves appropriate without incurring any obligation to you.Licensees of this program who wish to have information about it for the purposeof enabling: (i) the exchange of information between independently created© Copyright <strong>IBM</strong> Corp. 1987, 2001 425


programs and other programs (including this one) and (ii) the mutual use of theinformation which has been exchanged, should contact:<strong>IBM</strong> CorporationMail Station P300,522 South RoadPoughkeepsie, NY 12601-5400U.S.A.Attention: Information RequestSuch information may be available, subject to appropriate terms and conditions,including in some cases, payment of a fee.The licensed program described in this document and all licensed materialavailable for it are provided by <strong>IBM</strong> under terms of the <strong>IBM</strong> Customer Agreement,<strong>IBM</strong> International Program License Agreement or any equivalent agreementbetween us.Any performance data contained herein was determined in a controlledenvironment. Therefore, the results obtained in other operating environments mayvary significantly. Some measurements may have been made on development-levelsystems and there is no guarantee that these measurements will be the same ongenerally available systems. Furthermore, some measurement may have beenestimated through extrapolation. Actual results may vary. Users of this documentshould verify the applicable data for their specific environment.Information concerning non-<strong>IBM</strong> products was obtained from the suppliers ofthose products, their published announcements or other publicly available sources.<strong>IBM</strong> has not tested those products and cannot confirm the accuracy ofperformance, compatibility or any other claims related to non-<strong>IBM</strong> products.Questions on the capabilities on non-<strong>IBM</strong> products should be addressed to thesuppliers of those products.All statements regarding <strong>IBM</strong>’s future direction or intent are subject to change orwithdrawal without notice, and represent goals and objectives only.This information contains examples of data and reports used in daily businessoperations. To illustrate them as completely as possible, the examples include thenames of individuals, companies, brands, and products. All of these names arefictitious and any similarity to the names and addresses used by an actual businessenterprise is entirely coincidental.COPYRIGHT LICENSE:This information contains sample application programs in source language, whichillustrates programming techniques on various operating platforms. You may copy,modify, and distribute these sample programs in any form without payment to<strong>IBM</strong>, for the purposes of developing, using, marketing or distributing applicationprograms conforming to the application programming interface for the operatingplatform for which the sample programs are written. These examples have notbeen thoroughly tested under all conditions. <strong>IBM</strong>, therefore, cannot guarantee orimply reliability, serviceability, or function of these programs. You may copy,modify, and distribute these sample programs in any form without payment to<strong>IBM</strong> for the purposes of developing, using, marketing, or distributing applicationprograms conforming to <strong>IBM</strong>’s application programming interfaces.426 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


TrademarksThe following terms are trademarks of the International Business MachinesCorporation in the United States, or other countries, or both:Advanced Peer-to-Peer NetworkingAIXBookManager C/370CICSCommon User AccessCUA DATABASE 2DB2DFSMS/<strong>VM</strong>ESCONNGDDM<strong>IBM</strong><strong>IBM</strong>LinkIMSLanguage EnvironmentMicro ChannelMVSMVS/ESAMVS/XAOfficeVisionOfficeVision/MVSOpenEditionOpenExtensionsOperating System/2OS/2OS/390PROFSRACF S/390System/390<strong>VM</strong>/ESAVTAMz/<strong>VM</strong>UNIX is a registered trademark in the United States and/or other countries.NetView is a registered trademark in the United States and other countries licensedexclusively through Tivoli.Other company, product, and service names may be trademarks or service marksof others.Notices 427


428 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


GlossaryThis glossary describes the most common termsassociated with <strong>TCP</strong>/<strong>IP</strong> communication in aninternet environment, as used in this book.If you do not find the term you are looking for,see the <strong>IBM</strong> Dictionary of Computing, New York:McGraw-Hill, 1994.For abbreviations, the definition usually consistsonly of the words represented by the letters; forcomplete definitions, see the entries for thewords.Numerics3172. <strong>IBM</strong> Interconnect Controller.3174. <strong>IBM</strong> Establishment Controller.3270. Refers to a series of <strong>IBM</strong> display devices; forexample, the <strong>IBM</strong> 3275, 3276 Controller Display Station,3277, 3278, and 3279 Display Stations, the 3290Information Panel, and the 3287 and 3286 printers. Aspecific device type is used only when a distinction isrequired between device types. Information aboutdisplay terminal usage also refers to the <strong>IBM</strong> 3138,3148, and 3158 Display Consoles when used in displaymode, unless otherwise noted.37xx Communication Controller. A network interfaceused to connect a <strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong> or MVS network thatsupports X.25 connections. NCP with X.25 NPSI mustbe running in the controller, and VTAM must berunning on the host.6611. <strong>IBM</strong> Network Processor.8232. <strong>IBM</strong> LAN Station.9370. Refers to a series of processors, namely the <strong>IBM</strong>9373 Model 20, the <strong>IBM</strong> 9375 Models 40 and 60, andthe <strong>IBM</strong> 9377 Model 90 and other models.Aabend.task.The abnormal termination of a program orabstract syntax. A description of a data structure thatis independent of machine-oriented structures andencodings.Abstract Syntax Notation One (ASN.1).language for describing abstract syntax.The OSIactive gateway. A gateway that is treated like anetwork interface in that it is expected to exchangerouting information, and if it does not do so for aperiod of time, the route associated with the gateway isdeleted.active open. The state of a connection that is activelyseeking a service. Contrast with passive open.adapter. A piece of hardware that connects a computerand an external device. An auxiliary device or unitused to extend the operation of another system.address. The unique code assigned to each device orworkstation connected to a network. A standardinternet address uses a two-part, 32-bit address field.The first part of the address field contains the networkaddress; the second part contains the local address.address mask. A bit mask used to select bits from anInternet address for subnet addressing. The mask is 32bits long and selects the network portion of the Internetaddress and one or more bits of the local portion. It issometimes called a subnet mask.address resolution. A means for mapping networklayer addresses onto media-specific addresses. See ARP.Address Resolution Protocol (ARP). A protocol usedto dynamically bind an internet address to a hardwareaddress. ARP is implemented on a single physicalnetwork and is limited to networks that supportbroadcast addressing.address space. A collection of bytes that are allocated,and in many ways managed, as a single entity by CP.Each byte within an address space is identified by aunique address. An address space represents an extentof storage available to a program. Address spacesallocated by <strong>VM</strong> range in size from 64KB to 2GB.Advanced Interactive Executive (AIX).version of the UNIX operating system.<strong>IBM</strong>’s licensedAdvanced Program-to-Program Communications(APPC). The interprogram communication servicewithin SNA LU 6.2 on which the APPC/<strong>VM</strong> interfaceis based.Advanced Research Projects Agency (ARPA). Nowcalled DARPA, its the U.S. Government agency thatfunded the ARPANET.Advanced Research Projects Agency Network(ARPANET). A packet switched network developed inthe early 1970’s that is the forerunner of today’sInternet. It was decommissioned in June 1990.© Copyright <strong>IBM</strong> Corp. 1987, 2001 429


agent. As defined in the SNMP architecture, an agent,or an SNMP server is responsible for performing thenetwork management functions requested by thenetwork management stations.AIX.Advanced Interactive Executive.American National Standard Code for InformationInterchange (ASCII). The standard code, using acoded character set consisting of 7-bit coded characters(8 bits including parity check), used for informationinterchange among data processing systems, datacommunication systems, and associated equipment. TheASCII set consists of control characters and graphiccharacters. The default file transfer type for FTP, usedto transfer files that contain ASCII text characters.American National Standards Institute (ANSI). Anorganization consisting of producers, consumers, andgeneral interest groups that establishes the proceduresby which accredited organizations create and maintainvoluntary industry standards in the United States.ANSI is sponsored by the Computer and BusinessEquipment Manufacturer Association and is responsiblefor establishing voluntary industry standards.ANSI.API.American National Standards Institute.Application Program Interface.APPC. Advanced Program-to-ProgramCommunications.application. The use to which an informationprocessing system is put, for example, a payrollapplication, an airline reservation application, anetwork application.application layer. The seventh layer of the OSI (OpenSystems Interconnection) model for datacommunication. It defines protocols for user orapplication programs.Application Program Interface (API). The formallydefined programming-language interface between an<strong>IBM</strong> system control program or licensed program andits user. APIs allow programmers to write applicationprograms that use the <strong>TCP</strong>, UDP, and <strong>IP</strong> layers of the<strong>TCP</strong>/<strong>IP</strong> protocol suite.argument. A parameter passed between a callingprogram and a called program.ARP.ARPA.ARPANET.Network.Address Resolution Protocol.Advanced Research Projects Agency.Advanced Research Projects AgencyASCII. American National Standard Code forInformation Interchange. The default file transfer typefor FTP, used to transfer files that contain ASCII textcharacters.ASN.1.ASYNC.Abstract Syntax Notation One.Asynchronous.asynchronous (ASYNC). Without regular timerelationship; unexpected or unpredictable with respectto the execution of program instruction. Seesynchronous.asynchronous communication. A method ofcommunication supported by the operating system thatallows an exchange of data with remote device, usingeither a start-stop line or an X.25 line. Asynchronouscommunications include the file transfer and theinteractive terminal facility support.Athena Widgets. The X Window widget set developedby MIT for Project Athena.Attachment Unit Interface (AUI). Connector usedwith thick Ethernet that often includes a drop cable.AUI.Attachment Unit Interface.attention key. A function key on terminals that, whenpressed, causes an I/O interruption in the processingunit.authentication server. The service that reads aKerberos database to verify that a client making arequest for access to an end-service is the client namedin the request. The authentication server provides anauthenticated client ticket as permission to access theticket-granting server.authenticator. Information encrypted by a Kerberosauthentication server that a client presents along with aticket to an end-server as permission to access theservice.authorization. The right granted to a user tocommunicate with, or to make use of, a computersystem or service.Bbackbone. In a local area network multiple-bridgering configuration, a high-speed link to which rings areconnected by means of bridges. A backbone can beconfigured as a bus or as a ring. In a wide areanetwork, a high-speed link to which nodes or dataswitching exchanges (DSES) are connected.background task. A task with which the user is notcurrently interacting, but continues to run.baseband. Characteristic of any network technologythat uses a single carrier frequency and requires allstations attached to the network to participate in everytransmission. See broadband.Basic Encoding Rules (BER). Standard rules forencoding data units described in ASN.1. Sometimes430 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


incorrectly grouped under the term ASN.1, whichcorrectly refers only to the abstract descriptionlanguage, not the encoding technique.Basic Input/Output System (BIOS). A set of routinesthat permanently resides in read-only memory (ROM)in a PC. The BIOS performs the most basic tasks, suchas sending a character to the printer, booting thecomputer, and reading the keyboard.batch. An accumulation of data to be processed. Agroup of records or data processing jobs broughttogether for processing or transmission. Pertaining toactivity involving little or no user action. See interactiveBayonet Neill-Concelman (BNC). A standardizedconnector used with Thinnet and coaxial cable.Because It’s Time NETwork (BITNET). A network ofhosts that use the Network Job Entry (NJE) protocol tocommunicate. The network is primarily composed ofuniversities, nonprofit organizations, and researchcenters. BITNET has recently merged with theComputer and Science Network (CSNET) to form theCorporation for Research and Educational Networking(CSNET). See CSNET.BER.Basic Encoding Rules.Berkeley Software Distribution (BSD). Term usedwhen describing different versions of the BerkeleyUNIX software, as in “4.3BSD UNIX”.BFS.Byte File System.big-endian. A format for storage or transmission ofbinary data in which the most significant bit (or byte)comes first. The reverse convention is little-endian.BIOS.BITNET.Basic Input/Output System.Because It’s Time NETwork.block. A string of data elements recorded, processed,or transmitted as a unit. The elements can becharacters, words, or physical records.blocking mode. If the execution of the programcannot continue until some event occurs, the operatingsystem suspends the program until that event occurs.BNC.BOOTPD.Bayonet Neill-Concelman.Bootstrap Protocol Daemon.Bootstrap Protocol Daemon (BOOTPD). The BOOTPdaemon responds to client requests for bootinformation using information contained in a BOOTPmachine file.bridge. A router that connects two or more networksand forwards packets among them. The operationscarried out by a bridge are done at the physical layerand are transparent to <strong>TCP</strong>/<strong>IP</strong> and <strong>TCP</strong>/<strong>IP</strong> routing. Afunctional unit that connects two local area networks(LANs) that use the same logical link control (LLC)procedures but may use different medium accesscontrol (MAC) procedures.broadband. Characteristic of any network thatmultiplexes multiple, independent network carriersonto a single cable. This is usually done usingfrequency division multiplexing. Broadband technologyallows several networks to coexist on one single cable;traffic from one network does not interfere with trafficfrom another, because the “conversations” happen ondifferent frequencies in the ether, similar to acommercial radio system.broadcast. The simultaneous transmission of datapackets to all nodes on a network or subnetwork.broadcast address. An address that is common to allnodes on a network.BSD.Berkeley Software Distribution.bus topology. A network configuration in which onlyone path is maintained between stations. Any datatransmitted by a station is concurrently available to allother stations on the link.byte-ordering. The method of sorting bytes underspecific machine architectures. Of the two commonmethods, little endian byte ordering places the leastsignificant byte first. This method is used in Intel**microprocessors. In the second method, big endian byteordering, the most significant byte is placed first. Thismethod is used in Motorola microprocessors.Byte File System (BFS). A file system in which a fileconsists of an ordered sequence of bytes rather thanrecords. BFS files can be organized into hierarchicaldirectories. Byte file systems are enrolled as file spacesin CMS file pools.CCarrier Sense Multiple Access with CollisionDetection (CSMA/CD). The access method used bylocal area networking technologies such as Ethernet.case-sensitive. A condition in which entries for anentry field must conform to a specific lowercase,uppercase, or mixed-case format to be valid.CCITT. Comite Consultatif InternationalTelegraphique et Telephonique.channel. A path in a system that connects a processorand main storage with an I/O device.channel-attached. pertaining to attachment of devicesdirectly by data channels (I/O channels)to a computer.Pertaining to devices attached to a controlling unit bycables, rather than by telecommunication lines.Synonymous with local, locally attached.Glossary 431


checksum. The sum of a group of data associated withthe group and used for checking purposes.CICS.Customer Information Control System.Class A network. An internet network in which thehigh-order bit of the address is 0. The host numberoccupies the three, low-order octets.Class B network. An internet network in which thehigh-order bit of the address is 1, and the nexthigh-order bit is 0. The host number occupies the twolow-order octets.Class C network. An internet network in which thetwo high-order bits of the address are 1 and the nexthigh-order bit is 0. The host number occupies thelow-order octet.CLAW.Common Link Access to Workstation.client. A function that requests services from a server,and makes them available to the user. In MVS, anaddress space that is using <strong>TCP</strong>/<strong>IP</strong> services.client-server model. A common way to describenetwork services and the model user processes(programs) of those services. Examples include thename server and resolver paradigm of the DNS and fileserver/file client relationships such as NFS and disklesshosts.client-server relationship. Any device that providesresources or services to other devices on a network is aserver. Any device that employs the resources providedby a server is a client. A machine can run client andserver processes at the same time.CLIST.CLPA.CMS.Command List.Create Link Pack Area.Conversational Monitor System.Comite Consultatif International Telegraphicque etTelephonique (CCITT). The International Telegraphand Telephone Consultative Committee. A unit of theInternational Telecommunications Union (ITU) of theUnited Nations. CCITT produces technical standards,known as “recommendations,” for all internationallycontrolled aspects of analog and digital communication.command. The name and any parameters associatedwith an action that can be performed by a program.The command is entered by the user; the computerperforms the action requested by the command name.Command List (CLIST). A list of commands andstatements designed to perform a specific function forthe user.command prompt. A displayed symbol, such as [C:\]that requests input from a user.Common Link Access to Workstation (CLAW). Acontinuously executing duplex channel programdesigned to minimize host interrupts while maximizingchannel utilization.communications adapter. A hardware feature thatenables a computer or device to become a part of adata network.community name. A password used by hosts runningSimple Network Management Protocol (SNMP) agentsto access remote network management stations.compile. To translate a program written in ahigh-level language into a machine language program.The computer actions required to transform a sourcefile into an executable object file.compiler. A program that translates a source programinto an executable program (an object program).Computer and Science Network (CSNET). A largecomputer network, mostly in the U.S. but withinternational connections. CSNET sites includeuniversities, research labs, and some commercialcompanies. It is now merged with BITNET to formCREN. See BITNET.connection. An association established betweenfunctional units for conveying information. The pathbetween two protocol modules that provides reliablestream delivery service. In an internet, a connectionextends from a <strong>TCP</strong> module on one machine to a <strong>TCP</strong>module on the other.Control Program (CP). The <strong>VM</strong> operating system thatmanages the real processor’s resources and isresponsible for simulating System/370s or 390s forindividual users.conversational monitor system (CMS). A virtualmachine operating system that provides generalinteractive time sharing, problem solving, and programdevelopment capabilities, and operates only undercontrol of the <strong>VM</strong>//ESA control program.Corporation for Research and EducationalNetworking (CREN). A large computer networkformed from the merging of BITNET and CSNET. SeeBITNET and CSNET.CP.Control Program.Create Link Pack Area (CLPA). A parameter specifiedat startup, which says to create the link pack area.CREN. Corporation for Research and EducationalNetworking.CSMA/CD. Carrier Sense Multiple Access withCollision Detection.CSNET.Computer and Science Network.432 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Customer Information Control System (CICS). An<strong>IBM</strong>-licensed program that enables transactions enteredat remote terminals to be processed concurrently byuser written application programs. It includes facilitiesfor building, using, and maintaining databases.Ddaemon. A background process usually started atsystem initialization that runs continuously andperforms a function required by other processes. Somedaemons are triggered automatically to perform theirtask; others operate periodically.DASD.DARPA.Direct Access Storage Device.Defense Advanced Research Projects Agency.DATABASE 2 (DB2). An <strong>IBM</strong> relational databasemanagement system for the MVS operating system.database administrator (DBA). An individual orgroup responsible for the rules by which data isaccessed and stored. The DBA is usually responsible fordatabase integrity, security, performance and recovery.datagram. A basic unit of information that is passedacross the internet, it consists of one or more datapackets.data link layer. Layer 2 of the OSI (Open SystemsInterconnection) model; it defines protocols governingdata packetizing and transmission into and out of eachnode.data set. The major unit of data storage and retrievalin MVS, consisting of a collection of data in one ofseveral prescribed arrangements and described bycontrol information to which the system has access.Synonymous with file in <strong>VM</strong> and OS/2.DB2. DATABASE 2.DBA.DBCS.DDN.Database administrator.Double Byte Character Set.Defense Data Network.decryption. The unscrambling of data using analgorithm that works under the control of a key. Thekey allows data to be protected even when thealgorithm is unknown. Data is unscrambled aftertransmission.default. A value, attribute, or option that is assumedwhen none is explicitly specified.Defense Advanced Research Projects Agency(DARPA). The U.S. government agency that fundedthe ARPANET.Defense Data Network (DDN). Comprises theMILNET and several other Department of Defensenetworks.destination node.is sent.DHCPD.Daemon.The node to which a request or dataDynamic Host Configuration ProtocolDirect Access Storage Device (DASD). A device inwhich access to data is independent of where dataresides on the device.directory.A named grouping of files in a file system.Disk Operating System (DOS). An operating systemfor computer systems that use disks and diskettes forauxiliary storage of programs and data.display terminal. An input/output unit by which auser communicates with a data-processing system orsub-system. Usually includes a keyboard and alwaysprovides a visual presentation of data; for example, an<strong>IBM</strong> 3179 display.Distributed Program Interface (DPI). A programminginterface that provides an extension to the functionprovided by the SNMP agents.DLL.DNS.Dynamic Link Library.Domain Name System.domain. In an internet, a part of the naming hierarchy.Syntactically, a domain name consists of a sequence ofnames (labels) separated by periods (dots).Domain Name System (DNS). A system in which aresolver queries name servers for resource recordsabout a host.domain naming. A hierarchical system for namingnetwork resources.DOS.Disk Operating System.dotted-decimal notation. The syntactic representationfor a 32-bit integer that consists of four 8-bit numbers,written in base 10 and separated by periods (dots).Many internet application programs accept dotteddecimal notations in place of destination machinenames.double-byte character set (DBCS). A set of charactersin which each character is represented by two bytes.Languages such as Japanese, Chinese, Korean, whichcontain more symbols than can be represented by 256code points, require double-byte character sets. Becauseeach character requires 2 bytes, the typing, display, andprinting of DBCS characters requires hardware andprograms that support DBCS.Glossary 433


doubleword. A contiguous sequence of bits orcharacters that comprises two computer words and iscapable of being addressed as a unit.DPI.Distributed Program Interface.Dynamic Host Configuration Protocol Daemon(DHCPD). The DHCP daemon (DHCPD server)responds to client requests for boot information usinginformation contained in a DHCP machine file. Thisinformation includes the <strong>IP</strong> address of the client, the <strong>IP</strong>address of the TFTP daemon, and information aboutthe files to request from the TFTP daemon.dynamic resource allocation. An allocation techniquein which the resources assigned for execution ofcomputer programs are determined by criteria appliedat the moment of need.dynamic link library (DLL). A module containingdynamic link routines that is linked at load or run time.EEBCDIC.code.EGP.Extended binary-coded decimal interchangeExterior Gateway Protocol.encapsulation. A process used by layered protocols inwhich a lower-level protocol accepts a message from ahigher-level protocol and places it in the data portionof the low-level frame. As an example, in Internetterminology, a packet would contain a header from thephysical layer, followed by a header from the networklayer (<strong>IP</strong>), followed by a header from the transportlayer (<strong>TCP</strong>), followed by the application protocol data.encryption. The scrambling or encoding of data usingan algorithm that works under the control of a key. Thekey allows data to be protected even when thealgorithm is unknown. Data is scrambled prior totransmission.ES/9370 Integrated Adapters. An adapter you can usein <strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong> to connect into Token-Ring networksand Ethernet networks, as well as <strong>TCP</strong>/<strong>IP</strong> networksthat support X.25 connections.Ethernet. The name given to a local areapacket-switched network technology invented in theearly 1970s by Xerox**, Incorporated. Ethernet uses aCarrier Sense Multiple Access/Collision Detection(CSMA/CD) mechanism to send packets.EXEC. In a <strong>VM</strong> operating system, a user-writtencommand file that contains CMS commands, otheruser-written commands, and execution controlstatements, such as branches.extended binary-coded decimal interchange code(EBCDIC). A coded character set consisting of 8-bitcoded characters.extended character. A character other than a 7-bitASCII character. An extended character can be a 1-bitcode point with the 8th bit set (ordinal 128-255) or a2-bit code point (ordinal 256 and greater).Exterior Gateway Protocol (EGP). A reachabilityrouting protocol used by gateways in a two-levelinternet.eXternal Data Representation (XDR). A standarddeveloped by Sun Microsystems, Incorporated forrepresenting data in machine-independent format.FFAT.File Allocation Table.FDDI. Fiber Distributed Data Interface. Also used toabbreviate Fiber Optic Distributed Data Interface.Fiber Distributed Data Interface (FDDI). The ANSIstandard for high-speed transmission over fiber opticcable.Fiber Optic Network. A network based on thetechnology and standards that define data transmissionusing cables of glass or plastic fibers carrying visiblelight. Fiber optic network advantages are: highertransmission speeds, greater carrying capacity, andlighter, more compact cable.file. In <strong>VM</strong> and OS/2, a named set of records storedor processed as a unit. Synonymous with data set inMVS.File Allocation Table (FAT).space on a disk for a file.A table used to allocateFile Transfer Access and Management (FTAM). Anapplication service element that enables userapplication processes to manage and access a filesystem, which may be distributed.File Transfer Protocol (FTP). A <strong>TCP</strong>/<strong>IP</strong> protocol usedfor transferring files to and from foreign hosts. FTP alsoprovides the capability to access directories. Passwordprotection is provided as part of the protocol.foreign host. Any machine on a network that can beinterconnected.foreign network. In an internet, any other networkinterconnected to the local network by one or moreintermediate gateways or routers.foreign node.See foreign host.frame. The portion of a tape on a line perpendicularto the reference edge, on which binary characters canbe written or read simultaneously.FTAM.File Transfer Access and Management.434 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


FTP.fullword.4 bytes.GFile Transfer Protocol.A computer word. In System/370, 32 bits orgadget. A windowless graphical object that looks likeits equivalent like-named widget but does not supportthe translations, actions, or pop-up widget childrensupplied by that widget.gateway. A functional unit that interconnects a localdata network with another network having differentprotocols. A host that connects a <strong>TCP</strong>/<strong>IP</strong> network to anon-<strong>TCP</strong>/<strong>IP</strong> network at the application layer. See alsorouter.gather and scatter data. Two related operations.During the gather operation, data is taken frommultiple buffers and transmitted. In the scatteroperation, data is received and stored in multiplebuffers.GC.GContext.GCS.GDDM.Graphics Context.See Graphics Context.Group Control System.Graphical Data Display Manager.GDDMXD. Graphical Data Display Manager interfacefor X Window System. A graphical interface thatformats and displays alphanumeric, data, graphics, andimages on workstation display devices that support theX Window System.GDF.Graphics data file.Graphical Display Data Manager (GDDM). A groupof routines that allows pictures to be defined anddisplayed procedurally through function routines thatcorrespond to graphic primitives.Graphics Context (GC). The storage area for graphicsoutput. Also known as GC and GContext. Used onlywith graphics that have the same root and depth as thegraphics content.Group Control System (GCS) . A component of<strong>VM</strong>/ESA, consisting of a shared segment that you canInitial Program Load (<strong>IP</strong>L) and run in a virtualmachine. It provides simulated MVS services andunique supervisor services to help support a nativeSNA network.Hhandle. A temporary data representation thatidentifies a file.halfword. A contiguous sequence of bits or charactersthat constitutes half a fullword and can be addressed asa unit.HASP.HDLC.Houston automatic spooling priority system.High-level Data Link Control.header file. A file that contains constant declarations,type declarations, and variable declarations andassignments. Header files are supplied with allprogramming interfaces.High-level Data Link Control (HDLC). An ISOprotocol for X.25 international communication.High Performance File System (HPFS). An OS/2 filemanagement system that supports high-speed bufferstorage, long file names, and extended attributes.hop count. The number of gateways or routersthrough which a packet passes on its way to itsdestination.host. A computer connected to a network, whichprovides an access method to that network. A hostprovides end-user services and can be a client, a server,or a client and server simultaneously.Houston automatic spooling priority system (HASP).A computer program that provides supplementary jobmanagement, data management, and task managementfunctions such as control of job flow, ordering of tasks,and spooling.HPFS.High Performance File System.HYPERchannel Adapter. A network interface used toconnect a <strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong> or MVS host into an existing<strong>TCP</strong>/<strong>IP</strong> HYPERchannel network, or to connect <strong>TCP</strong>/<strong>IP</strong>hosts together to create a <strong>TCP</strong>/<strong>IP</strong> HYPERchannelnetwork.IIAB.ICMP.IEEE.IETF.IGMP.IGP.Internet Activities Board.Internet Control Message Protocol.Institute of Electrical and Electronic Engineers.Internet Engineering Task Force.Internet Group Management Protocol (IGMP).Interior Gateway Protocol.include file. A file that contains preprocessor text,which is called by a program, using a standardprogramming call. Synonymous with header file.IMS.Information Management System.Glossary 435


Information Management System (IMS). Adatabase/data communication (DB/DC) system thatcan manage complex databases and networks.initial program load (<strong>IP</strong>L). The initializationprocedure that causes an operating system tocommence operation.instance. Indicates a label that is used to distinguishamong the variations of the principal name. An instanceallows for the possibility that the same client or servicecan exist in several forms that require distinctauthentication.Institute of Electrical and Electronic Engineers(IEEE). An electronics industry organization.Integrated Services Digital Network (ISDN). Adigital, end-to-end telecommunication network thatsupports multiple services including, but not limited to,voice and data.interactive. Pertaining to a program or a system thatalternately accepts input and then responds. Aninteractive system is conversational; that is, acontinuous dialog exists between user and system. Seebatch.Interior Gateway Protocol (IGP). The protocol used toexchange routing information between collaboratingrouters in the Internet. R<strong>IP</strong> is an example of an IGP.Internet. The largest internet in the world consistingof large national backbone nets (such as MILNET,NSFNET, and CREN) and a myriad of regional andlocal campus networks all over the world. The Internetuses the Internet protocol suite. To be on the Internet,you must have <strong>IP</strong> connectivity (be able to TELNET to,or PING, other systems). Networks with only electronicmail connectivity are not actually classified as being onthe Internet.Internet Activities Board (IAB). The technical bodythat oversees the development of the Internet suite ofprotocols (commonly referred to as <strong>TCP</strong>/<strong>IP</strong>). It has twotask forces (the IRTF and the IETF) each charged withinvestigating a particular area.Internet address. A 32-bit address assigned to hostsusing <strong>TCP</strong>/<strong>IP</strong>. An internet address consists of anetwork number and a local address. Internet addressesare represented in a dotted-decimal notation and areused to route packets through the network.Internet Engineering Task Force (IETF). One of thetask forces of the IAB. The IETF is responsible forsolving short-term engineering needs of the Internet.International Organization for Standardization (ISO).An organization of national standards bodies fromvarious countries established to promote developmentof standards to facilitate international exchange ofgoods and services, and develop cooperation inintellectual, scientific, technological, and economicactivity.internet or internetwork. A collection of packetswitching networks interconnected by gateways,routers, bridges, and hosts to function as a single,coordinated, virtual network.internet address. The unique 32-bit addressidentifying each node in an internet. See also address.Internet Control Message Protocol (ICMP). The partof the Internet Protocol layer that handles errormessages and control messages.Internet Group Management Protocol (IGMP).is used by <strong>IP</strong> hosts to report their host groupmemberships to multicast routers.IGMPInternet Protocol (<strong>IP</strong>). The <strong>TCP</strong>/<strong>IP</strong> layer between thehigher level host-to-host protocol and the local networkprotocols. <strong>IP</strong> uses local area network protocols to carrypackets, in the form of datagrams, to the next gateway,router, or destination host.interoperability. The capability of different hardwareand software by different vendors to effectivelycommunicate together.Inter-user communication vehicle (IUCV). A<strong>VM</strong>facility for passing data between virtual machines and<strong>VM</strong> components.intrinsics X-Toolkit. A set management mechanismthat provides for constructing and interfacing betweencomposite X Window widgets, their children, and otherclients. Also, intrinsics provide the ability to organize acollection of widgets into an application.<strong>IP</strong>.Internet Protocol.<strong>IP</strong> datagram. The fundamental unit of informationpassed across the Internet. An <strong>IP</strong> datagram containssource and destination addresses along with data and anumber of fields that define such things as the lengthof the datagram, the header checksum, and flags to saywhether the datagram can be (or has been) fragmented.<strong>IP</strong>L.ISDN.ISO.IUCV.JJCL.JES.Initial Program Load.Integrated Services Digital Network.International Organization for Standardization.Inter-User Communication Vehicle.Job Control Language.Job Entry Subsystem.436 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


JIS.Japanese Institute of Standards.Job Control Language (JCL). A problem-orientedlanguage designed to express statements in a job thatare used to identify the job or describe its requirementsto an operating system.Job Entry Subsystem (JES). An <strong>IBM</strong> System/370licensed program that receives jobs into the system andprocesses all output data produced by the jobs.JUNET. The Japanese Academic and ResearchNetwork that connects various UNIX operatingsystems.KKanji. A graphic character set consisting of symbolsused in Japanese ideographic alphabets. Each characteris represented by 2 bytes.katakana. A character set of symbols used on one ofthe two common Japanese phonetic alphabets, which isused primarily to write foreign words phonetically. Seealso kanji.Kerberos. A system that provides authenticationservice to users in a network environment.Kerberos Authentication System. An authenticationmechanism used to check authorization at the userlevel.LLaMail. The client that communicates with the OS/2Presentation Manager to manage mail on the network.LAN.Local area network.Line Printer Client (LPR). A client command thatallows the local host to submit a file to be printed on aremote print server.Line Printer Daemon (LPD). The remote printerserver that allows other hosts to print on a printer localto your host.little-endian. A format for storage or transmission ofbinary data in which the least significant bit (or byte)comes first. The reverse convention is big-endian.LLB.Local Location Broker.local area network (LAN). A data network located onthe user’s premises in which serial transmission is usedfor direct data communication among data stations.local host. In an internet, the computer to which auser’s terminal is directly connected without using theinternet.Local Location Broker (LLB). In Network ComputingSystem (NCS) Location Broker, a server that maintainsinformation about objects on the local host andprovides the Location Broker forwarding facility.local network. The portion of a network that isphysically connected to the host without intermediategateways or routers.logical character delete symbol. A special editingsymbol, usually the at (@) sign, which causes CP todelete it and the immediately preceding character fromthe input line. If many delete symbols are consecutivelyentered, the same number of preceding characters aredeleted from the input line.Logical Unit (LU). An entity addressable within anSNA-defined network. LUs are categorized by the typesof communication they support.LPD.LPR.LU.Line Printer Daemon.Line Printer Client.Logical Unit.LU-LU session. In SNA, a session between two logicalunits (LUs). It provides communication between twoend users, or between an end user and an LU servicescomponent.LU type. In SNA, the classification of an LU-LUsession in terms of the specific subset of SNA protocolsand options supported by the logical units (LUs) forthat session.MMAC.Media Access Control.mail gateway. A machine that connects two or moreelectronic mail systems (often different mail systems ondifferent networks) and transfers messages betweenthem.Management Information Base (MIB). A standardused to define SNMP objects, such as packet countsand routing tables, that are in a <strong>TCP</strong>/<strong>IP</strong> environment.mapping. The process of relating internet addresses tophysical addresses in the network.mask. A pattern of characters used to control retentionor elimination of portions of another pattern ofcharacters. To use a pattern of characters to controlretention or elimination of another pattern ofcharacters. A pattern of characters that controls thekeeping, deleting, or testing of portions of anotherpattern of characters.Maximum Transmission Unit (MTU). The largestpossible unit of data that can be sent on a givenphysical medium.Glossary 437


media access control (MAC). The method used bynetwork adapters to determine which adapter hasaccess to the physical network at a given time.Message Handling System (MHS). The system ofmessage user agents, message transfer agents, messagestores, and access units that together provide OSIelectronic mail.MHS.MIB.Message Handling System.Management Information Base.microcode. A code, representing the instructions of aninstruction set, which is implemented in a part ofstorage that is not program-addressable.MILNET.Military Network.Military Network (MILNET). Originally part of theARPANET, MILNET was partitioned in 1984 to make itpossible for military installations to have reliablenetwork service, while the ARPANET continued to beused for research. See DDN.minidisk. Logical divisions of a physical direct accessstorage device.modem (modulator/demodulator). A device thatconverts digital data from a computer to an analogsignal that can be transmitted on a telecommunicationline, and converts the analog signal received to data forthe computer.Motif.see OSF/Motif.mouse. An input device that is used to move a pointeron the screen and select items.MTU.Maximum Transmission Unit.multicast. The simultaneous transmission of datapackets to a group of selected nodes on a network orsubnetwork.multiconnection server. A server that is capable ofaccepting simultaneous, multiple connections.Multiple Virtual Storage (MVS). Implies MVS/370,the MVS/XA product, and the MVS/ESA product.multitasking. A mode of operation that provides forthe concurrent performance execution of two or moretasks.MVS.Nname server.about hosts.Multiple Virtual Storage.The server that stores resource recordsNational Science Foundation (NSF).NSFNET.Sponsor of theNational Science Foundation Network (NSFNET). Acollection of local, regional, and mid-level networks inthe U.S. tied together by a high-speed backbone.NSFNET provides scientists access to a number ofsupercomputers across the country.NCK**.NCP.NCS.NDB.NDIS.Network Computing Kernel.Network Control Program.Network Computing System.Network Database.Network Driver Interface Specification.Netman. This device keyword specifies that thisdevice is a 3172 LAN Channel Station that supports<strong>IBM</strong> Enterprise-Specific SNMP ManagementInformation Base (MIB) variables for 3172. <strong>TCP</strong>/<strong>IP</strong> for<strong>VM</strong> supports SNMP GET and SNMP GETNEXToperations to request and retrieve 3172Enterprise-Specific MIB variables. These requests areanswered only by those 3172 devices with theNETMAN option in the PROFILE <strong>TCP</strong><strong>IP</strong> file.NetView. A system 390-based, <strong>IBM</strong>-licensed programused to monitor, manage, and diagnose the problems ofa network.network. An arrangement of nodes and connectingbranches. Connections are made between data stations.Physical network refers to the hardware that makes upa network. Logical network refers to the abstractorganization overlaid on one or more physicalnetworks. An internet is an example of a logicalnetwork.network adapter. A physical device, and its associatedsoftware, that enables a processor or controller to beconnected to a network.network administrator. The person responsible for theinstallation, management, control, and configuration ofa network.Network Computing Kernel (NCK). In the NetworkComputing System (NCS), the combination of theremote procedure call runtime library and the LocationBroker.Network Computing System (NCS). A set of softwarecomponents developed by Apollo, Incorporated, thatconform to the Network Computing Architecture(NCA). NCS is made up of two parts: the nidl compilerand Network Computing Kernel (NCK). NCS is aprogramming tool kit that allows programmers todistribute processing power to other hosts.Network Control Program (NCP). An <strong>IBM</strong>-licensedprogram that provides communication controllersupport for single-domain, multiple-domain, andinterconnected network capability.438 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


network database (NDB). An <strong>IBM</strong>-licensed programthat provides communication controller support forsingle-domain, multiple-domain, and interconnectednetwork capability. NDB allows interoperability amongdifferent database systems, and uses RPC protocol witha client/server type of relationship. NDB is used fordata conversion, security, I/O buffer management, andtransaction management.Network Driver Interface Specification (NDIS). Anindustry-standard specification used by applications asan interface with network adapter device drivers.network elements. As defined in the SNMParchitecture, network elements are gateways, routers,and hosts that contain management agents responsiblefor performing the network management functionsrequested by the network management stations.network file system (NFS). The NFS protocol, whichwas developed by Sun Microsystems, Incorporated,allows computers in a network to access each other’sfile systems. Once accessed, the file system appears toreside on the local host.Network Information Center (NIC). Originally therewas only one, located at SRI International and tasked toserve the ARPANET (and later DDN) community.Today, there are many NICs operated by local, regional,and national networks all over the world. Such centersprovide user assistance, document service, training, andmore.Network Interface Definition Language (NIDL). Adeclarative language for the definition of interfaces thathas two forms, a Pascal-like syntax and a C-like syntax.NIDL is a component of the Network ComputingArchitecture.Network Job Entry (NJE). In object distribution, anentry in the network job table that specifies the systemaction required for incoming network jobs sent by aparticular user or group of users. Each entry isidentified by the user ID of the originating user orgroup.network layer. Layer 3 of the Open SystemsInterconnection (OSI) model; it defines protocolsgoverning data routing.network management stations. As defined in theSNMP architecture, network management stations, orSNMP clients, execute management applications thatmonitor and control network elements.NFS.NIC.NIDL.NJE.Network file system.Network Information Center.Network Interface Definition Language.Network Job Entry.node. In a network, a point at which one or morefunctional units connect channels or data circuits. In anetwork topology, the point at an end of a branch.nonblocking mode. If the execution of the programcannot continue until some event occurs, the operatingsystem does not suspend the program until that eventoccurs. Instead, the operating system returns an errormessage to the program.NPSI.NSF.NSFNET.Ooctet.X.25 NCP Packet Switching Interface.National Science Foundation.National Science Foundation Network.A byte composed of eight binary elements.OfficeVision (OV). <strong>IBM</strong>’s new proprietary, integratedoffice management system used for sending, receiving,and filing electronic mail, and a variety of other officetasks. OfficeVision replaces PROFSOffload host. Any device that is handling the <strong>TCP</strong>/<strong>IP</strong>processing for the MVS host where <strong>TCP</strong>/<strong>IP</strong> for MVS isinstalled. Currently, the only supported Offload host isthe 3172-3.Offload system. Represents both the MVS host where<strong>TCP</strong>/<strong>IP</strong> for MVS is installed and the Offload host thatis handling the <strong>TCP</strong>/<strong>IP</strong> Offload processing.open system. A system with specified standards andthat therefore can be readily connected to other systemsthat comply with the same standards.Open Systems Interconnection (OSI). Theinterconnection of open systems in accordance withspecific ISO standards. The use of standardizedprocedures to enable the interconnection of dataprocessing systems.Operating System/2 (OS/2). Pertaining to the <strong>IBM</strong>licensed program that can be used as the operatingsystem for personal computers. The OS/2 licensedprogram can perform multiple tasks at the same time.OS/2.Operating System/2.OSF/Motif. OSF/Motif is an X Window System toolkitdefined by Open Software Foundation, Inc. (OSF),which enables the application programmer to includestandard graphic elements that have a 3-D appearance.Performance of the graphic elements is increased withgadgets and windowless widgets.OSI.Open Systems Interconnection.out-of-band data. Data that is placed in a secondarychannel for transmission. Primary and secondarycommunication channels are created physically byGlossary 439


modulation on a different frequency, or logically byspecifying a different logical channel. A primarychannel can have a greater capacity than a secondaryone.OV.POfficeVision.packet. A sequence of binary digits, including dataand control signals, that is transmitted and switched asa composite whole.Packet Switching Data Network (PSDN). A networkthat uses packet switching as a means of transmittingdata.parameter. A variable that is given a constant valuefor a specified application.parse. To analyze the operands entered with acommand.passive open. The state of a connection that isprepared to provide a service on demand. Contrastwith active open.Partitioned data set (PDS). A data set in direct accessstorage that is divided into partitions, called members,each of which can contain a program, part of aprogram, or data.PC.PCA.Personal computer.Personal Channel Attach.PC Network. A low-cost, broadband network thatallows attached <strong>IBM</strong> personal computers, such as <strong>IBM</strong>5150 Personal Computers, <strong>IBM</strong> Computer ATs, <strong>IBM</strong>PC/XTs, and <strong>IBM</strong> Portable Personal Computers tocommunicate and to share resources.PDS.PDN.PDU.Partitioned data set.Public Data Network.Protocol data unit.peer-to-peer. In network architecture, any functionalunit that resides in the same layer as another entity.Personal Channel Attach (PCA).Channel Attach.see Personal SystemPersonal Computer (PC). A microcomputer primarilyintended for stand-alone use by an individual.Personal System Channel Attach (PSCA). An adaptercard to connect a micro-channel based personalcomputer (or processor) to a System/370 parallelchannel.physical layer. Layer 1 of the Open SystemsInterconnection (OSI) model; it details protocolsgoverning transmission media and signals.physical unit (PU). In SNA, the component thatmanages and monitors the resources, such as attachedlinks and adjacent link stations, associated with a node,as requested by an SSPC via an SSPC-PU session. AnSSPC activates a session with the physical unit in orderto indirectly manage, through the PU, resources of thenode such as attached links.PING. The command that sends an ICMP EchoRequest packet to a host, gateway, or router with theexpectation of receiving a reply.PM.Presentation Manager.PMANT. In OS/2, the 3270 client terminal emulationprogram that is invoked by the PMANT command.polling. On a multipoint connection or apoint-to-point connection, the process whereby datastations are invited one at a time to transmit.Interrogation of devices for such purposes as to avoidcontention, to determine operational status, or todetermine readiness to send or receive data.POP.Post Office Protocol.port. An endpoint for communication betweendevices, generally referring to a logical connection. A16-bit number identifying a particular TransmissionControl Protocol or User Datagram Protocol resourcewithin a given <strong>TCP</strong>/<strong>IP</strong> node.PORTMAP.Synonymous with Portmapper.Portmapper. A program that maps client programs tothe port numbers of server programs. Portmapper isused with Remote Procedure Call (RPC) programs.Post Office Protocol (POP).exchanging network mail.A protocol used forpresentation layer. Layer 6 of the Open SystemsInterconnections (OSI) model; it defines protocolsgoverning data formats and conversions.Presentation Manager (PM). A component of OS/2that provides a complete graphics-based user interface,with pull-down windows, action bars, and layeredmenus.principal name. Specifies the unique name of a user(client) or service.PostScript. A standard that defines how text andgraphics are presented on printers and display devices.process. A unique, finite course of events defined byits purpose or by its effect, achieved under definedconditions. Any operation or combination of operationson data. A function being performed or waiting to be440 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


performed. A program in operation; for example, adaemon is a system process that is always running onthe system.Professional Office Systems (PROFS). <strong>IBM</strong>’sproprietary, integrated office management system usedfor sending, receiving, and filing electronic mail, and avariety of other office tasks. PROFS has been replacedby OfficeVision. See OfficeVision.PROFS.Professional Office Systems.protocol. A set of semantic and syntactic rules thatdetermines the behavior of functional units in achievingcommunication. Protocols can determine low-leveldetails of machine-to-machine interfaces, such as theorder in which bits from a byte are sent; they can alsodetermine high-level exchanges between applicationprograms, such as file transfer.Protocol data unit (PDU). A set of commands used bythe SNMP agent to request management station data.protocol suite. A set of protocols that cooperate tohandle the transmission tasks for a data communicationsystem.PSCA.PSDN.PU.Personal System Channel Attach.Packet Switching Data Network.Physical unit.Public Data Network (PDN). A network establishedand operated by a telecommunication administration orby a Recognized Private Operating Agency (RPOA) forthe specific purpose of providing circuit-switched,packet-switched, and leased-circuit services to thepublic.Qqueue. A line or list formed by items in a systemwaiting for service; for example, tasks to be performedor messages to be transmitted. To arrange in, or form, aqueue.RRACF.RARP.Resource access control facility.Reverse Address Resolution Protocol.read-only access. An access mode associated with avirtual disk directory that lets a user read, but not writeor update, any file on the disk directory.read/write access. An access mode associated with avirtual disk directory that lets a user read and writeany file on the disk directory (if write authorized).realm. One of the three parts of a Kerberos name. Therealm specifies the network address of the principalname or instance. This address must be expressed as afully qualified domain name, not as a “dot numeric”internet address.recursion. A process involving numerous steps, inwhich the output of each step is used for the successivestep.reduced instruction-set computer (RISC). A computerthat uses a small, simplified set of frequently usedinstructions for rapid execution.reentrant. The attribute of a program or routine thatallows the same copy of a program or routine to beused concurrently by two or more tasks.Remote Execution Protocol (REXEC). A protocol thatallows the execution of a command or program on aforeign host. The local host receives the results of thecommand execution. This protocol uses the REXECcommand.remote host. A machine on a network that requires aphysical link to interconnect with the network.remote logon. The process by which a terminal userestablishes a terminal session with a remote host.Remote Procedure Call (RPC). A facility that a clientuses to request the execution of a procedure call from aserver. This facility includes a library of procedures andan eXternal data representation.Remote Spooling Communications Subsystem(RSCS). An <strong>IBM</strong>-licensed program that transfers spoolfiles, commands, and messages between <strong>VM</strong> users,remote stations, and remote and local batch systems,through HASP-compatible telecommunication facilities.Request For Comments (RFC). A series of documentsthat covers a broad range of topics affectinginternetwork communication. Some RFCs areestablished as internet standards.resolver. A program or subroutine that obtainsinformation from a name server or local table for useby the calling program.resource access control facility (RACF). An<strong>IBM</strong>-licensed program that provides for access controlby identifying and by verifying the users to the system,authorizing access to protected resources, logging thedetected unauthorized attempts to enter the system,and logging the detected accesses to protectedresources.resource records. Individual records of data used bythe Domain Name System. Examples of resourcerecords include the following: a host’s Internet Protocoladdresses, preferred mail addresses, and aliases.Glossary 441


esponse unit (RU). In SNA, a message unit thatacknowledges a request unit. It may contain prefixinformation received in a request unit. If positive, theresponse unit may contain additional information suchas session parameters in response to BIND SESSION. Ifnegative, it contains sense data defining the exceptioncondition.Restructured Extended Executor (REXX) language. Ageneral purpose programming language, particularlysuitable for EXEC procedures, XEDIT macros, orprograms for personal computing. Procedures, XEDITmacros, and programs written in this language can beinterpreted by the Procedures Language <strong>VM</strong>/REXXinterpreter.return code. A code used to influence the execution ofsucceeding instructions. A value returned to a programto indicate the results of an operation requested by thatprogram.Reverse Address Resolution Protocol (RARP). Aprotocol that maintains a database of mappingsbetween physical hardware addresses and <strong>IP</strong> addresses.REXEC.REXX.RFC.R<strong>IP</strong>.RISC.Remote Execution Protocol.Restructured Extended Executor language.Request For Comments.Routing Information Protocol.Reduced instruction-set computer.router. A device that connects networks at the ISONetwork Layer. A router is protocol-dependent andconnects only networks operating the same protocol.Routers do more than transmit data; they also select thebest transmission paths and optimum sizes for packets.In <strong>TCP</strong>/<strong>IP</strong>, routers operate at the Internetwork layer.See also gateway.Routing Information Protocol (R<strong>IP</strong>). The protocol thatmaintains routing table entries for gateways, routers,and hosts.routing table. A list of network numbers and theinformation needed to route packets to each.RPC.RSCS.RU.SSAA.SBCS.SDLC.Remote Procedure Call.Remote Spooling Communications Subsystem.Response unit.Systems Application Architecture.Single Byte Character Set.Synchronous data link control.Sendmail. The OS/2 mail server that uses SimpleMail Transfer Protocol to route mail from one host toanother host on the network.serial line. A network media that is a de factostandard, not an international standard, commonlyused for point-to-point <strong>TCP</strong>/<strong>IP</strong> connections. Generally,a serial line consists of an RS-232 connection into amodem and over a telephone line.semantics. The relationships of characters or groups ofcharacters to their meanings, independent of themanner of their interpretation and use. Therelationships between symbols and their meanings.server. A function that provides services for users. Amachine can run client and server processes at thesame time.SFS.Shared File System.Shared File System (SFS). A part of CMS that letsusers organize their files into groups known asdirectories and selectively share those files anddirectories with other users.Simple Mail Transfer Protocol (SMTP). A <strong>TCP</strong>/<strong>IP</strong>application protocol used to transfer mail betweenusers on different systems. SMTP specifies how mailsystems interact and the format of control messagesthey use to transfer mail.Simple Network Management Protocol (SNMP). Aprotocol that allows network management by elements,such as gateways, routers, and hosts. This protocolprovides a means of communication between networkelements regarding network resources.simultaneous peripheral operations online (SPOOL).(Noun) An area of auxiliary storage defined totemporarily hold data during its transfer betweenperipheral equipment and the processor. (Verb) To useauxiliary storage as a buffer storage to reduceprocessing delays when transferring data betweenperipheral equipment and the processing storage of acomputer.single-byte character set (SBCS). A character set inwhich each character is represented by a one-byte code.Contrast with double-byte character set.SMI.SMTP.SNA.SNALINK.Structure for Management Information.Simple Mail Transfer Protocol.Systems Network Architecture.SNA Network Link.SNA Network Link. An SNA network link function of<strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong> and MVS hosts running <strong>TCP</strong>/<strong>IP</strong> tocommunicate through an existing SNA backbone.SNMP.Simple Network Management Protocol.442 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


SOA.Start of authority record.socket. An endpoint for communication betweenprocesses or applications. A pair consisting of <strong>TCP</strong> portand <strong>IP</strong> address, or UDP port and <strong>IP</strong> address.socket address. An address that results when the portidentification number is combined with an internetaddress.socket interface. An application interface that allowsusers to write their own applications to supplementthose supplied by <strong>TCP</strong>/<strong>IP</strong>.SPOOL.Simultaneous peripheral operations online.spooling. The processing of files created by orintended for virtual readers, punches, and printers. Thespool files can be sent from one virtual device toanother, from one virtual machine to another, and toread devices.SQL.SQL/DS.Structured Query Language.Structured Query Language/Data System.start of authority record (SOA). In the Domain NameSystem, the resource record that defines a zone.stream. A continuous sequence of data elements beingtransmitted, or intended for transmission, in characteror binary-digit form, using a defined format.Structured Query Language (SQL). Fourth generationEnglish-like programming language used to performqueries on relational databases.Structured Query Language/Data System (SQL/DS).An <strong>IBM</strong> relational database management system for the<strong>VM</strong> and VSE operating systems.Structure for Management Information (SMI). Therules used to define the objects that can be accessedthrough a network management protocol. See also MIB.subagent. In the SNMP architecture, a subagentprovides an extension to the utility provided by theSNMP agent.subdirectory. A directory contained within anotherdirectory in a file system hierarchy.subnet. A networking scheme that divides a singlelogical network into smaller physical networks tosimplify routing.subnet address. The portion of the host address thatidentifies a subnetwork.subnet mask. A mask used in the <strong>IP</strong> protocol layer toseparate the subnet address from the host portion ofthe address.subsystem. A secondary or subordinate system,usually capable of operating independent of, orasynchronously with, a controlling system.SYNC.Synchronous.synchronous (SYNC). Pertaining to two or moreprocesses that depend on the occurrences of a specificevent such as common timing signal. Occurring with aregular or predictable time relationship. Seeasynchronous.synchronous data link control (SDLC). A data linkover which communication is conducted using thesynchronous data protocol.Systems Application Architecture (SAA). A formalset of rules that enables applications to be run withoutmodification in different computer environments.Systems Network Architecture (SNA). Thedescription of the logical structure, formats, protocols,and operational sequences for transmitting informationunits through, and controlling the configuration andoperation of, networks.TTALK. An interactive messaging system that sendsmessages between the local host and a foreign host.<strong>TCP</strong>.Transmission Control Protocol.<strong>TCP</strong>/<strong>IP</strong>. Transmission Control Protocol/InternetProtocol.Telnet. The Terminal Emulation Protocol, a <strong>TCP</strong>/<strong>IP</strong>application protocol for remote connection service.Telnet allows a user at one site to gain access to aforeign host as if the user’s terminal were connecteddirectly to that foreign host.terminal emulator. A program that imitates thefunction of a particular kind of terminal.Terminate and Stay Resident (TSR) program. A TSRis a program that installs part of itself as an extensionof DOS when it is executed.TFTPD.Trivial File Transfer Protocol Daemon.ticket. Encrypted information obtained from aKerberos authentication server or a ticket-grantingserver. A ticket authenticates a user and, in conjunctionwith an authenticator, serves as permission to access aservice when presented by the authenticated user.ticket-granting server. Grants Kerberos tickets toauthenticated users as permission to access anend-service.subnetwork.Synonymous with subnet.Glossary 443


Time Sharing Option (TSO). An operating systemoption; for System/370 system, the option providesinteractive time sharing from remote terminalstime stamp. To apply the current system time. Thevalue on an object that is an indication of the systemtime at some critical point in the history of the object.In query, the identification of the day and time when aquery report was created that query automaticallyprovides on each report.TN3270. An informally defined protocol fortransmitting 3270 data streams over Telnet.token. In a local network, the symbol of authoritypassed among data stations to indicate the stationtemporarily in control of the transmission medium.token-bus.See bus topology.token ring. As defined in IEEE 802.5, acommunication method that uses a token to controlaccess to the LAN. The difference between a token busand a token ring is that a token-ring LAN does not usea master controller to control the token. Instead, eachcomputer knows the address of the computer thatshould receive the token next. When a computer withthe token has nothing to transmit, it passes the token tothe next computer in line.token-ring network. A ring network that allowsunidirectional data transmission between data stationsby a token-passing procedure over one transmissionmedium, so that the transmitted data returns to thetransmitting station.Transmission Control Protocol (<strong>TCP</strong>). The <strong>TCP</strong>/<strong>IP</strong>layer that provides reliable, process-to-process datastream delivery between nodes in interconnectedcomputer networks. <strong>TCP</strong> assumes that <strong>IP</strong> (InternetProtocol) is the underlying protocol.Transmission Control Protocol/Internet Protocol(<strong>TCP</strong>/<strong>IP</strong>). A suite of protocols designed to allowcommunication between networks regardless of thetechnologies implemented in each network.transport layer. Layer 4 of the Open SystemsInterconnection (OSI) model; it defines protocolsgoverning message structure and some error checking.TRAP. An unsolicited message that is sent by anSNMP agent to an SNMP network management station.Trivial File Transfer Protocol Daemon (TFTPD). TheTFTP daemon (TFTPD server) transfers files betweenthe Byte File System (BFS) and TFTP clients. TFTPDsupports access to files maintained in a BFS directorystructure that is mounted.TSO.Time Sharing Option.TSR. Terminate and stay resident. TSR usually refersto a terminate-and-stay-resident program.UUDP.User Datagram Protocol.user. A function that uses the services provided by aserver. A host can be a user and a server at the sametime. See client.User Datagram Protocol (UDP). A datagram levelprotocol built directly on the <strong>IP</strong> layer. UDP is used forapplication-to-application programs between <strong>TCP</strong>/<strong>IP</strong>hosts.user exit. A point in an <strong>IBM</strong>-supplied program atwhich a user routine may be given control.user profile. A description of a user, including userID, user name, defaults, password, access authorization,and attributes.Vvirtual address. The address of a location in virtualstorage. A virtual address must be translated into a realaddress to process the data in processor storage.Virtual Machine (<strong>VM</strong>). Licensed software whose fullname is Virtual Machine/Enterprise SystemsArchitecture (<strong>VM</strong>/ESA) It is a software operatingsystem that manages the resources of a real processorto provide virtual machines to end users. It includestime-sharing system control program (CP), theconversational monitor system (CMS), the groupcontrol system (GCS), and the dump viewing facility(DVF).Virtual Machine Communication Facility (<strong>VM</strong>CF). Aconnectionless mechanism for communication betweenaddress spaces.Virtual Machine/System Product (<strong>VM</strong>/SP). An<strong>IBM</strong>-licensed program that manages the resources of asingle computer so that multiple computing systemsappear to exist. Each virtual machine is the functionalequivalent of a real machine.virtual storage. Storage space that can be regarded asaddressable main storage by the user of a computersystem in which virtual addresses are mapped into realaddresses. The size of virtual storage is limited by theaddressing scheme of the computing system and by theamount of auxiliary storage available, not by the actualnumber of main storage locations.Virtual Telecommunications Access Method (VTAM).An <strong>IBM</strong>-licensed program that controls communicationand the flow of data in an SNA network. It providessingle-domain, multiple-domain, and interconnectednetwork capability.444 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


<strong>VM</strong>.<strong>VM</strong>CF.Virtual Machine.Virtual Machine Communication Facility.<strong>VM</strong>/ESA. Virtual Machine/Enterprise SystemArchitecture<strong>VM</strong>SES/E. Virtual Machine ServiceabilityEnhancements Staged/Extended.VTAM.WWAN.Virtual Telecommunications Access Method.Wide area network.well-known port. A port number that has beenpreassigned for specific use by a specific protocol orapplication. Clients and servers using the same protocolcommunicate over the same well-known port.wide area network (WAN). A network that providescommunication services to a geographic area largerthan that served by a local area network.widget. The basic data type of the X Window SystemToolkit. Every widget belongs to a widget class thatcontains the allowed operations for that correspondingclass.window. An area of the screen with visible boundariesthrough which a panel or portion of a panel isdisplayed.working directory. The directory in which anapplication program is found. The working directorybecomes the current directory when the application isstarted.X Window System API. An application programinterface designed as a distributed,network-transparent, device-independent, windowingand graphics system.X Window System Toolkit.application environments.Functions for developingX.25. A CCITT communication protocol that definesthe interface between data terminal equipment andpacket switching networks.X.25 NCP Packet Switching Interface (X.25 NPSI). An<strong>IBM</strong>-licensed program that allows users tocommunicate over packet switched data networks thathave interfaces complying with Recommendation X.25(Geneva** 1980) of the CCITT. It allows SNA programsto communicate with SNA equipment or with non-SNAequipment over such networks.ZZAP. To modify or dump an individual text file/dataset using the ZAP command or the ZAPTEXT EXEC.ZAP disk. The virtual disk in the <strong>VM</strong> operatingsystem that contains the user-written modifications toVTAM code.zone. In the Domain Name System, a zone is a logicalgrouping of domain names that is assigned to aparticular organization. Once an organization controlsits own zone, it can change the data in the zone, addnew tree sections connected to the zone, delete existingnodes, or delegate new subzones under its zone.XX Client. An application program which uses the Xprotocol to communicate windowing and graphicsrequests to an X Server.XDR.eXternal Data Representation.XEDIT. The CMS facility, containing the XEDITcommand and XEDIT subcommands and macros, thatlets a user create, change, and manipulate CMS files.X Server. A program which interprets the X protocoland controls one or more screens, a pointing device, akeyboard, and various resources associated with the XWindow System, such as Graphics Contexts, Pixmaps,and color tables.X Window System. The X Window System is aprotocol designed to support network transparentwindowing and graphics. <strong>TCP</strong>/<strong>IP</strong> for <strong>VM</strong> and MVSprovides client support for the X Window Systemapplication program interface.Glossary 445


446 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


BibliographyThis bibliography lists the publications thatprovide information about your z/<strong>VM</strong> system.The z/<strong>VM</strong> library includes z/<strong>VM</strong> basepublications, publications for additional facilitiesincluded with z/<strong>VM</strong>, and publications for z/<strong>VM</strong>optional features. For abstracts of z/<strong>VM</strong>publications and information about currenteditions and available publication formats, seez/<strong>VM</strong>: General Information.z/<strong>VM</strong> Base PublicationsEvaluationv z/<strong>VM</strong>: Licensed Program Specifications, GC24-5943v z/<strong>VM</strong>: General Information, GC24-5944Installation and Servicev z/<strong>VM</strong>: Installation Guide, GC24-5945v z/<strong>VM</strong>: Service Guide, GC24-5946v z/<strong>VM</strong>: <strong>VM</strong>SES/E Introduction and <strong>Reference</strong>,GC24-5947Planning and Administrationv z/<strong>VM</strong>: Planning and Administration, SC24-5948v z/<strong>VM</strong>: CMS File Pool Planning, Administration,and Operation, SC24-5949v z/<strong>VM</strong>: Migration Guide, GC24-5928v <strong>VM</strong>/ESA: REXX/EXEC Migration Tool for<strong>VM</strong>/ESA, GC24-5752v z/<strong>VM</strong>: Running Guest Operating Systems,SC24-5950v <strong>VM</strong>/ESA: Connectivity Planning, Administration,and Operation, SC24-5756v z/<strong>VM</strong>: Group Control System, SC24-5951v z/<strong>VM</strong>: Performance, SC24-5952Customizationv z/<strong>VM</strong>: CP Exit Customization, SC24-5953Operationv z/<strong>VM</strong>: System Operation, SC24-5954v z/<strong>VM</strong>: Virtual Machine Operation, SC24-5955Application Programmingv z/<strong>VM</strong>: CP Programming Services, SC24-5956v z/<strong>VM</strong>: CMS Application Development Guide,SC24-5957v z/<strong>VM</strong>: CMS Application Development Guide forAssembler, SC24-5958v z/<strong>VM</strong>: CMS Callable Services <strong>Reference</strong>, SC24-5959v z/<strong>VM</strong>: CMS Macros and Functions <strong>Reference</strong>,SC24-5960v z/<strong>VM</strong>: CMS Application Multitasking, SC24-5961v <strong>VM</strong>/ESA: REXX/<strong>VM</strong> Primer, SC24-5598v z/<strong>VM</strong>: REXX/<strong>VM</strong> User’s Guide, SC24-5962v z/<strong>VM</strong>: REXX/<strong>VM</strong> <strong>Reference</strong>, SC24-5963v z/<strong>VM</strong>: OpenExtensions POSIX ConformanceDocument, GC24-5976v z/<strong>VM</strong>: OpenExtensions User’s Guide, SC24-5977v z/<strong>VM</strong>: OpenExtensions Command <strong>Reference</strong>,SC24-5978v z/<strong>VM</strong>: OpenExtensions Advanced ApplicationProgramming Tools, SC24-5979v z/<strong>VM</strong>: OpenExtensions Callable Services <strong>Reference</strong>,SC24-5980v z/<strong>VM</strong>: Reusable Server Kernel Programmer’s Guideand <strong>Reference</strong>, SC24-5964v z/<strong>VM</strong>: Enterprise Systems Architecture/ExtendedConfiguration Principles of Operation, SC24-5965v C for <strong>VM</strong>/ESA: Library <strong>Reference</strong>, SC23-3908v OS/390: DFSMS Program Management,SC27-0806v z/<strong>VM</strong>: Program Management Binder for CMS,SC24-5934v Debug Tool User’s Guide and <strong>Reference</strong>, SC09-2137v External Security Interface (RACROUTE) Macro<strong>Reference</strong> for MVS and <strong>VM</strong>, GC28-1366v <strong>VM</strong>/ESA: Programmer’s Guide to theServer-Requester Programming Interface for <strong>VM</strong>,SC24-5455v <strong>VM</strong>/ESA: CPI Communications User’s Guide,SC24-5595v Common Programming Interface Communications<strong>Reference</strong>, SC26-4399v Common Programming Interface Resource Recovery<strong>Reference</strong>, SC31-6821© Copyright <strong>IBM</strong> Corp. 1987, 2001 447


End Usev z/<strong>VM</strong>: CP Command and Utility <strong>Reference</strong>,SC24-5967v <strong>VM</strong>/ESA: CMS Primer, SC24-5458v z/<strong>VM</strong>: CMS User’s Guide, SC24-5968v z/<strong>VM</strong>: CMS Command <strong>Reference</strong>, SC24-5969v z/<strong>VM</strong>: CMS Pipelines User’s Guide, SC24-5970v z/<strong>VM</strong>: CMS Pipelines <strong>Reference</strong>, SC24-5971v CMS/TSO Pipelines: Author’s Edition, SL26-0018v z/<strong>VM</strong>: XEDIT User’s Guide, SC24-5972v z/<strong>VM</strong>: XEDIT Command and Macro <strong>Reference</strong>,SC24-5973v z/<strong>VM</strong>: Quick <strong>Reference</strong>, SC24-5986Diagnosisv z/<strong>VM</strong>: System Messages and Codes, GC24-5974v z/<strong>VM</strong>: Diagnosis Guide, GC24-5975v z/<strong>VM</strong>: <strong>VM</strong> Dump Tool, GC24-5887v z/<strong>VM</strong>: Dump Viewing Facility, GC24-5966Publications for AdditionalFacilitiesDFSMS/<strong>VM</strong> ®v <strong>VM</strong>/ESA: DFSMS/<strong>VM</strong> Function Level 221Planning Guide, GC35-0121v <strong>VM</strong>/ESA: DFSMS/<strong>VM</strong> Function Level 221Installation and Customization, SC26-4704v <strong>VM</strong>/ESA: DFSMS/<strong>VM</strong> Function Level 221 StorageAdministration Guide and <strong>Reference</strong>, SH35-0111v <strong>VM</strong>/ESA: DFSMS/<strong>VM</strong> Function Level 221Removable Media Services User’s Guide and<strong>Reference</strong>, SC35-0141v <strong>VM</strong>/ESA: DFSMS/<strong>VM</strong> Function Level 221Messages and Codes, SC26-4707v <strong>VM</strong>/ESA: DFSMS/<strong>VM</strong> Function Level 221Diagnosis Guide, LY27-9589OSA/SFv S/390: Planning for the S/390 Open SystemsAdapter (OSA-1, OSA-2) Feature, GC23-3870v <strong>VM</strong>/ESA: Open Systems Adapter Support FacilityUser’s Guide for OSA-2, SC28-1992v S/390: Open Systems Adapter-Express Customer’sGuide and <strong>Reference</strong>, SA22-7403Language Environment ®v Language Environment for OS/390 & <strong>VM</strong>:Concepts Guide, GC28-1945v Language Environment for OS/390 & <strong>VM</strong>:Migration Guide, SC28-1944v Language Environment for OS/390 & <strong>VM</strong>:Programming Guide, SC28-1939v Language Environment for OS/390 & <strong>VM</strong>:Programming <strong>Reference</strong>, SC28-1940v Language Environment for OS/390 & <strong>VM</strong>: WritingInterlanguage Communication Applications,SC28-1943v Language Environment for OS/390 & <strong>VM</strong>:Debugging Guide and Run-Time Messages,SC28-1942Publications for OptionalFeaturesCMS Utilities Featurev <strong>VM</strong>/ESA: CMS Utilities Feature, SC24-5535<strong>TCP</strong>/<strong>IP</strong> Feature for z/<strong>VM</strong>v z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Level 3A0 Planning andCustomization, SC24-5981v z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Level 3A0 User’s Guide, SC24-5982v z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Level 3A0 Programmer’s <strong>Reference</strong>,SC24-5983v z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Level 3A0 Messages and Codes,GC24-5984v z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Level 3A0 Diagnosis Guide,GC24-5985OpenEdition ® DCE Feature for<strong>VM</strong>/ESA ®v OpenEdition DCE for <strong>VM</strong>/ESA: Introducing theOpenEdition Distributed Computing Environment,SC24-5735v OpenEdition DCE for <strong>VM</strong>/ESA: Planning,SC24-5737v OpenEdition DCE for <strong>VM</strong>/ESA: Configuring andGetting Started, SC24-5734v OpenEdition DCE for <strong>VM</strong>/ESA: AdministrationGuide, SC24-5730v OpenEdition DCE for <strong>VM</strong>/ESA: Administration<strong>Reference</strong>, SC24-5731v OpenEdition DCE for <strong>VM</strong>/ESA: ApplicationDevelopment Guide, SC24-5732448 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


v OpenEdition DCE for <strong>VM</strong>/ESA: ApplicationDevelopment <strong>Reference</strong>, SC24-5733v OpenEdition DCE for <strong>VM</strong>/ESA: User’s Guide,SC24-5738v OpenEdition DCE for <strong>VM</strong>/ESA: Messages andCodes, SC24-5736LANRES/<strong>VM</strong>v LAN Resource Extension and Services/<strong>VM</strong>:Licensed Program Specifications, GC24-5617v LAN Resource Extension and Services/<strong>VM</strong>: GeneralInformation, GC24-5618v LAN Resource Extension and Services/<strong>VM</strong>: Guideand <strong>Reference</strong>, SC24-5622v "Network Management of <strong>TCP</strong>/<strong>IP</strong> Networks:Present and Future," A. Ben-Artzi, A. Chandna,V. Warrier.v "Special Issue: Network Management andNetwork Security,"ConneXions-TheInteroperability Report, Volume 4, No. 8, August1990.v The Art of Distributed Application: ProgrammingTechniques for Remote Procedure Calls, John R.Corbin, Springer-Verlog, 1991.v The Simple Book: An Introduction to Managementof <strong>TCP</strong>/<strong>IP</strong>-based Internets, Marshall T Rose,Prentice Hall, Englewood Cliffs, New Jersey,1991.CD-ROMThe following CD-ROM contains all the <strong>IBM</strong>libraries that are available in <strong>IBM</strong> BookManager ®format for current <strong>VM</strong> system products andcurrent <strong>IBM</strong> licensed programs that run on <strong>VM</strong>. Italso contains PDF versions of z/<strong>VM</strong> publicationsand publications for some related <strong>IBM</strong> licensedprograms.v Online Library Omnibus Edition: <strong>VM</strong> Collection,SK2T-2067Note: Only unlicensed publications are included.Other <strong>TCP</strong>/<strong>IP</strong> RelatedPublicationsThis section lists other publications, outside thez/<strong>VM</strong> 3.1.0 library, that you may find helpful.v <strong>TCP</strong>/<strong>IP</strong> Tutorial and Technical Overview,GG24-3376v <strong>TCP</strong>/<strong>IP</strong> Illustrated, Volume 1: The Protocols,SR28-5586v Internetworking with <strong>TCP</strong>/<strong>IP</strong> Volume I: Principles,Protocols, and Architecture, SC31-6144v Internetworking With <strong>TCP</strong>/<strong>IP</strong> Volume II:Implementation and Internals, SC31-6145v Internetworking With <strong>TCP</strong>/<strong>IP</strong> Volume III:Client-Server Programming and Applications,SC31-6146v DNS and BIND in a Nutshell, SR28-4970v "MIB II Extends SNMP Interoperability," C.Vanderberg, Data Communications, October 1990.v "Network Management and the Design of SNMP,"J.D. Case, J.R. Davin, M.S. Fedor, M.L.Schoffstall.Bibliography 449


450 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


IndexAabbreviations and acronyms 421accept() 22ACCEPT (IUCV) 177address, socket 7address families, socket 6address information file 18Addressing within an internet domain 7Addressing within an IUCV domain 8AddUserNote 110administration server 306AF_INET address family 6AF_INET domain example 26AF_IUCV address family 6AF_IUCV domain example 27Aliases information file 18APITYPE=3 (multiple request) 174applications program interface (API)IUCV sockets API 171ASCII to EBCDIC translation tables 18associate table functions 293asynchronous communication, sequence(Pascal API) 95auth_destroy() 207authenticators 304communicating 304name structures 303tickets 304authentication server 303, 305authnone_create() 208authunix_create() 208authunix_create_default() 208BBeginTcpIp (Pascal) 110Berkeley socket implementation 17big endian byte ordering convention 7bind() 23BIND (IUCV) 178BUFFERspaceAVAILABLE (<strong>VM</strong>CF) 164byte order, network 7CC socket application programminginterface 5C socket callsgetibmsockopt()call example 37description 36return values 38ibmsflush() 51setibmsockopt()call example 72, 74description 72return values 74structure elements 73sock_debug() 79sock_debug_bulk_perf0()description 80C socket calls (continued)sock_debug_bulk_perf0() (continued)example 80sock_do_bulkmode() 80sock_do_teststor() 81C socket program library 89C socket programs, examples<strong>TCP</strong> client 89<strong>TCP</strong> server 90UDP client 92UDP server 93C Socket Quick <strong>Reference</strong> 19callrpc() 209ClearTimer 111clientKerberos 179, 318, 320remote procedure calls 201SNMP DPI programs 337client verification exit, SMTP 373clnt_broadcast() 209clnt_call() 211clnt_destroy() 213clnt_freeres() 213clnt_geterr() 213clnt_pcreateerror() 214clnt_perrno() 214clnt_perror() 214clnt_spcreateerror() 215clnt_sperrno() 215clnt_sperror() 216clntcp_create() 212clntraw_create() 216clnttcp_create() 217clntudp_create() 217close() 27command exit, SMTP 384compiling and linkinggeneral for all APIs 1SNMP DPI 328X Windows 254connect() 27CONNECT (IUCV) 180connection information record(Pascal) 97connection states (Pascal) 96CONNECTIONclosing (Pascal) 96CONNECTIONstateCHANGED(<strong>VM</strong>CF) 164CreateTimer 111CREDENTIALS structure 309DDATA 363data structuresPascal 96<strong>VM</strong>CF 147DATAdelivered (<strong>VM</strong>CF) 164datagram socket, interface 5<strong>TCP</strong><strong>IP</strong>.DATA 79, 81debugging messages 19DestroyTimer 111directoriesKerberos 307remote procedure calls 206sockets 8DPI client program 337, 339EEBCDIC to ASCII translation tables 18EHLO 361EndTcpIp (Pascal) 111envelope, SMTPdescription 359example 369environment variables 17HOSTALIASES 18SOCK_DEBUG 19X-ADDR 18X-SITE 18X-XLATE 18ETC SERVICES file 413exit routines, SMTP 373, 390Exits, ServerTelnet 391EXPN 368extension routines (X windowsystem) 292eXternal Data Representation protocol,general information 201FFCNTL (IUCV) 180fDPIparse() 330file specification record (Pascal) 105ForeignSocket 98GGET, SNMP DPI request 327get_myaddress() 218GET-NEXT, SNMP DPI request 327GETCLIENTID (IUCV) 181getdtablesize() 33gethostbyaddr() 33gethostbyname() 34gethostent() 35gethostid() 36GETHOSTID (IUCV) 182gethostname() 36Gethostname (REXX) 182GetHostNumber 112GetHostResol 112GetHostString 113Get<strong>IBM</strong>Sockopt 36GetIdentity 113getnetbyaddr() 38getnetbyname() 39getnetent() 40GetNextNote 113getpeername() 40© Copyright <strong>IBM</strong> Corp. 1987, 2001 451


GETPEERNAME (IUCV) 183getprotobyname() 41getprotobynumber() 41getprotoent() 42getservbyname() 43getservbyport() 43getservent() 44GetSmsg 114getsockname() 44GETSOCKNAME (IUCV) 183getsockopt() 45GETSOCKOPT (IUCV) 184givesocket() 49GIVESOCKET (IUCV) 185HHandle (Pascal) 114handling external interrupts 107HELO 360HELP 364host information file 18Host lokkup routines 109HOSTALIASES environment variable 18HOSTS ADDRINFO 18HOSTS SITEINFO 18htonl() 51htons() 51Iibmsflush() 51inet_addr() 52inet_lnaof() 52inet_makeaddr() 53inet_netof() 53inet_network() 53inet_ntoa() 54initialization procedures, <strong>TCP</strong>/UDP(Pascal) 106inter-communication vehicle sockets 169interface, C socket 5internet addressing 7ioctl() 54IOCTL (IUCV) 186<strong>IP</strong>USER variable, returned by socketcall 173IsLocalAddress 115IsLocalHost 115IUCV, subsystem communication macrosIUCV CONNECT 171IUCV PURGE 175IUCV REJECT 175, 200IUCV REPLY 175IUCV SEND 171IUC<strong>VM</strong>COM SEVER 174IUCV socket API 171IUCV socket call, buffer formatsACCEPT 178BIND 178CANCEL 179CLOSE 179CONNECT 180FCNTL 181GETCLIENTID 182GETHOSTID 182GETHOSTNAME 183IUCV socket call, buffer formats(continued)GETPEERNAME 183GETSOCKNAME 184GETSOCKOPT 185GIVESOCKET 186IOCTL 187LASTERRNO 200LISTEN 189READ 190READV 190RECV 191REC<strong>VM</strong>SG 191RRCVFROM 191SELECT 192SELECT and SELECTEXDESCR<strong>IP</strong>TOR_SET macro 191descriptor sets 191FD_CLR macro 191FD_ISSET macro 191SELECTEX 192SEND 193SENDTO 195SHUTDOWN 197SOCKET 197TAKESOCKET 198WRITE 199WRITEV 199IUCV socket callsACCEPT 177BIND 178CLOSE 179CONNECT 180FCNTL 180GETCLENTID 181GETHOSTID 182GETHOSTNAME 182GETPEERNAME 183GETSOCKNAME 183GETSOCKOPT 184GIVESOCKET 185IOCTL 186LISTEN 188MAXDESC 189READ 189READV 189RECV 190RECVFROM 190REC<strong>VM</strong>SG 190SELECT 191SELECTEX 191SEND 193SENDMSG 194SENDTO 194SETSOCKOPT 195SHUTDOWN 196SOCKET 197TAKESOCKET 198WRITE 199WRITEV 199IUCV sockets, generalconnect parameters 171general information 169issuing socket calls 174lasterrno special request 200multiple-req socket program(apitype=3) 171, 174IUCV sockets, general (continued)path severance 173response from initial message 172response from <strong>TCP</strong><strong>IP</strong> 175restrictions 169send parameters, initial message 171sever, application initiated 173sever, clean_up of stream sockets 173sever, <strong>TCP</strong><strong>IP</strong> initiated 173socket API 171socket call syntax 176waiting for response from <strong>TCP</strong><strong>IP</strong> 175IUCV Sockets, prerequisiteknowledge 169KKerberosadministration server 306applications library 307authentication serverauthenticators 304communicating 304name structures 303tickets 304authentication system 303, 325database 306encryption 305Kerberos routineskrb_get_cred() 309krb_kntoln() 309krb_mk_err() 310krb_mk_priv() 310krb_mk_req() 311krb_mk_safe() 311krb_rd_err() 312krb_rd_priv() 313krb_rd_req() 314krb_rd_safe() 315krb_recvauth() 315krb_sendauth() 316Quick <strong>Reference</strong> routines 308sample programsclient 318server 320ticket granting service 305user programs 308LLDRTBLS, SET command 4level parameter on C socket callson getibmsockopt() 37on setibmsockopt() 72librariesKerberos 306, 307remote procedure calls 206SNMP DPI 329sockets 16listen() 56, 188LISTENING (Pascal) 96little endian byte ordering convention 7Mmail forwarding exit, SMTP 378MAILFROM 361452 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Management Information Base(MIB) 325, 327maxdesc() 57MAXDESC (IUCV) 189messagesPascal 104system 1mkDPIregister() 331mkDPIresponse() 331mkDPIset() 332mkDPItrap() 333MonCommand 116Monitor procedures 108monitor query 117MonQuery 117MSG_DAT fields 312, 313, 315, 317NnamesKerberos 303, 304network, physical 5network byte order 7big endian byte ordering 7htonl() 51htons() 51little endian byte ordering 7ntohl() 58ntohs() 59NONEXISTENT (Pascal) 96NOOP 364notification record (Pascal) 98notificationsnotifications (Pascal) 105notifications, specifying those toreceive (<strong>VM</strong>CF) 153notifications (<strong>VM</strong>CF) 163NotifyIo 118ntohl() 58ntohs() 59Oonoff parameter on C socket callson sock_debug() 80on sock_debug_bulk_perf0() 80on sock_do_bulkmode() 81on sock_do_teststor() 81OPEN (Pascal) 96OpenAttemptTimeout 97optlen parameter on C socket callson getibmsockopt() 37on setibmsockopt() 72optname parameter on C socket callson getibmsockopt() 37on setibmsockopt() 72optval parameter on C socket callson getibmsockopt() 37on setibmsockopt() 72OSF/Motif 251, 296, 297Pparameter, domain (C sockets) 8parameter, protocol (C sockets) 9parameter, type (C sockets) 8parse 330PascalAPI, description 95assembler callsRTcpExtRupt 123RTcpVmcfRupt 123asynchronous communication, generalsequence 95Compiler, <strong>IBM</strong> VS Pascal &Library 95connection state typeCONNECTIONclosing 96LISTENING 96NONEXISTENT 96OPEN 96RECEIVINGonly 96SENDINGonly 97TRYINGtoOPEN 97data structures 96descriptionconnection information record 97connection states 96file specification record 105notification record 98return codes 405, 409sample program 143software requirements 95password 303, 305, 306path addresses, SMTP 370pDPIpacket() 335PING interface 107PingRequest 119PINGresponse (<strong>VM</strong>CF) 167pmap_getmaps() 219pmap_getport() 219pmap_rmtcall() 220pmap_set() 221pmap_unset() 221portport assignments 204unspecified ports 135portingassessing system return messages 1printing system return messages 1remote procedure calls 206sockets 17portmap 204Portmapper 203procedure calls, Pascaldescriptions 105handling external interruptsRTcpExtRupt 123RTcpVmcfRupt 123TcpExtRupt 128TcpVmcfRupt 138Host lookup routinesGetHostNumber 112GetHostResol 112GetHostString 113GetIdentity 113IsLocalAddress 115IsLocalHost 115Monitor proceduresMonCommand 116MonQuery 117notificationsdescription 105GetNextNote 113procedure calls, Pascal (continued)notifications (continued)Handle 114Unhandle 142Other routinesAddUserNote 110GetSmsg 114ReadXlateTable 122SayCalRe 124SayConSt 124SayIntAd 124SayIntNum 125SayNotEn 125SayPorTy 125SayProTy 125Raw <strong>IP</strong> interfaceRawIpClose 119RawIpOpen 120RawIpReceive 120RawIpSend 121<strong>TCP</strong> communication proceduresTcpAbort 127TcpClose 127TcpFReceive, TcpReceive, andTcpWaitReceive 128TcpFSend, TcpSend, andTcpWaitSend 131TcpOpen and TcpWaitOpen 134TcpOption 136TcpStatus 137<strong>TCP</strong>/UDP initialization proceduresBeginTcpIp 110StartTcpNotice 126TcpNameChange 133<strong>TCP</strong>/UDP termination procedure,EndTcpIp 106Timer routinesClearTimer 111CreateTimer 111DestroyTimer 111SetTimer 126UDP communication proceduresUdpClose 138UdpNReceive 139UdpOpen 139UdpReceive 140UdpSend 141prototypes 17Qquery_DPI_port() 336QUEU 365quick reference tablesKerberos routines 308SNMP DPI routines 329socket calls 19X Windows 256QUIT 364RRaw <strong>IP</strong> interface 108raw sockets 6RawIpClose (Pascal) 119RawIpOpen (Pascal) 120RAW<strong>IP</strong>packetsDELIVERED (<strong>VM</strong>CF) 166Index 453


RawIpReceive (Pascal) 120RawIpSend (Pascal) 121RAW<strong>IP</strong>spaceAVAILABLE (<strong>VM</strong>CF) 167RCPT TO 362read() 59readv() 60ReadXlateTable 122RECEIVINGonly (Pascal) 96recv() 61recvfrom() 62recvmsg() 63REGISTER, SNMP DPI request 328registerrpc() 222related protocols 417remote procedure calls (RPCs) 201, 245accessing system returnmessages 206auth_destroy() 207authnone_create() 208authunix_create() 208authunix_create_default() 208callrpc() 209clnt_broadcast() 209clnt_call() 211clnt_control() 211clnt_create() 212clnt_destroy() 213clnt_freeres() 213clnt_geterr() 213clnt_pcreateerror() 214clnt_perrno() 214clnt_perror() 214clnt_spcreateerror() 215clnt_sperrno() 215clnt_sperror() 216clntraw_create() 216clnttcp_create() 217clntudp_create() 217enum clnt_stat structure 205enumerations 207general information 201get_myaddress() 218getrpcport() 219interface 201library 206pmap_getmaps() 219pmap_getport() 219pmap_rmtcall() 220pmap_set() 221pmap_unset() 221porting 206Portmappercontacting 204target assistance 204printing system return messages 207registerrpc() 222remapping file names 206rpc_createerr 207RPCGEN command 204svc_destroy() 222svc_fds() 207svc_freeargs() 223svc_getargs() 223svc_getcaller() 224svc_getreq() 224svc_register() 224svc_run() 225remote procedure calls (RPCs) 201, 245(continued)svc_sendreply() 225svc_unregister() 226svcerr_auth() 226svcerr_decode() 226svcerr_noproc() 226svcerr_noprog() 227svcerr_progvers() 227svcerr_systemerr() 227svcerr_weakauth() 228svcraw_create() 228svctcp_create() 228svcudp_create() 229xdr_accepted_reply() 229xdr_array() 230xdr_authunix_parms() 230xdr_bool() 231xdr_bytes() 231xdr_callhdr() 232xdr_callmsg() 232xdr_double() 232xdr_enum() 233xdr_float() 234xdr_inline() 234xdr_int() 235xdr_long() 235xdr_opaque() 235xdr_opaque_auth() 236xdr_pmap() 236xdr_pmaplist() 237xdr_pointer() 237xdr_reference() 237xdr_rejected_reply() 238xdr_replymsg() 238xdr_short() 239xdr_string() 239xdr_u_int() 239xdr_u_long() 240xdr_u_short() 240xdr_union() 241xdr_vector() 241xdr_void() 242xdr_wrapstring() 242xdrmem_create() 243xdrrec_create() 243xdrrec_endofrecord() 244xdrrec_eof() 244xdrrec_skiprecord() 244xdrstdio_create() 244xprt_register() 245xprt_unregister() 245resolver customization 18RESOURCESavailable (<strong>VM</strong>CF) 167return codesPascal 405, 409systemAccessing 1Printing 1rpc_createerr 207RPC sample programsclient 246raw data stream 248server 246RPCGEN command 204RSET 364SS, defines socket descriptor on C socketcallon getibmsockopt() 37on ibmsflush() 51on setibmsockopt() 72SayCalRe 124SayConSt 124SayIntAd 98, 124SayIntNum 125SayNotEn 125SayPorTy 125SayProTy 125select() 64SELECT (IUCV) 191selectex() 67SELECTEX (IUCV) 191send() 68SEND (IUCV) 193SENDINGonly 97sendmsg() 69SENDMSG (IUCV) 194sendto() 70SENDTO (IUCV) 194serverKerberos 303, 320, 325NCS 306remote procedure calls 203, 246, 251sockets 90, 92SERVICES file 413SET, SNMP DPI request 327SET LDRTBLS command 4sethostent() 72setibmsockopt() 72setnetent() 75setprotoent() 75setservent() 75setsockopt() 76SETSOCKOPT (IUCV) 195SetTimer 126shutdown() 81SHUTDOWN (IUCV) 196SMSG command (<strong>VM</strong>CF) 114SMTP exit routines 373, 390SMTP interfacebatch command files, format 371batch examplesconverting to batch format 371querying delivery queues 372sending mail 371envelope, description of 369path addresses 370responses 369SMTP commandsDATA 363EHLO 361EXPN 368HELO 360HELP 364MAILFROM 361NOOP 364QUEU 365QUIT 364RCPT TO 362RSET 364TICK 369VERB 368454 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


SMTP interface (continued)VRFY 367SMTP transactions 359SMTPSEND EXEC 372SNMP agent distributed programinterface (DPI) 325, 337SNMP DPIagents 325compiling and linking 328requestsGET 327GET-NEXT 327REGISTER 328SET 327TRAP 328routinesDPIdebug() 329fDPIparse() 330mkDPIlist() 330mkDPIregister() 331mkDPIresponse() 331mkDPIset() 332mkDPItrap() 333mkDPItrape() 334pDPIpacket() 335query_DPI_port() 336Quick <strong>Reference</strong> 329SOCK_DGRAM 8SOCK_RAW 8SOCK_STREAM 8software requirements 328subagents 325SO_BULKMODE, on C socket calls. 36SO_NONBLOCKLOCAL, on C socketcalls. 36Sock_debug() 79Sock_debug_bulk_perf0() 80SOCK_DEBUG environment variable 19Sock_do_bulkmode() 80Sock_do_teststor()Sock_debug_bulk_perf0() 81socket() 82SOCKET (IUCV) 197socket callsaccept() 10, 22bind() 9, 23close() 14, 27connect() 10, 27endhostent() 30endnetent() 31endprotoent() 31endservent() 31fcntl() 13, 31getclientid() 32getdtablesize() 33gethostbyaddr() 33gethostbyname() 34gethostent() 35gethostid() 36gethostname() 36getnetbyaddr() 38getnetbyname() 39getnetent() 40getpeername() 40getprotobyname() 41getprotobynumber() 41getprotoent() 42getservbyname() 43socket calls (continued)getservbyport() 43getservent() 44getsockname() 44getsockopt() 45givesocket() 49htonl() 51htons() 51ibmsflush() 51inet_addr() 52inet_lnaof() 52inet_makeaddr() 53inet_netof() 53inet_network() 53inet_ntoa() 54ioctl() 13, 54listen() 10, 56maxdesc() 57ntohl() 58ntohs() 59read() 11, 59readv() 11, 60recv() 11, 61recvfrom() 11, 62recvmsg() 12, 63select() 12, 64selectex() 67send() 11, 68sendmsg() 12, 69sendto() 11, 70sethostent() 72setibmsockopt() 72setnetent() 75setprotoent() 75setservent() 75setsockopt() 76shutdown() 81socket() 8, 82takesocket() 85tcperror() 86write() 11, 87writev() 11, 88SOCKET.H header file 7socket record 98socketsaddress 7address familiesAF_INET 6AF_IUCV 6Addressing within an internetdomain 7Addressing within an IUCVdomain 8C Socket application programinterface 5connected 11, 16, 26definition 5domain parameter 8example program fragment series 8,14general information 5guidelines for using types of 6header files 17SOCKET.H 37interfacedatagram 5raw socket 6sockets (continued)interface (continued)stream 5transaction 6library, C socket 16main socket calls 8porting 17programming concepts 5protocol parameter 9<strong>TCP</strong> socket 14type parameter 8typical <strong>TCP</strong> socket session 14, 16typical UDP socket session 16UDP socket 16unconnected 16software requirementsPascal 95sockets 5X window system 251SOL_SOCKET, on C socket calls. 36STANDARD <strong>TCP</strong>XLBIN 18StartTcpNotice (Pascal) 126stream sockets 5stubs 205subroutines (X window system) 256svc_destroy() 222svc_fds() 207svc_freeargs() 223svc_getargs() 223svc_getcaller() 224svc_getreq() 224svc_register() 224svc_run() 225svc_sendreply() 225svc_unregister() 226svcerr_auth() 226svcerr_decode() 226svcerr_noproc() 226svcerr_noprog() 227svcerr_progvers() 227svcerr_systemerr() 227svcerr_weakauth() 228svcraw_create() 228svctcp_create() 228svcudp_create() 229syntax diagramexamplesdefault xiiifragment xiiireturn arrow xiisymbols xiivariable xiitable xii, xiiisystem return codes 409Ttablesyntax diagram xii, xiiitakesocket() 85TAKESOCKET (IUCV) 198<strong>TCP</strong> communication procedures(Pascal) 107<strong>TCP</strong>/<strong>IP</strong> initialization and terminationprocedures (<strong>VM</strong>CF)abort a <strong>TCP</strong> connection 158begin <strong>TCP</strong>/<strong>IP</strong> service 152close a <strong>TCP</strong> connection 157Index 455


<strong>TCP</strong>/<strong>IP</strong> initialization and terminationprocedures (<strong>VM</strong>CF) (continued)close a UDP port 160determine whether an address islocal 161end <strong>TCP</strong>/<strong>IP</strong> service 153instruct <strong>TCP</strong><strong>IP</strong> to obey a file ofcommands 162obtain current status of <strong>TCP</strong>connection 158obtain status information from<strong>TCP</strong><strong>IP</strong> 162open a UDP port 159open <strong>TCP</strong> connection 154receive raw <strong>IP</strong> packets of a givenprotocol 161receive <strong>TCP</strong> data with FRECEIVEtcpfunction 156receive <strong>TCP</strong> data with RECEIVEtcpfunction 157receive UDP data 159send an ICMP echo request 163send raw <strong>IP</strong> packets 160send <strong>TCP</strong> data 155send UDP data 159specifiying the notifications toreceive 153tell <strong>TCP</strong><strong>IP</strong> that your program will nolonger use a particular <strong>IP</strong>protocol 161tell <strong>TCP</strong><strong>IP</strong> that your program will usea particular <strong>IP</strong> protocol 160<strong>TCP</strong>/UDP initialization procedures(Pascal) 106<strong>TCP</strong>/UDP/<strong>IP</strong> API (Pascal) 95connection information record 97connection state 96data structures 96file specification record 105handling external interrupts 107notification record 98notifications 105socket record 98software requirements 95using procedure calls 105<strong>TCP</strong>/UDP termination procedure(Pascal) 106TcpAbort (Pascal) 127TcpClose (Pascal) 127tcperror() 86TcpExtRupt 128TcpFReceive (Pascal) 128TcpFSend (Pascal) 131<strong>TCP</strong><strong>IP</strong> A<strong>TCP</strong>PSRC file (Pascal) 95<strong>TCP</strong>LOADEXEC 2using 3TcpNameChange 133TcpOpen (Pascal) 104, 134TcpOption (Pascal) 136TcpReceive (Pascal) 128TcpSend (Pascal) 131TcpStatus (Pascal) 137TcpVmcfRupt 138TcpWaitOpen (Pascal) 104, 134TcpWaitReceive 128TcpWaitSend 131Textlib (TXTLIB) FilesCLIB 3CMSLIB 3COMMTXT 3GLOBAL 3<strong>IBM</strong>LIB 3PASCAL 3RPCLIB 3SCEELKED 3<strong>TCP</strong>ASCAL 3<strong>TCP</strong>LANG 3TICK 369ticket-granting server 305tickets 304, 305Timer routines 109transaction sockets 6transactions, SMTP 359Translation information file 18TRAP, SNMP DPI request 328TRYINGtoOPEN (Pascal) 97UUDP communication procedure 108, 139UDP socket session 16UdpClose (Pascal) 138UDPdatagramDELIVERED (<strong>VM</strong>CF) 104,165UDPdatagramSPACEavailable(<strong>VM</strong>CF) 166UdpNReceive 139UdpReceive (Pascal) 104, 140UDPresourcesAVAILABLE (<strong>VM</strong>CF) 167UdpSend (Pascal) 141Unhandle (Pascal) 142UnNotifyIo 142UnpackedBytes 98URGENTpending (<strong>VM</strong>CF) 165user exit routines, SMTP 373, 390Vvariables, environment 17VERB 368Virtual Machine Communication Facility(<strong>VM</strong>CF) InterfaceCALLCODE notificationsACTIVEprobe 168BUFFERspaceAVAILABLE 164CONNECTIONstateCHANGED 164DATAdelivered 164DUMMYprobe 168PINGresponse 167RAW<strong>IP</strong>packetsDELIVERED 166RAW<strong>IP</strong>spaceAVAILABLE 167RESOURCESavailable 167UDPdatagramDELIVERED 165UDPdatagramSPACEavailable 166UDPresourcesAVAILABLE 167URGENTpending 165CALLCODE system queriesIShostLOCAL 161MONITORcommand 162MONITORquery 162PINGreq 163functions 149general informationdata structures 147, 154Virtual Machine Communication Facility(<strong>VM</strong>CF) Interface (continued)general information (continued)use of <strong>VM</strong>CF interrupt headerfields 148use of <strong>VM</strong>CF parameter listfields 148<strong>IP</strong> CALLCODE requestsCLOSErawip 161OPENrawip 160RECEIVErawip 161SENDrawip 160<strong>TCP</strong> CALLCODE requestsABORTtcp 158CLOSEtcp 157FRECEIVEtcp 156FSENDtcp 155OPENtcp 154OPTIONtcp 158RECEIVEtcp 157SENDtcp 155STATUStcp 158<strong>TCP</strong>/<strong>IP</strong> initialization and terminationproceduresabort a <strong>TCP</strong> connection 158begin <strong>TCP</strong>/<strong>IP</strong> service 152close a <strong>TCP</strong> connection 157close a UDP port 160determine whether an address islocal 161end <strong>TCP</strong>/<strong>IP</strong> service 153instruct <strong>TCP</strong><strong>IP</strong> to obey a file ofcommands 162obtain current status of <strong>TCP</strong>connection 158obtain status information from<strong>TCP</strong><strong>IP</strong> 162open a UDP port 159open <strong>TCP</strong> connection 154receive raw <strong>IP</strong> packets of a givenprotocol 161receive <strong>TCP</strong> data withFRECEIVEtcp function 156receive <strong>TCP</strong> data with RECEIVEtcpfunction 157receive UDP data 159send an ICMP echo request 163send raw <strong>IP</strong> packets 160send <strong>TCP</strong> data 155send UDP data 159specifiying the notifications toreceive 153tell <strong>TCP</strong><strong>IP</strong> that your program willno longer use a particular <strong>IP</strong>protocol 161tell <strong>TCP</strong><strong>IP</strong> that your program willuse a particular <strong>IP</strong> protocol 160<strong>TCP</strong>/UDP/<strong>IP</strong> initialization andtermination proceduresBEGINtcp<strong>IP</strong>service 152ENDtcp<strong>IP</strong>service 153HANDLEnotice 153<strong>TCP</strong><strong>IP</strong> communication CALLCODEnotifications 151<strong>TCP</strong><strong>IP</strong> communication CALLCODErequests 150456 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Virtual Machine Communication Facility(<strong>VM</strong>CF) Interface (continued)UDP CALLCODE requestsCLOSEudp 160NRECEIVEudp 159OPENudp 159SENDudp 159when to use 147VRFY 367Wwell-known port assignments<strong>TCP</strong> 413UDP 414windowschanging attributes 257communicating with windowmanagers 267controlling the screen saver 265creating and destroying 256cut and paste buffers 270default error handling 267display functions 272enabling and disablingsynchronization 266handling events 266hosts and access control 265keyboard event functions 268keyboard settings 264manipulating bitmaps 271manipulating images 271manipulating properties 258manipulating regions 269manipulating windows 257obtaining information 258opening and closing 256querying visual types 270resource manager 271setting selections 258window manager functions 264write() 87WRITE (IUCV) 199writev() 88WRITEV (IUCV) 199XX-ADDR environment variable 18X-SITE environment variable 18X Window Quick <strong>Reference</strong> tablesassociate table functions 276Athena widget support 290authorization routines 280character string sizes, querying 262clearing and copying areas 261communicating with windowmanagers 267controlling the screen saver 265default error handling 267drawing lines 261drawing text 263extension routines 275filling areas 261fonts, loading and freeing 262handling events 266X Window Quick <strong>Reference</strong> tables(continued)handling window managerfunctions 264manipulating ofbitmaps 271color cells 259colormaps 259coursors 263display functions 272graphics contents 260hosts and access control 265images 271keyboard event functions 268keyboard settings 264regions 269miscellaneous utility routines 277MIT extensions to X 275Pixmaps, creating and freeing 259querying visual types 270synchronization, enabling anddisabling 266transferring images 263using cut and paste buffers 270using the resource manager 271windowschanging attributes 257creating and destroying 256display, opening and closing 256manipulating 257manipulating properties 258obtaining information 258properties and atoms 258selections, setting 258X intrinsics routiness 280X window systemapplication resource file 253application resources 295associate table functions 293authorization routines 293compiling and linking 254creating an application 254defining widgets 294EBCDIC-ASCII translation 252extension routines 292how the interface works 251interface 251MIT extensions 293running an application 255sample programsAthena widget set, use of 300OSF/Motif-based widget set, useof 302Xlib calls, use of 299software requirements 251subroutineschanging window attributes 257clearing and copying areas 261communicating with windowmanagers 267controlling the screen saver 251,265creating and destroyingwindows 256creating and freeing pixmaps 259drawing lines 261drawing text 263X window system (continued)subroutines (continued)enabling and disablingsynchronization 266filling areas 261handling events 266handling window managerfunctions 264loading and freeing fonts 262manipulating bitmaps 271manipulating color cells 259manipulating colormaps 259manipulating cursors 263manipulating displayfunctions 272manipulating graphicscontexts 260manipulating hosts and accesscontrol 265manipulating images 271manipulating keyboard eventfunctions 268manipulating keyboardsettings 264manipulating regions 269manipulating windowproperties 258manipulating windows 257obtaining windowinformation 258opening and closing adisplay 256properties and atoms 258querying character stringsizes 262querying visual types 270setting window selections 258transferring images 263using cut and paste buffers 270using default error handling 267using the resource manager 271target display, identifying 254utility routines 293widget supportAthena 296OSF/MOTIF based 297X Defaults 253X Window System Toolkit 293X-XLATE environment variable 18xdr_accepted_reply() 229xdr_array() 230xdr_authunix_parms() 230xdr_bool() 231xdr_bytes() 231xdr_callhdr() 232xdr_callmsg() 232xdr_double() 232xdr_enum() 233xdr_float() 234xdr_inline() 234xdr_int() 235xdr_long() 235xdr_opaque() 235xdr_opaque_auth() 236xdr_pmap() 236xdr_pmaplist() 237xdr_pointer() 237Index 457


xdr_reference() 237xdr_rejected_reply() 238xdr_replymsg() 238xdr_short() 239xdr_string() 239xdr_u_int() 239xdr_u_long() 240xdr_u_short() 240xdr_union() 241xdr_vector() 241xdr_void() 242xdr_wrapstring() 242xdrmem_create() 243xdrrec_create() 243xdrrec_endofrecord() 244xdrrec_eof() 244xdrrec_skiprecord() 244xdrstdio_create() 244xprt_register() 245xprt_unregister() 245458 z/<strong>VM</strong>: <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong>


Readers’ Comments — We’d Like to Hear from Youz/<strong>VM</strong><strong>TCP</strong>/<strong>IP</strong> Level 3A0Programmer’s <strong>Reference</strong>Version 3 Release 1.0Publication No. SC24-5983-00Overall, how satisfied are you with the information in this book?Very Satisfied Satisfied Neutral Dissatisfied VeryDissatisfiedOverall satisfaction h h h h hHow satisfied are you that the information in this book is:Very Satisfied Satisfied Neutral Dissatisfied VeryDissatisfiedAccurate h h h h hComplete h h h h hEasy to find h h h h hEasy to understand h h h h hWell organized h h h h hApplicable to your tasks h h h h hPlease tell us how we can improve this book:Thank you for your responses. May we contact you? h Yes h NoWhen you send comments to <strong>IBM</strong>, you grant <strong>IBM</strong> a nonexclusive right to use or distribute your comments in anyway it believes appropriate without incurring any obligation to you.NameAddressCompany or OrganizationPhone No.


Readers’ Comments — We’d Like to Hear from YouSC24-5983-00SC24-5983-00_________________________________________________________________________________________Fold and Tape Please do not staple Fold and TapeBUSINESS REPLY MAILFIRST-CLASS MAIL PERMIT NO. 40 ARMONK, NEW YORKPOSTAGE WILL BE PAID BY ADDRESSEENO POSTAGENECESSARYIF MAILED IN THEUNITED STATES_________________________________________________________________________________________Fold and Tape Please do not staple Fold and Tape___________________________________________________________________________________________________Cut or FoldAlong LineCut or FoldAlong Line


File Number: S370/4300/30XX-50Program Number: 5654-A17Printed in the United States of Americaon recycled paper containing 10%recovered post-consumer fiber.SC24-5983-00


Spine information: z/<strong>VM</strong> <strong>TCP</strong>/<strong>IP</strong> Programmer’s <strong>Reference</strong> Version 3 Release 1.0

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!