Transcript Socket

A TCP/IP Application
Programming Perspective
Chris Greenhalgh
G53ACC
1
Contents
• Overview
• IP layer, IP addresses and API
• Transport layer
– TCP service, API and examples
– UDP service, API and examples
Books: Comer ch.17, 18, 24 & 25 (part), 2830 (part); Farley ch. 2
2
Overview
• The TCP/IP Internet
Protocols
– Internet =
Inter-Network
Concept
(transparency:-)
• Universal service: the
illusion of a single
network
Internal details
3
Comer Fig. 17.3
TCP/IP reference model
TCP, UDP
IP
IEEE802
Ethernet,
WiFi, …
4
Comer Fig. 17.4
IP: Internet layer
• Deals with end-to-end communication
between hosts on the Internet
• Identifies hosts using IP addresses
– One per host network interface
– Globally unique
• But only on the Internet proper
• See also NAT & private IP addresses
(later notes)
5
IP v.4 addresses: 32 bits
• Normally written in dotted decimal
notation:
6
Comer Fig. 18.3
One IP address per network
interface (e.g.)
Host (computer)
7
Comer Fig. 18.9
Special IP v.4 addresses
Network =
class bit(s)
and prefix
8
Comer Fig. 18.1, 18.8
Address ranges, masks and CIDR
addresses (e.g.) CIDR notation
NB first 28 bits are 1s
NB bit-wise AND with
Mask value = prefix
9
Comer Fig. 18.7
Java API: java.net.InetAddress
• Instance = single IP address and/or DNS hostname
– (see later notes for more detail of DNS)
• API Excerpts:
public class InetAddress {
// host may be dotted IP or DNS name
public static InetAddress
getByName(String host)
throws UnknownHostException;
public static InetAddress getLocalHost()
throws UnknownHostException;
public String getHostAddress();
public String getHostName();
public boolean isMulticastAddress();
}
10
Transport Layer
• Allows multiple end-points per host
• Supports different qualities of service
(QOS)
– Connection oriented (stream) service
• Transport Control Protocol (TCP)
– Connectionless (datagram) service
• User Datagram Protocol (UDP)
11
Transport Control Protocol (TCP)
• Specified in RFC793
• Service:
– Connection between two processes
– Reliable delivery
– Bi-directional
– With flow and congestion control
– e.g. used for remote login, email, HTTP
• Acts as a “pipe” between two endpoints.
12
Connection-Oriented Services
• C.f. the telephone network
– Pick up the phone = initiate a connection
– Dial number = specify address of other party
– Recipient answers phone = connection is
made
– Speak = data is transferred in both directions
– One or both parties hang up = break
connection
13
Ports
• Each transport protocol has a set of ‘ports’ on
the network
– TCP & UDP have 16 bit port numbers (0-65535)
• Transport level protocols identify source &
destination port numbers
– Network level protocol (IP) identifies source and
destination host
• Application can be bound to one particular IP
and one particular port, or to any local IP and
one particular port
14
Ports example
Process
A
1 2
3
4
Host=128.243.22.10
Process
B
Process
C
...
Network
Packet
Host 128.243.22.10
Port# 4
15
Special port numbers
• Fixed port numbers allocated by Internet
Assigned Numbers Authority (IANA)
– E.g. HTTP, tcp port 80
• “Low” port-numbers typically reserved for
standard services
– E.g. <1024
• Or application may obtain “next unused”
local port number from OS
16
Sockets
• A socket
– is an endpoint of communication
• Created and used within an application
– is bound to a particular port
– has a type which specifies the type of
communications it supports
• E.g. TCP (stream), UDP (datagram)
– communicates with sockets of the same type
• May be linked to one specific socket, e.g. TCP, or may be
able to communicate with multiple other sockets, e.g. TCP
server socket or UDP socket.
17
Java API: java.net.ServerSocket
• Used by server
• API Excerpts:
public class ServerSocket {
// port 0 => next unused local port
public ServerSocket(int port)
throws java.io.IOException;
public InetAddress getInetAddress();
public int getLocalPort();
public Socket accept()
throws java.io.IOException;
public void close()
throws java.io.IOException;
}
18
Java server skeleton
import java.net.Socket;
import java.net.ServerSocket;
import java.io.IOException;
public class ReverseServerTCP {
public static void main(String [] args) {
try {
int port = Integer.parseInt(args[0]);
ServerSocket s = new ServerSocket(port);
while (true) {
Socket c = s.accept();
// handle client...
}
} catch (IOException e) { /* ... */ }
}
19
Java API: java.net.Socket
• Used by client and server (once connected)
• API Excerpts:
public class Socket {
// constructors only used by client
public Socket(String host, int port)
throws UnknownHostException, IOException;
public Socket(InetAddress host, int port)
throws IOException;
public InetAddress getInetAddress();
public int getPort();
public java.io.InputStream getInputStream()
throws IOException;
public java.io.OutputStream getOutputStream()
throws IOException;
public void close()
throws IOException;
20
}
Sample client (and full server)
• See ACCExamples
– tcp/ReverseClientTCP.java
– tcp/ReverseServerTCP.java
• Note: relies on java.io framework - TCP just
moves a sequence of bytes
– Use raw streams and/or BufferedInput/OutputStreams
if you want to exchange particular byte sequences
– Use Reader/Writer if you want to exchange text
– Use DataInput/DataOutput if you want to marshall
java primitive types
– Use ObjectInputStream/ObjectOutputStream if you
want to marshall Java Serializable objects
21
TCP Client and server structure
• Server
• Client
– new ServerSocket(port)
– serverSkt.accept()
connect – new Socket(host, port)
• returns new Socket
– skt.getOutputStream
– skt.getInputStream
• read, etc.
– skt.getOutputStream
• write, etc.
– skt.close()
request
response
• write, etc.
– skt.getInputStream
• read, etc.
– skt.close()
22
Multi-threaded server execution
ServerSocket
accept()
Main thread
new Thread().start()
[UNIX: fork()]
client Socket(s)
Client-specific thread(s)
23
User Datagram Protocol (UDP)
• Specified in RFC 768
• Connectionless
• Datagrams can be transmitted to
– A single machine
– A group of machines (multicast or broadcast)
• Bidirectional
• Unreliable
• Maximum payload 64Kbytes (65535 bytes)
24
Connectionless Services analogy
• Can be compared to the postal service
– A letter is put into an envelope (data into a
datagram)
– The envelope is addressed to the recipient
– The envelope is put in the post box and
enters the delivery system
– The envelope arrives (hopefully) at the
destination
25
Connectionless Services
• Unreliable
– May never arrive
– No indication if the delivery is successful
• Unordered
– May arrive in a different order
(a variety of possible routes)
• Rarely (but occasionally) duplicated
• Error-checked (corrupt packets usually
detected and discarded)
26
UDP and TCP
• Uses sockets API for both UDP and TCP
– stream type for TCP
– datagram type for UDP
• Uses port numbers for both
– but UDP port 53 is NOT same as TCP port 53
27
UDP uses
• Very simple request/response protocols
– small maximum size, e.g. DNS
• No 3-way handshake delay (cf. TCP)
• No reliability overhead/retransmit delay
– E.g. for streamed audio, video
• But:
– no flow control, congestion control
(can be added, but quite tricky and
more overhead again)
28
Java API: java.net.DatagramSocket
• Used by client and server
• API Excerpts:
public class DatagramSocket {
public DatagramSocket()
throws SocketException;
public DatagramSocket(int port)
throws SocketException;
public int getLocalPort();
public void setSoTimeout(int timeout)
throws SocketException;
public void send(DatagramPacket p)
throws IOException;
public void receive(DatagramPacket p)
throws IOException;
public void close();
}
29
Java API: java.net.DatagramPacket
• Instance combines:
– Application data - byte array
– Actual size used (number of bytes)
– Source/destination InetAddress
– Source/destination port
• Source if received, destination if sending
• API Excerpts: see over
30
• public class DatagramPacket {
public DatagramPacket(byte[] buf, int offset,
int length);
public DatagramPacket(byte[] buf,
int length);
public DatagramPacket(byte[] buf, int offset,
int length, InetAddress address, int port);
public DatagramPacket(byte[] buf, int length,
InetAddress address, int port);
public InetAddress getAddress();
public int getPort();
public byte[] getData();
public int getLength();
public void setAddress(InetAddress iaddr);
public void setPort(int iport);
public void setData(byte[] buf);
public void setData(byte[] buf, int offset,
int length);
public void setLength(int length);
}
31
Sample UDP client and server
• See ACCExamples
– unicast/ReverseClientUnicast.java
– unicast/ReverseServerUnicast.java
• Note: can still use java.io framework - UDP just
moves an array of bytes (<=65535)
– Can get/set bytes directly
– Can use ByteArrayInput/OutputStream to read/write
bytes as streams
• Can combine with DataInput/Output or
ObjectInput/OutputStream as used with TCP
32
UDP Client and server structure
• Server
• Client
– new DatagramSocket()
– loop:
•
•
•
•
new DatagramPacket()
skt.receive(pkt)
request
new DatagramPacket()
skt.send(pkt)
response
– GC DatagramSocket
– new DatagramSocket()
– work:
•
•
•
•
new DatagramPacket()
skt.send(pkt)
new DatagramPacket()
skt.receive(pkt)
– GC DatagramSocket
33