View
222
Download
2
Embed Size (px)
Citation preview
1Netcomm 2005 - Sockets
Communication NetworksCommunication Networks
Recitation 2Recitation 2
2Netcomm 2005 - Sockets
TCP/IP Socket ProgrammingTCP/IP Socket ProgrammingCont.Cont.
3Netcomm 2005 - 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
4Netcomm 2005 - Sockets
IP Address/InterfacesIP Address/Interfaces• Identifies a host interface (not a host)Identifies a host interface (not a host)
• Interface:Interface: connection between host or connection between host or router and the physical network linkrouter and the physical network link
• Hosts may have multiple interfacesHosts may have multiple interfaces
192.18.22.13 209.134.16.123
5Netcomm 2005 - 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
6Netcomm 2005 - 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
7Netcomm 2005 - 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
8Netcomm 2005 - 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
9Netcomm 2005 - 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
10Netcomm 2005 - 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
11Netcomm 2005 - 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-descriptor file-descriptor
control functioncontrol function– use the use the select() select() function call.function call.
• What does select do?What does select do?– can be permanent blocking, time-limited blocking or non-can be permanent blocking, time-limited blocking or non-
blockingblocking– 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 use”: calls involving i.e., can identify sockets that are “ready for use”: calls involving
that socket will return immediatelythat socket will return immediately
12Netcomm 2005 - 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
fcntl(sockfd, F_SETFL, O_NONBLOCK);fcntl(sockfd, F_SETFL, O_NONBLOCK);
13Netcomm 2005 - 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: list of descriptors to check if read-ready: list of descriptors to check if read-ready– writefdswritefds: list of descriptors to check if write-ready: list of descriptors to check if write-ready– exceptfdsexceptfds: list of descriptors to check if an exception is : list 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
14Netcomm 2005 - Sockets
To be used with select():To be used with select():• Recall select uses a structure, Recall 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 is set in [readfds, writefds, exceptfds], select will
check if file descriptor (i.e. socket) check if file descriptor (i.e. socket) ii is ready for [reading, is ready for [reading, writing, exception]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 is
“ready”“ready”
15Netcomm 2005 - Sockets
Read-ready TipsRead-ready Tips
• Standard input (STDIN) is file descriptor 0Standard input (STDIN) is file descriptor 0
• 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
• Set Set timeouttimeout to NULL for no timeout to NULL for no timeout– Otherwise, see structure in Beej’s guideOtherwise, see structure in Beej’s guide
16Netcomm 2005 - 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 ) );
17Netcomm 2005 - 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 );
18Netcomm 2005 - 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()
19Netcomm 2005 - 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
20Netcomm 2005 - Sockets
Client-server ExampleClient-server Example
request
reply
telnet
ftp
Port 20
Port 23
Port 2356
Port 3325
Client 1
Client 2 Server
IP=132.66.48.37
IP=132.66.48.12 IP=132.66.2.1
21Netcomm 2005 - Sockets
Quick Unix reminderQuick Unix reminder
• ps –efps –ef
• grepgrep
• jobsjobs
• killkill
• manman
• ^z + bg ^z + bg
• |, <, >|, <, >