Download presentation
Presentation is loading. Please wait.
1
TCP and Sockets Lecture 3
cs193i – Internet Technologies Summer 2004 Stanford University
2
Sending a Message Ron Leslie Leland.Stanford.edu Arachne . Berkeley
Network Layer Link Layer Ron Leslie Leland.Stanford.edu Arachne . Berkeley .edu Application Layer Transport Layer O.S. Header Data H D
3
Protocol Stack Application End-to-End Network Link Level
Ethernet, token ring Network IP End-to-End TCP, UDP Application HTTP, SMTP, FTP, TELNET, DNS
4
Protocol Stack Application End-to-End Network Link Level
Ethernet, token ring Network IP End-to-End TCP, UDP Application HTTP, SMTP, FTP, TELNET, DNS
5
Protocol Stack Application End-to-End Network Link Level
Ethernet, token ring Network IP End-to-End TCP, UDP Application HTTP, SMTP, FTP, TELNET, DNS
6
Protocol Stack Application End-to-End Network Link Level
Ethernet, token ring Network IP End-to-End TCP, UDP Application HTTP, SMTP, FTP, TELNET, DNS
7
TCP Connection-Oriented Reliable Byte-Stream Flow Control
Port on “client” connects to port on “server” Reliable 3-way handshake Byte-Stream To application, looks like stream of bytes flowing between two hosts Flow Control Prevents overrunning receiver / network capacity First, it is connection-oriented, unlike IP. IP, where each packet is conceptually separate... TCP packets are part of one connection In Addition, the connection is two-way. Software can write bytes to the connection, and it shows up other side. Second, it’s End-to-End Reliable The destination will reassemble and error check packets Lost, Corrupted packets will be resent by the sender Third, TCP provides illusion of continuous, byte stream from sender to recipient. Bytes written 1234 by the sender... will show up 1234 at the receiver Finally, TCP has Flow Control which means that Sender wills slow down to a packet rate that the receiver and network can cope with. The way it does this is with ACK packets. Helps to share network capacity between users...
8
Establishing the Connection
Client Sequence # (x) Server ACK (x+1) Own sequence # (y) ACK (y+1) Sequence # (x+1)
9
Maintaining the “Connection”
IP Hdr IP Data TCP TCP Data Src port Dst port Sequence # Ack HLEN 4 RSVD 6 URG ACK PSH RST SYN FIN Flags Window Size Checksum Urg Pointer (TCP Options) 15 31 /dst port numbers and IP addresses uniquely identify socket
10
Terminating the Connection
Connection Close/Teardown 2 x 2-way handshake (Active) Client (Passive) Server Fin (Data +) Ack
11
Another Transport Layer Protocol: UDP
Basically allows access to IP functionality without TCP overhead...
12
User Datagram Protocol (UDP)
Characteristics Connectionless, Datagram, Unreliable Adds only application multiplexing/demultiplexing and checksumming to IP Good for Streaming Media, Real-time Multiplayer Networked Games, VoIP No connection establishment.... packets can show up at any time.... the App has to handle whether you are prepared for the incoming data or not... Datagram.... means UDP packets are self contained no sequencing like in TCP Unreliable like IP, no ACKs... no flow control, no automatic retransmission... Adds checksumming the headers.... to prevent errors... Adds application multiplexing, to send the UDP packet to the correct service. Both TCP and UDP perform this demultiplexing, and they use port numbers to do it....
13
Summary IP is the basis of Internetworking
TCP builds on top of IP adds reliable, congestion-controlled, connection-oriented byte-stream. UDP builds on top of IP allows access to IP functionality
14
Brief Return to Addressing
Broadcast Send message to everyone on LAN Address Resolution Protocol (ARP) Broadcast “Who has IP address ?” Owner of IP address answers with LAN address
15
Addressing in Action IP Address Subnet Mask Gateway DNS server
Last 8 bits used for host Gateway Local router to forward traffic to DNS server Translates names to IP addresses
16
Domain Name Service (DNS)
Distributed database maps host names --> numerical IP Address Hierarchical Namespace Top-level domain (root domain) .com, .net, .org Second-level domain hotmail.com, stanford.edu Sub domains movies.yahoo.com
17
DNS and Routing Both are Hierarchical
IP Routing Hierarchy is left to right ( ) DNS Hierarchy is right to left ( Root name server & delegate name server Backbone router & delegate router
18
Network Address Translation (NAT)
Hosts share single IP address Hosts IP addresses in *.* Router between LAN and Internet IP address ( ) Translates to host address before forwarding
19
Five Minute Break
20
Sockets Basic Concepts & Important Issues
Client Socket Code & Server Socket Code Client-Server Interaction
21
What is a Socket? Interface to the TCP Byte-Stream (2-way)
Both sides think they are writing to Files! Example Code write(SOCK, “Hello\n”); print SOCK “Hello\n”;
22
TCP Byte Stream (Virtual Circuit)
23
Protocol Stack SOCKETS
24
What is a Port? Transport address to which processes can listen for connection requests Local to host: ports Well-known ports Below 1024 Standard services Only supervisor privileged enough to access Examples FTP: 21 HTTP: 80 TELNET: 23
25
Server and Client host:port host:port host:port Server listens
on a port # host:port Clients make “calls” to that port #
26
Server and client can be the same machine!
SSH SSHD Client Process Server Process
27
Client Side
28
Establishing a Connection
Establish Socket Connection Send & Receive Data Close Socket Connection Remember how TCP is connection-oriented, and has three phases of a connection?
29
Once the connection is established...
Protocol (RFC) dictates turn taking between Server and Client Write by saying in Perl: print SOCK “Hello\n”; Read by saying in Perl: $incoming_data = <SOCK>;
30
Example Sockets in Perl
$ipaddr = inet_aton(” $sockaddr = sockaddr_in(80, $ipaddr); socket($sock, .... ); connect($sock, $a); print $sock “Hi There!”
31
Socket Example in C struct sockaddr_in peer;
peer.sin_addr.s_addr = inet_addr(” ”); peer.sin_port = htons(7500); peer.sin_family = AF_INET; s = socket(AF_INET, SOCK_STREAM,0); connect(s, (struct sockaddr *)&peer, sizeof(peer)); send(s, “Hi There!”, 9, 0);
32
Demo Code in Java myClient = new Socket(”www.yahoo.com”, 80);
outputStream = new PrintStream(myClient.getOutputStream()); outputStream.println(”Hello There!”);
33
Blocking vs. Non-Blocking
Blocking Function Call Waits if necessary <SOCK> blocks if no data to read OS will wake up the process to read Also write blocks (send faster than recipient can handle) Non-Blocking Function Call Returns immediately May need a while loop to check for data
34
Buffering Why is it good normally?
Batch the work for efficiency (Harddrives...) Prevent Failures (CD Players, etc...) Concept of flushing the buffer (write to disk/network) Why is it a problem for networking?
35
Autoflush Automatically flush after every write
use FileHandle; # FileHandle module... .... autoflush SOCK, 1; # set autoflush
36
Other Issues Irregular Timing (CPU fast, mostly blocked)
Irregular Sizing Line Endings \r\n -- most common on Internet, oldest \n -- Unix way (single char, nice) \n may get remapped! Messes up portability. In your code... really is \015\012
37
Setting Up a Socket Program
1. Hostname to IPAddr conversion $ip = inet_aton($hostname); 2. Create Socket Address $sockaddr = sockaddr_in($port, $ip); 3. Allocate Socket socket(SOCK, PF_INET, SOCK_STREAM, 0); 4. Connect connect(SOCK, $sockaddr);
38
Reading from a Socket connect(SOCK, $sockaddr); $line = <SOCK>;
$line =~ s/\015\012//g; Turn-taking via EOF while ($line = <SOCK>) { ..... } OR sysread(SOCK, str, length); ## efficient
39
sysread vs <> Read bytes sysread(SOCK, ...)
Read line by line <SOCK> Do things in larger chunks! Just like in Buffering...
40
Writing to a Socket print SOCK “Hello!\012”;
OR syswrite(SOCK, str, length);
41
Close the Socket close(SOCK); ## sends EOF to other end
Other side sees all data, then EOF... then quits Consider it an end “marker” that is sent across
42
Server Side
43
Server Listens on Port Create the Socket as before Bind socket
bind(...) associates port & socket Listen at a port Does not block. Accept an incoming connection (so server must sit on the Internet all day) This call blocks! Returns when client connects...
44
Server Listens on Port Look at Client Address (caller id) Read & Write
Close Loop and listen again...
45
Perl Server Setup Example
sub CreateServerSocket { my($sock, $port) socket($sock, PF_INET, SOCK_STREAM, 0); setsockopt($sock, SOL_SOCKET, SO_REUSEADDR, pack("l",1)); bind($sock, sockaddr_in($port, INADDR_ANY)); autoflush $sock, 1; return(""); }
46
Listen and Accept listen (SERVER, ...); accept (CLIENT, SERVER);
autoflush CLIENT, 1;
47
Server Pseudo-code $serverport = 3456;
CreateServerSocket(SERVER, $serverport); listen(SERVER,...); while($clientaddr = accept(CLIENT, SERVER)) { $incomingline = <CLIENT>; print CLIENT “$outgoingline\n”; close(CLIENT); }
48
Telnet Trick Many Services just use ASCII text dialog between server and client > telnet host port Bottom Line: Text based protocols are easier to debug because their state is visible and accessible
49
Design of a Chat Room Server/Client
Server listens Clients call
50
Chat Server Design Server State Server Abilities Who is connected
Max clients connected Server Abilities Accept a New Connection Close a Connection Send Message from A --> B Send Message from A --> All
51
Chat Server Design Main Thread Handler Threads Handles connections
Calls handler threads Handler Threads <CLIENT> print CLIENT “Hi!\n”; close CLIENT;
52
Chat Client Design Client State Client Abilities
Server’s IP address : port Who is connected to server Client Abilities Connect to server Send message to A (thru server handler) Send message to all (thru server handler) Leave server (e.g. print SOCK “BYE”, close SOCK)
53
Peer-to-Peer No fixed Server & Client
Anybody can be Server or Client at any time Example P2P software File Sharing (Bittorrent, FastTrack, Gnutella)
54
Socket Summary Client Socket Server Socket
Setup/Create, Connect, Read/Write, Close Server Socket Setup/Create, Bind, Listen, Accept, Read/Write, Close It’s just a Programmer’s Application Programming Interface (API) to TCP or UDP on top of IP
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.