21
1 Comnet 2010 - Recitation 2 - Sock ets Communication Networks Communication Networks Recitation 2 Recitation 2

1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

  • View
    224

  • Download
    2

Embed Size (px)

Citation preview

Page 1: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

1Comnet 2010 - Recitation 2 - Sockets

Communication NetworksCommunication Networks

Recitation 2Recitation 2

Page 2: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

2Comnet 2010 - Recitation 2 - Sockets

TCP/IP Socket ProgrammingTCP/IP Socket ProgrammingCont.Cont.

Page 3: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

3Comnet 2010 - Recitation 2 - Sockets

OutlineOutline

Send/Receive dataSend/Receive data

Terminating a connectionTerminating a connection

Dealing with blocking callsDealing with blocking calls

Client-server model summaryClient-server model summary

Page 4: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

5Comnet 2010 - Recitation 2 - Sockets

Sending / Receiving Data Sending / Receiving Data

• With a connection (SOCK_STREAM):With a connection (SOCK_STREAM):– int count = send(sock, &buf, len, flags);int count = send(sock, &buf, len, flags);

• countcount: # bytes transmitted (-1 if error): # bytes transmitted (-1 if error)• bufbuf: char[], buffer to be transmitted: char[], buffer to be transmitted• lenlen: integer, length of buffer (in bytes) to transmit: integer, length of buffer (in bytes) to transmit• flagsflags: integer, special options, usually just 0: integer, special options, usually just 0

– int count = recv(sock, &buf, len, flags);int count = recv(sock, &buf, len, flags);• countcount: # bytes received (-1 if error): # bytes received (-1 if error)• bufbuf: void[], stores received bytes: void[], stores received bytes• lenlen: max # bytes received: max # bytes received• flagsflags: integer, special options, usually just 0: integer, special options, usually just 0

Page 5: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

6Comnet 2010 - Recitation 2 - Sockets

Example of send()Example of send()

……

connectconnect((sock, sock, ((struct sockaddr struct sockaddr *)*)&dest_addr, &dest_addr, sizeofsizeof((struct sockaddrstruct sockaddr))));;

……

char char **msg msg = "= "Comnet is the courseComnet is the course!"!";;

int len, bytes_sent;int len, bytes_sent;

len len = = strlenstrlen((msgmsg));;

bytes_sent bytes_sent = = sendsend((sock, msg, len, 0sock, msg, len, 0)); ;

Page 6: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

7Comnet 2010 - Recitation 2 - Sockets

Sending / Receiving Data Sending / Receiving Data (cont’d)(cont’d) • Without a connection (SOCK_DGRAM):Without a connection (SOCK_DGRAM):

– int count = sendto(sock, &buf, len, flags, &addr, int count = sendto(sock, &buf, len, flags, &addr, addrlen);addrlen);• count, sock, buf, len, flagscount, sock, buf, len, flags: same as send: same as send• addraddr: struct sockaddr, address of the destination: struct sockaddr, address of the destination• addrlenaddrlen: sizeof(addr): sizeof(addr)

– int count = recvfrom(sock, &buf, len, flags, int count = recvfrom(sock, &buf, len, flags, &addr, &addrlen);&addr, &addrlen);• count, sock, buf, len, flags: count, sock, buf, len, flags: same as recvsame as recv• namename: struct sockaddr, address of the source: struct sockaddr, address of the source• namelennamelen: sizeof(name): value/result parameter: sizeof(name): value/result parameter

Page 7: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

8Comnet 2010 - Recitation 2 - Sockets

Sending/Receiving notesSending/Receiving notes

• send( )send( ) might send only a fraction of the might send only a fraction of the bufferbuffer– Need to push the restNeed to push the rest– See See sendall( )sendall( ) in Beej’s guide in Beej’s guide

• recv( )recv( ) might get several messages might get several messages together, or a fraction of a messagetogether, or a fraction of a message– Need to be able to identify message’s Need to be able to identify message’s

beginning and endbeginning and end

Page 8: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

9Comnet 2010 - Recitation 2 - Sockets

Closing connectionClosing connection

• When finished using a socket, the socket When finished using a socket, the socket should be closed:should be closed:

• status = close(s);status = close(s);– status: 0 if successful, -1 if errorstatus: 0 if successful, -1 if error– s: the file descriptor (socket being closed)s: the file descriptor (socket being closed)

