c socket programming

24
Feb 1998 SAS/C & C++ Compiler R&D Slide 1 C Socket Programming Tutorial SHARE Session 5959 SAS SAS Institute Inc Institute Inc Cary, NC Cary, NC Writing Client/Server Programs in C Writing Client/Server Programs in C Using Sockets (A Tutorial) Using Sockets (A Tutorial) Part II Part II Session 5959 Session 5959 Greg Granger Greg Granger grgran grgran @ @ sas sas .com .com SAS/C & C++ Support SAS/C & C++ Support SAS SAS Institute Institute Cary, NC Cary, NC

Upload: api-26343069

Post on 10-Apr-2015

1.307 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 1

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

Writing Client/Server Programs in CWriting Client/Server Programs in CUsing Sockets (A Tutorial)Using Sockets (A Tutorial)

Part IIPart II

Session 5959Session 5959

Greg GrangerGreg Grangergrgrangrgran@@sassas.com.com

SAS/C & C++ SupportSAS/C & C++ SupportSASSAS Institute Institute

Cary, NCCary, NC

Page 2: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 2

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

Remote Execution Sample ProgramRemote Execution Sample Program�� Remote Execution Connection DiagramRemote Execution Connection Diagram�� getservbynamegetservbyname() coding() coding�� rexecrexec() function declaration() function declaration�� gethostbynamegethostbyname() and() and struct hostent struct hostent�� rexecrexec() caller source code examination() caller source code examination�� System call return conventionsSystem call return conventions�� Socket address structures and conventionsSocket address structures and conventions�� recv() and send() conventionsrecv() and send() conventions�� File descriptor sets and select()File descriptor sets and select()

Page 3: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 3

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

Remote Execution Connection DiagramRemote Execution Connection Diagram

rexeccmdrexeccmd

rexecrexec

execexec cmd cmd((lsls -l) -l)

rexecdrexecd

<child><child>

<parent><parent>

Client issues:rexec server.unx mark mypass ls -l

host.host.mvsmvs server.server.unxunx

stderrstderr (pipe) (pipe)

stdin

stdoutstdoutPrimaryPrimarySocketSocket

SecondarySecondarySocketSocket

Page 4: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 4

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

REXEC Initial ConnectionREXEC Initial Connection

rexeccmdrexeccmdrexecrexec

host.host.mvsmvs server.server.unxunx

PrimaryPrimarySocketSocket

inetdinetd

rexecdrexecd

rexecd issues: issues:

socket()socket()bind()bind()

listen()listen()

select()select()accept()accept()

client issues:rexeccmd.c [53] getservbyname() [60] rexec() rexec.c [61] gethostbyname() [70] socket() [79] connect()

Page 5: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 5

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

getservbynamegetservbyname() Coding() Codinggetservbyname() returns NULL for failure or a pointer to this structure for success:

struct servent { char *s_name; /* official name */ char **s_aliases; /* array of aliases */ int s_port; /* well-known port */ char *s_proto; }; /* protocol to use (udp/tcp) */

On UNIX the data comes from the “/etc/services” file formatted like the following:

exec 512/exec 512/tcptcp # remote execution # remote executionlogin 513/login 513/tcptcp # remote login # remote login

who 513/who 513/udp whodudp whod # remote who and uptime # remote who and uptime

Page 6: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 6

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