• Closing a socketClosing a socket– closes a connection (for SOCK_STREAM)closes a connection (for SOCK_STREAM)– frees up the port used by the socketfrees up the port used by the socket

Page 9: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

10Comnet 2010 - Recitation 2 - Sockets

Skipping the bind()Skipping the bind()

• SOCK_DGRAM:SOCK_DGRAM:– if only sending, no need to bind. The OS finds if only sending, no need to bind. The OS finds

a port each time the socket sends a packeta port each time the socket sends a packet– if receiving, need to bindif receiving, need to bind

• SOCK_STREAM:SOCK_STREAM:– The OS binds a port to the client during The OS binds a port to the client during

connection setupconnection setup

Page 10: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

11Comnet 2010 - Recitation 2 - Sockets

Dealing with blocking callsDealing with blocking calls• Many of the functions we saw block until a certain Many of the functions we saw block until a certain

eventevent– acceptaccept: until a connection comes in: until a connection comes in– connectconnect: until the connection is established: until the connection is established– recvrecv, , recvfromrecvfrom: until a packet (of data) is received: until a packet (of data) is received– sendsend, , sendtosendto: until data is pushed into socket’s buffer: until data is pushed into socket’s buffer

• For simple programs, blocking is convenientFor simple programs, blocking is convenient• What about more complex programs?What about more complex programs?

– multiple connectionsmultiple connections– simultaneous sends and receivessimultaneous sends and receives– simultaneously doing non-networking processingsimultaneously doing non-networking processing

Page 11: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

12Comnet 2010 - Recitation 2 - Sockets

Dealing with blocking (cont’d)Dealing with blocking (cont’d)• Options:Options:

– create multi-process or multi-threaded codecreate multi-process or multi-threaded code– turn off the blocking feature using the turn off the blocking feature using the fcntl()fcntl() file- file-

descriptor control functiondescriptor control function– use the use the select() select() function call.function call.

Page 12: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

13Comnet 2010 - Recitation 2 - Sockets

fcntl() function callfcntl() function call• int fcntl(int filedes, int cmd, args ...);int fcntl(int filedes, int cmd, args ...);

– statusstatus: -1 if error: -1 if error– filedes:filedes: argument is an open file descriptor argument is an open file descriptor– cmd:cmd: specifies the operation to be performed specifies the operation to be performed– arg:arg: depends upon the value of cmd depends upon the value of cmd

sockfd = socket(PF_INET, SOCK_STREAM, 0); sockfd = socket(PF_INET, SOCK_STREAM, 0);

fcntl(sockfd, F_SETFL, O_NONBLOCK);fcntl(sockfd, F_SETFL, O_NONBLOCK);

Page 13: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

14Comnet 2010 - Recitation 2 - Sockets

Using select()Using select()

• What does select do?What does select do?– can be permanent blocking, time-limited can be permanent blocking, time-limited

blocking or non-blockingblocking or non-blocking– input: a set of file-descriptorsinput: a set of file-descriptors– output: info on the file-descriptors’ statusoutput: info on the file-descriptors’ status– i.e., can identify sockets that are “ready for i.e., can identify sockets that are “ready for

use”: calls involving that socket will return use”: calls involving that socket will return immediatelyimmediately

Page 14: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

15Comnet 2010 - Recitation 2 - Sockets

select() function callselect() function call• int status = select(nfds, &readfds, &writefds, int status = select(nfds, &readfds, &writefds,

&exceptfds, &timeout);&exceptfds, &timeout);– statusstatus: # of ready objects, -1 if error: # of ready objects, -1 if error– nfdsnfds: 1 + largest file descriptor to check: 1 + largest file descriptor to check– readfdsreadfds: set of descriptors to check if read-ready: set of descriptors to check if read-ready– writefdswritefds: set of descriptors to check if write-ready: set of descriptors to check if write-ready– exceptfdsexceptfds: set of descriptors to check if an exception is : set of descriptors to check if an exception is

registeredregistered

– timeouttimeout: time after which select returns, even if nothing : time after which select returns, even if nothing ready - can be 0 or ready - can be 0 or

Page 15: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

16Comnet 2010 - Recitation 2 - Sockets

To be used with select():To be used with select():• For sets, select uses a structure, For sets, select uses a structure, struct fd_setstruct fd_set

– it is just a bit-vectorit is just a bit-vector– if bit if bit ii is set in [readfds, writefds, exceptfds], select will check if file is set in [readfds, writefds, exceptfds], select will check if file

descriptor (i.e. socket) descriptor (i.e. socket) ii is ready for [reading, writing, exception] is ready for [reading, writing, exception]

• Before calling select:Before calling select:– FD_ZERO(&fdvar)FD_ZERO(&fdvar): clears the structure: clears the structure– FD_SET(i, &fdvar)FD_SET(i, &fdvar): to check file desc. : to check file desc. ii

• After calling select:After calling select:– int FD_ISSET(i, &fdvar)int FD_ISSET(i, &fdvar): boolean returns TRUE iff : boolean returns TRUE iff ii is “ready to is “ready to

read”read”

• Standard input (STDIN) is file descriptor 0Standard input (STDIN) is file descriptor 0

Page 16: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

17Comnet 2010 - Recitation 2 - Sockets

Timeout parameterTimeout parameter

struct timeval {struct timeval {

int tv_sec; int tv_sec; // // seconds seconds

int tv_usec; int tv_usec; // // microsecondsmicroseconds

};};

• Set Set timeouttimeout to NULL for no timeout to NULL for no timeout

• Set both to 0 for immediate timeoutSet both to 0 for immediate timeout

Page 17: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

18Comnet 2010 - Recitation 2 - Sockets

Ready to readReady to read

• Listening port is read-ready if Listening port is read-ready if acceptaccept won’t won’t blockblock

• Closed connections are read-ready but Closed connections are read-ready but recv( )recv( ) returns 0 bytes returns 0 bytes

Page 18: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

19Comnet 2010 - Recitation 2 - Sockets

Other useful functionsOther useful functions• bzero(char* c, int n):bzero(char* c, int n): 0’s n bytes starting at c 0’s n bytes starting at c• gethostname(char *name, int len):gethostname(char *name, int len): gets the name of gets the name of

the current hostthe current host• gethostbyname(const char *name):gethostbyname(const char *name): converts host’s converts host’s

name to structure containing long integername to structure containing long integer

char hostname[128];char hostname[128];struct hostent *he;

gethostname( hostname, sizeof( hostname) );gethostname( hostname, sizeof( hostname) );printf( “My hostname:%s\n”, hostname );printf( “My hostname:%s\n”, hostname );he = gethostbyname( “www.yahoo.com” );printf( “Address: %s\n”, inet_n_ntoa( he->h_addr ) );

Page 19: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

20Comnet 2010 - Recitation 2 - Sockets

Useful functions (cont.)Useful functions (cont.)• gethostbyaddr(char *addr, int len, int type):gethostbyaddr(char *addr, int len, int type): converts converts

IP hostname to structure containing long integerIP hostname to structure containing long integer• inet_aton(const char *cp, struct in_addr *inp):inet_aton(const char *cp, struct in_addr *inp):

converts dotted-decimal char-string to binary converts dotted-decimal char-string to binary (network order)(network order)

• inet_ntoa(const struct in_addr in):inet_ntoa(const struct in_addr in): converts binary to converts binary to dotted-decimal stringdotted-decimal string

struct hostent *he;struct in_addr addr;

inet_aton( “66.94.230.32”, &addr );printf( “Address: %s\n”, inet_ntoa( addr.sin_addr ) );he = gethostbyaddr( &addr, sizeof( addr ), AF_INET );printf( “Name: %s\n”, he->h_name );

Page 20: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

21Comnet 2010 - Recitation 2 - Sockets

UDP Client-ServerUDP Client-Server

socket()

close()

recvfrom()

sendto()

sendto()

recvfrom()

bind()

socket()

blocks

process request

data (request)

data (reply)

UDP Client

UDP Server

bind()

close()

Page 21: 1 Comnet 2010 - Recitation 2 - Sockets Communication Networks Recitation 2

22Comnet 2010 - Recitation 2 - Sockets

TCP Client-Server TCP Client-Server

socket()

connect()

write()

read()

close()

socket()

bind()

listen()

accept()

read()

write()

close()

read()

TCP Client

TCP Server

blocks untilconnection from client

process request

end-of-file notification

data (reply)

data (request)

connection establishment3-way handshake