rexecrexec() Function Declaration() Function Declarationint rexec( /* Returns primary socket */

char **host, /* Pointer to hostname by */ /* reference */

int port, /* Port for rexecd server */

char *username, /* Username on remote host */

char *passwd, /* Password on remote host */

char *cmd, /* Command to execute */

int *ptr_secondary /* Place to store secondary */

Page 7: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 7

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

gethostbynamegethostbyname() Coding() CodingGethostbyname() returns NULL for failure or a pointer to this structure for success: Struct hostent { char *h_name; /* Official name */ char **h_aliases; /* array of aliases */ int h_addrtype; /* AF_INET for TCP/IP */ int h_length; /* sizeof(struct in_addr) for TCP/IP */ char **h_addr_list; /* points to array of struct in_addr */ #define h_addr h_addr_list[0]}; /* Primary IP address */

Here is an example of printing the IP address:

struct hostent *he;char * host = ”ahost.unx.sas.com";struct in_addr *ia;

he = gethostbyname(host);ia = (struct in_addr *)(he->h_addr);printf("IP address: %s\n",inet_ntoa(*ia));

Page 8: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 8

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

““struct hostentstruct hostent” diagram” diagram

Struct hostent

char *h_name

char **h_aliases

int h_addrtype AF_INET

int h_length 4

char **h_addr_list

tools.tools.sassas.com.comchar[]char[]

array ofarray ofchar *char *

0

server1.server1.sassas.com.comchar[]char[]

bigserverbigserver..sassas.com.comchar[]char[]

array ofarray ofchar *char *

0

149.179.3.3149.179.3.3structstruct in_ in_addraddr

154.166.17.231154.166.17.231structstruct in_ in_addraddr

Page 9: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 9

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

System Call Return ConventionsSystem Call Return Conventions�� Most system calls have the same returnMost system calls have the same return

conventionsconventions�� AnAn int int value >= 0 indicates success; -1 indicates value >= 0 indicates success; -1 indicates

failure.failure.�� Failed calls set “Failed calls set “errnoerrno” to indicate the cause of” to indicate the cause of

failure;failure; perror perror() will print a message based on the() will print a message based on the““errnoerrno” value.” value.

�� Here is the typical coding logic:Here is the typical coding logic:int s = socket(AF_INET, SOCK_STREAM, 0);if (s < 0) { perror(“socket() failed”); exit(EXIT_FAILURE); }

Page 10: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 10

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

Socket Address StructuresSocket Address StructuresSocket address formats vary. Each format is called an “addressing family”. The generic format is:

struct sockaddr { u_short sa_family; /* Addressing family */ char sa_data[14]; }; /* varies */

AF_INET is the addressing AF_INET is the addressing family for TCP/IP. It’s format is: for TCP/IP. It’s format is:struct in_addr { u_long s_addr; }; /* net byte order */

struct sockaddr_in { short sin_family; /* AF_INET */ u_short sin_port; /* TCP or UDP port */ struct in_addr sin_addr; /* IP address */ char sin_zero[8]; }; /* varies */

Page 11: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 11

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

Socket Address ConventionsSocket Address Conventions�� For connect(), the port and IP address must beFor connect(), the port and IP address must be

specified.specified.�� For bind(), either may be set to zero.For bind(), either may be set to zero.�� Specifying “sin_port” as zero requests that theSpecifying “sin_port” as zero requests that the

system assign a transient port. Usesystem assign a transient port. Use getsockname getsockname()()to find out what port number was chosen.to find out what port number was chosen.

�� Specifying “sin_Specifying “sin_addraddr” as zero binds to all IP” as zero binds to all IPaddresses on the host (some hosts have more thanaddresses on the host (some hosts have more thanone).one).

Page 12: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 12

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

inetdinetd Create Server Program Create Server Program

rexeccmdrexeccmdrexecrexec PrimaryPrimary

SocketSocket

inetdinetd

rexecdrexecd

exec()

host.host.mvsmvs server.server.unxunx

Server creation program (inetd) issues a fork() and exec() call to startrexecd. The socket descriptor is attached to stdin, stdout and stderrof rexecd.

fork()

rexecrexec.c lines [79 - 82].c lines [79 - 82]

Page 13: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 13

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

Server Creation Socket CloseServer Creation Socket Close

rexeccmdrexeccmdrexecrexec PrimaryPrimary

SocketSocket

inetdinetd

rexecdrexecd

host.host.mvsmvs server.server.unxunx

Server creation program (inetd) issues aclose() to close it’s connection to the socket,then waits for a new client connection.

closeclose()()

rexecrexec.c lines [79 - 82].c lines [79 - 82]

Page 14: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 14

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

Client EstablishesClient Establishes stderr stderr port port

rexeccmdrexeccmdrexecrexec

PrimaryPrimary

SocketSocketrexecdrexecd

host.host.mvsmvs server.server.unxunx

stdin/stdout/stderr

Rexecd reads stdin until a null character is found, if any characters are read before the null they are interpreted as an optional secondary port address to be used for stderr.

rexecrexec.c lines [83 - 140].c lines [83 - 140]

Page 15: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 15

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

recvrecv() and send() conventions() and send() conventions�� recv() returns 0 for EOF; >0 for number of bytesrecv() returns 0 for EOF; >0 for number of bytes

readread�� recv() often returns fewer bytes than requested;recv() often returns fewer bytes than requested;

call recv() in a loop until you have gotten them allcall recv() in a loop until you have gotten them all�� For TCP, send() does not create record boundaries;For TCP, send() does not create record boundaries;

recv() may get the result of more or less than onerecv() may get the result of more or less than onesend()send()

�� recv()/send() behavior is a common programmingrecv()/send() behavior is a common programmingerror with TCP/IP and socket programming.error with TCP/IP and socket programming.

Page 16: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 16

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

rexecdrexecd connect() connect() stderr stderr Port Port

rexeccmdrexeccmdrexecrexec

PrimaryPrimarySocketSocket

rexecdrexecd

host.host.mvsmvs server.server.unxunx

stdin/stdout

SecondarySecondarySocketSocket

RexecdRexecd connects connects stderr stderr to port created and specified by to port created and specified by rexec rexec.. StderrStderr is used to return error information to is used to return error information to rexec rexec and to send and to sendsignal requests (kill calls) tosignal requests (kill calls) to rexecd rexecd. .

stderr

rexecrexec.c lines [83 - 140].c lines [83 - 140]

Page 17: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 17

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

Send user, password and commandSend user, password and command

rexeccmdrexeccmdrexecrexec

PrimaryPrimarySocketSocket

rexecdrexecd

host.host.mvsmvs server.server.unxunx

stdin/stdout

SecondarySecondarySocketSocket

stderr

ClientClient rexec rexec writes the writes the userid userid, password and command to , password and command to execute to the primary socket, whereexecute to the primary socket, where rexecd rexecd receives them via receives them viareads of the primary socket (which isreads of the primary socket (which is stdin stdin).).

rexecrexec.c lines [141 - 150].c lines [141 - 150]

Page 18: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 18

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

Server confirmsServer confirms

rexeccmdrexeccmdrexecrexec

PrimaryPrimarySocketSocket

rexecdrexecd

host.host.mvsmvs server.server.unxunx

stdin/stdout

SecondarySecondarySocketSocket

stderr

ServerServer rexecd rexecd writes a one byte value of binary zero to the writes a one byte value of binary zero to the primary socket (primary socket (stdoutstdout) if authorization is successful, otherwise ) if authorization is successful, otherwise it writes a one byte value of binary one. Clientit writes a one byte value of binary one. Client rexec rexec receives receives this via a read of the primary socketthis via a read of the primary socket

rexecrexec.c lines [152 - 171].c lines [152 - 171]rexecrexec exits line [176] exits line [176]

Page 19: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 19

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

Server creates command executorServer creates command executor

rexeccmdrexeccmd PrimaryPrimarySocketSocket

rexecdrexecd

host.host.mvsmvs server.server.unxunx

stdin

stdout

SecondarySecondarySocketSocket

stderr

parent

child

stderr(pipe)

rexecdrexecd creates a pipe (for creates a pipe (for stderr stderr) then forks creating a child) then forks creating a childprocess in which to run the command. Note thatprocess in which to run the command. Note that rexecd rexecd closes it’s connection to the primary socket and that the closes it’s connection to the primary socket and that the child process closes it’s connection to the secondary socket.child process closes it’s connection to the secondary socket.

rexecdrexecd

rexeccmdrexeccmd lines [61-118] lines [61-118]

Page 20: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 20

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

Child Process Executes CommandChild Process Executes Command

rexeccmdrexeccmd PrimaryPrimarySocketSocket

rexecdrexecd

host.host.mvsmvs server.server.unxunx

stdin

stdout

SecondarySecondarySocketSocket

stderr

commandcommand

parent

child

stderr(pipe)

The child process then configures it’s environment to match The child process then configures it’s environment to match thethe userid userid and runs the command using the and runs the command using the execl execl call. call. Output from the command is sent toOutput from the command is sent to rexeccmd rexeccmd through the through theprimary socket.primary socket.

rexeccmdrexeccmd lines [61-118] lines [61-118]

Page 21: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 21

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

File Descriptor SetsFile Descriptor Sets�� A file descriptor is an integer [returned by open() orA file descriptor is an integer [returned by open() or

socket()] which identifies a file or socket.socket()] which identifies a file or socket.�� Descriptors are numbered 0 through FD_SETSIZE-1Descriptors are numbered 0 through FD_SETSIZE-1�� ““fdfd_set” is a type which contains a bit for each descriptor_set” is a type which contains a bit for each descriptor�� The following macros manipulate file descriptor sets:The following macros manipulate file descriptor sets:

#include <sys/types.h>int desc; fd_set fds;FD_ZERO(&fds); /* zero entire set */FD_CLR(desc, &fds); /* clear desc bit */FD_SET(desc, &fds); /* set desc bit */FD_ISSET(desc, &fds); /* test desc bit */

Page 22: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 22

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

The select() callThe select() call�� The select() system call awaits activity onThe select() system call awaits activity on

descriptor setsdescriptor sets

�� A “timeout” parameter of NULL specifies indefiniteA “timeout” parameter of NULL specifies indefinitewaitingwaiting

�� A zero time value sets select() non-blockingA zero time value sets select() non-blocking�� A non-zero time value, sets a maximum wait timeA non-zero time value, sets a maximum wait time

int select( /* returns number active */ int nfds, /* highest desc used + 1 */ fd_set *read, /* Await read on these */ fd_set *write, /* await write on these */ fd_set *except, /* seldom used */ struct timeval *timeout /* inactivity timeout */

Page 23: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 23

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

SummarySummary�� Reviewed various socket API function callsReviewed various socket API function calls�� REXEC / REXECD dialogREXEC / REXECD dialog�� Useable TCP/IP Socket ApplicationUseable TCP/IP Socket Application�� Questions ?Questions ?

Page 24: C Socket Programming

Feb 1998SAS/C & C++ Compiler R&D Slide 24

C Socket Programming Tutorial SHARE Session 5959

SASSAS Institute Inc Institute IncCary, NCCary, NC

BibliographyBibliography�� Internetworking with TCP/IP: Volumes I, II & III, DouglasInternetworking with TCP/IP: Volumes I, II & III, Douglas

Comer, Prentice Hall, 1991 (ISBNComer, Prentice Hall, 1991 (ISBN Vol Vol I: 0134685059, I: 0134685059, Vol VolIII: 0138487146)III: 0138487146)

�� The Whole Internet User’s Guide & Catalog by EdThe Whole Internet User’s Guide & Catalog by Ed Kroll Kroll;;O’Reilly & AssociatesO’Reilly & Associates

�� UNIX Network Programming by W. Richard Stevens;UNIX Network Programming by W. Richard Stevens;Prentice Hall, 1990 (ISBN 0139498761)Prentice Hall, 1990 (ISBN 0139498761)

�� Socket API Programmer’s ReferenceSocket API Programmer’s Reference�� UNIX “man” pagesUNIX “man” pages�� TCP/IP Illustrated: Volumes 1 & 2, W. Richard Stevens (v2TCP/IP Illustrated: Volumes 1 & 2, W. Richard Stevens (v2

with Gary R. Wright); Addison-Wesley Publishing Company,with Gary R. Wright); Addison-Wesley Publishing Company,19941994