Network Programming

Download Report

Transcript Network Programming

Networking Basics
Moshe Fresko
Bar-Ilan University
Networking Basics

Uses of Networks
 Resource
Sharing
 High Reliability
 Saving Money
 Communication Medium
 Access to remote information
Network Layers
Application Layer (http,ftp,telnet,smtp,dns,…)
Transport Layer (TCP,UDP,…)
Network Layer (IP,…)
Physical + Data Link Layer (Arpanet,SatNet,Lan, …)
TCP vs UDP

TCP : Transmission Control Protocol : Is a connection- based protocol that
provides a reliable flow of data between two computers.





Used when two applications want to communicate reliably
It is Connection Based
Data is get in the same order it was sent (via Streams)
Transmission guarantied, or error is reported.
Example:


HTTP, FTP, SMTP, TELNET,
UDP : User Datagram Protocol : Is a protocol that sends independent
packets of data, called datagrams, from one computer to another with no
guarantees about arrival.





Not connection based
Communication is not guaranteed
Datagram : A packet sent by UDP protocol.
The order of datagrams are not guaranteed.
Example:

Radio, Clock Server, Ping,
IP Address


IP (Internet Protocol) : Network layer protocol.
IP Address : A unique 32 bit number.

Dotted Decimal Notation : 192.41.6.20
 Range : 0.0.0.0 – 255.255.255.255


Every host and router in the Internet has an IP address, which
encodes its network number and host number.
Classes of IP Addresses






Class A : 0{7 bits Network}.{24 bits Host}
Class B : 10{14 bits Network}.{16 bits Host}
Class C : 110{21 bits Network}.{8 bits Host}
Class D : 1110{Multicast address}
Class E : 11110{Reserved for future use}
Special IP-addresses



0.0.0.0 : This host
255.255.255.255 : Broadcast on local network
127.?.?.? : Loopback
Ports



Generally a computer has a single physical connection
to the network.
The data can be intended to different applications
Port: A unique place within the machine. (Abstraction)


16 bit number
Well-known ports: 0..1023 are reserved ports



FTP is 21, TELNET 23, SMTP 25, HTTP 80, POP
Custom Use > 1024
The TCP and UDP protocols use ports to map incoming
data to a particular process running on a computer
URLs


URL : Uniform Resource Locater : It is a reference (an
address) to a resource on the Internet.
A URL has two main components



Example : http://java.sun.com/



Protocol Identifier
Resource Name
http : is the Protocol Identifier
//java.sun.com/ : is the Resource Name
The Resource Name may contain




HostName : The name of the machine
FileName : The pathname of the file on the machine
Port Number : The port number to which to connect (Typically
Optional)
Reference : A reference to a named anchor within a resource
(Typically Optional)
URLs

Two classes for URL processing in Java



java.net.URL : Represents a URL resource
java.net.URLConnection : An opened connection to a URL
resource
Creating an absolute URL object



Creating a URL relative to another




By Constructor : URL(String)
URL myurl = new URL(“http://cs.biu.ac.il/”) ;
Used for relative hyperlinks in an HTML page
<A HREF=“MyPres.html”>Presentations</A>
By Constructor : URL(URL,String)
URL myurl = new URL(“http://cs.biu.ac.il/~freskom1/”) ;
URL mypres = new URL(myurl, “MyPres.html”) ;
Other URL Constructors

All constructors throw MalformedURLException




URL(String protocol, String host, int port, String file)
URL(String protocol, String host, String file)
URL(String spec)
URL(URL context, String spec)
URLs

Parsing a URL
String getProtocol()
String getHost()
int getPort()
String getFile()
String getRef()

Example
import java.net.* ;
public class ParseURL {
public static void main(String[]args) throws MalformedURLException {
URL url = new URL("http://java.sun.com:80/docs/”+
”books/tutorial/intro.html#DOWNLOADING") ;
System.out.println("Protocol = "+url.getProtocol()) ;
System.out.println("Host = "+url.getHost()) ;
System.out.println("FileName = "+url.getFile()) ;
System.out.println("Port = "+url.getPort()) ;
System.out.println("Reference= "+url.getRef()) ;
}
}

Output
Protocol = http
Host = java.sun.com
FileName = /docs/books/tutorial/intro.html
Port = 80
Reference= DOWNLOADING
URLs

Reading directly from a URL using openStream() method that
returns an InputStream

Example:
import java.net.* ;
import java.io.* ;
public class URLReader {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.cs.biu.ac.il/~freskom1/") ;
BufferedReader br = new BufferedReader (
new InputStreamReader(url.openStream())) ;
String line ;
while ((line=br.readLine())!=null)
System.out.println(line) ;
br.close() ;
}
}
URL Connection

Connecting to a URL

URL’s openConnection() method
URLConnection openConnection() throws IOException ;

Example:
try {
URL url = new URL("http://www.cs.biu.ac.il/~freskom1/") ;
URLConnection uc = url.openConnection() ;
}
catch (MalformedURLException e) { … }
catch (IOException e) { … }

Reading from a URL connection
import java.net.* ;
import java.io.* ;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.cs.biu.ac.il/~freskom1/") ;
URLConnection uc = url.openConnection() ;
BufferedReader br=new BufferedReader(new InputStreamReader(uc.getInputStream()));
String line ;
while ((line=br.readLine())!=null)
System.out.println(line) ;
br.close() ;
}
}
Writing to a URLConnection

Like HTML forms.




In the Browser, Text fields and other GUI components that let user enter data.
Browser writes the data to the URL.
On the server a CGI-BIN script processes it and returns a response.
Example:
import java.io.* ;
import java.net.* ;
public class Reverse {
public static void main(String[]args) throws Exception {
if (args.length<1) {
System.err.println("Usage: java Reverse <String>") ; System.exit(1) ;
}
String stringToReverse = URLEncoder.encode(args[0],"UTF-8") ;
URL url = new URL("http://java.sun.com/cgi-bin/backwards") ;
URLConnection uc = url.openConnection() ;
uc.setDoOutput(true) ;
PrintWriter out = new PrintWriter(uc.getOutputStream()) ;
out.println("string="+stringToReverse) ;
out.close() ;
BufferedReader in = new BufferedReader(new
InputStreamReader(uc.getInputStream())) ;
String line ;
while ((line=in.readLine())!=null)
System.out.println(line) ;
}}
Sockets




Socket: End point of a two-way communication link
between two programs running on the network.
Socket is a software abstraction to represent the
“terminals” of a connection.
A socket is bound to a port number so that the TCP layer
can identify the application that data is destined to be
sent.
Two stream-based Socket classes

ServerSocket : For server


On connection returns a new Socket
Socket : For client

Have getInputStream() and getOutputStream() functions
Socket Example – Echo
import java.io.* ;
import java.net.* ;
public class EchoClient {
public static void main(String[]args) throws IOException {
Socket socket = null ;
PrintWriter out = null ;
BufferedReader in = null ;
String host = "localhost" ;
try {
socket = new Socket(host,7) ;
// Port number 7
out = new PrintWriter(socket.getOutputStream(),true) ;
in = new BufferedReader(new InputStreamReader(socket.getInputStream())) ;
} catch (UnknownHostException e) {
System.err.println("Dont know host: "+host) ;
System.exit(-1) ;
} catch (IOException e) {
System.err.println("Cannot get IO for connection to "+host) ;
System.exit(-1) ;
}
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)) ;
String input ;
while ((input=stdin.readLine())!=null) {
out.println(input) ;
System.out.println("echo: "+in.readLine()) ;
}
out.close() ; in.close() ; stdin.close() ; socket.close() ;
// Order important
} }
Socket Connection for Client
Basic program flow for Client

1.
2.
3.
4.
5.
–
Open Socket
Open an input stream and output stream to the
socket
Read from and write to the stream according to the
server’s protocol
Close the streams
Close the socket
Only step 3 differs from client to client, depending
on the server
Socket Connection for Server

Basic program flow for Server
1.
2.
3.
4.
5.
6.
7.

Create a ServerSocket
Call ServerSocket.accept() to get a Socket connection
Open input stream and output stream to that socket
Read from and write to streams according to the Protocol
Close the streams
Close the socket
( Optional: Return to 2 to get another connection )
For Server allowing multiple connections, 3-6 must be in
another thread
Example: Knock Knock

Example, the Knock Knock jokes
Server
Client
Server
Client
Server

: “Knock! Knock!”
: “Who’s there?”
: “Dexter”
: “Dexter who?”
: “Dexter halls with boughs of holly”
Classes:
KnockKnockProtocol : To implement the protocol
KnockKnockServer : Has main method for the Server and listens to
the port
KnockKnockClient : Connects to the server
KnockKnockProtocol
import java.net.* ;
import java.io.* ;
public class KnockKnockProtocol {
private static final int WAITING = 0 , SENTKNOCKKNOCK = 1 , SENTCLUE = 2 , ANOTHER = 3 ;
private static final int NUMJOKES = 5 ;
private int state = WAITING ;
private int currentJoke = 0 ;
private String[] clues = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" } ;
private String[] answers = { "Turnip the heat, it's cold in here", "I didn't know you could yodel!",
"Bless you!", "Is there an owl here?", "Is there an echo in here?" } ;
public String processInput(String theInput) {
String theOutput=null;
if (state==WAITING) {
theOutput="Knock! Knock!" ; state = SENTKNOCKKNOCK ;
} else if (state==SENTKNOCKKNOCK) {
if (theInput.equalsIgnoreCase("Who's there?")) {
theOutput = clues[currentJoke] ; state = SENTCLUE ;
} else {
theOutput = "You're supposed to say 'Who's there?' Try again. Knock! Knock!" ;
}
} else if (state==SENTCLUE) {
if (theInput.equalsIgnoreCase(clues[currentJoke]+" who?")) {
theOutput = answers[currentJoke] + " Want another? (y/n)" ; state = ANOTHER ;
} else {
theOutput = "You're supposed to say '"+clues[currentJoke]+" who?'"+" ! Try again. Knock! Knock!" ; state = SENTKNOCKKNOCK ;
}
} else if (state==ANOTHER) {
if (theInput.equalsIgnoreCase("y")) {
theOutput = "Knock! Knock!" ;
if ((++currentJoke)==NUMJOKES)
currentJoke=0 ;
state = SENTKNOCKKNOCK ;
} else {
theOutput = "Bye." ; state = WAITING ;
}}
return theOutput ;
}}
KnockKnockServer
import java.net.* ;
import java.io.* ;
public class KnockKnockServer
{
public static void main(String[]args) throws IOException {
ServerSocket serverSocket = null ;
try { serverSocket = new ServerSocket(4444) ; }
catch (IOException e) { System.err.println("Cannot listen on port 4444") ; System.exit(-1) ; }
Socket clientSocket = null ;
try { clientSocket = serverSocket.accept() ; }
catch (IOException e) { System.err.println("Accept failed") ; System.exit(-1) ; }
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true) ;
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())) ;
String inputLine, outputLine ;
KnockKnockProtocol kkp = new KnockKnockProtocol() ;
outputLine = kkp.processInput(null) ;
out.println(outputLine) ;
while((inputLine=in.readLine())!=null) {
outputLine = kkp.processInput(inputLine) ;
out.println(outputLine) ;
if (outputLine.equals("Bye.")) break ;
}
out.close() ; in.close() ;
clientSocket.close() ; serverSocket.close() ;
}}
KnockKnockClient
import java.io.* ;
import java.net.* ;
public class KnockKnockClient {
public static void main(String[]args) throws IOException {
Socket kkSocket = null ; PrintWriter out = null ; BufferedReader in = null ;
try {
kkSocket = new Socket("localhost",4444) ;
out = new PrintWriter(kkSocket.getOutputStream(),true) ;
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())) ;
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost") ; System.exit(-1) ;
} catch (IOException e) {
System.err.println("Cannot get IO for the connection to: localhost") ; System.exit(-1) ;
}
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)) ;
String fromServer, fromUser ;
while ((fromServer=in.readLine())!=null) {
System.out.println("Server: "+fromServer) ;
if (fromServer.equals("Bye.")) break ;
fromUser = stdin.readLine() ;
if (fromUser!=null) {
System.out.println("Client: "+fromUser) ;
out.println(fromUser) ;
}}
out.close() ; in.close() ; stdin.close() ;
kkSocket.close() ;
} }
KnockKnock Run

Server Side
E:\>java KnockKnockServer

Client Side
E:\>java KnockKnockClient
Server: Knock! Knock!
who is?
Client: who is?
Server: You're supposed to say 'Who's there?' Try again. Knock! Knock!
Who's there?
Client: Who's there?
Server: Turnip
Turnip who?
Client: Turnip who?
Server: Turnip the heat, it's cold in here Want another? (y/n)
n
Client: n
Server: Bye.
Supporting Multiple Clients

In the Server Side
while (true) {
accept a connection ;
create a thread to deal with the client ;
}
Server Thread - KKMultiServerThread
import java.net.* ;
import java.io.* ;
public class KKMultiServerThread extends Thread {
private Socket socket = null ;
public KKMultiServerThread(Socket socket) {
this.socket = socket ;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())) ;
PrintWriter out = new PrintWriter(socket.getOutputStream(),true) ;
String inputLine, outputLine ;
KnockKnockProtocol kkp = new KnockKnockProtocol() ;
outputLine = kkp.processInput(null) ;
out.println(outputLine) ;
while ((inputLine=in.readLine())!=null) {
outputLine = kkp.processInput(inputLine) ;
out.println(outputLine) ;
if (outputLine.equals("Bye."))
break ;
}
out.close() ; in.close() ; socket.close() ;
} catch (IOException e) {
e.printStackTrace() ;
} } }
Server Class - KKMultiServer
import java.net.* ;
import java.io.* ;
public class KKMultiServer {
public static void main(String[]args) throws IOException {
ServerSocket serverSocket = null ;
boolean listening = true ;
try {
serverSocket = new ServerSocket(4444) ;
} catch (IOException e) {
System.err.println("Could not listen on port 4444") ;
System.exit(-1) ;
}
while (listening)
new KKMultiServerThread(serverSocket.accept()).start() ;
serverSocket.close() ;
}
}
Remote Connections

Identifying a Machine

IP (Internet Protocol) adress
1.
2.


DNS (Domain Name System) : www.cs.biu.ac.il
Dotted Quad Form : 123.255.28.120
InetAddress ia=InetAddress.getByName(…);
Local Host (for testing)

All these three forms connect to local host




InetAddress ia=InetAddress.getByName(null) ;
InetAddress ia=InetAddress.getByName(“localhost”);
InetAddress ia=InetAddress.getByName(“127.0.0.1”);
InetAddress ia=InetAddress.getLocalHost()
Identifying a Machine
import java.net.*;
public class WhoAmI {
public static void main(String[] args) throws Exception {
if(args.length != 1) {
System.err.println("Usage: WhoAmI MachineName");
System.exit(1);
}
InetAddress a = InetAddress.getByName(args[0]);
System.out.println(a);
}
}
To run:
java WhoAmI myMachine
myMachine/127.0.0.1
UDP communication


UDP : Delivers independent packages whose
arrival and order of arrival is not guaranteed.
Packets sent by UDP protocol are called
Datagrams.
 DataGram
: Is an independent, self-contained
message sent over the network whose arrival, and
content are not guaranteed.

Classes for UDP connection
 DatagramPacket
 DatagramSocket
 MulticastSocket
DatagramPacket class

Constructors







DatagramPacket(byte
DatagramPacket(byte
DatagramPacket(byte
DatagramPacket(byte
DatagramPacket(byte
DatagramPacket(byte
buf[], int offset, int length)
buf[], int length)
buf[], int offset, int length, InetAddress address, int port)
buf[], int offset, int length, SocketAddress address)
buf[], int length, InetAddress address, int port)
buf[], int length, SocketAddress address)
Methods












void setAddress(InetAddress iaddr)
InetAddress getAddress()
void setSocketAddress(SocketAddress address)
SocketAddress getSocketAddress()
void setPort(int iport)
int getPort()
byte[] getData()
int getOffset()
int getLength() {
void setData(byte[] buf, int offset, int length)
void setData(byte[] buf)
void setLength(int length)
Example: Quote Server - Client

QuoteServer

Waits to get a DataGram
 Reads the next line from file “lines.txt”
 Sends it as a DataGram

QuoteClient



Sends a DataGram to Server
Listens to the Server for getting a DataGram with the Quote
Lines.txt file
Quote number 1.
Quote number 2.
Quote number 3.
Quote number 4.
…

Run:




E:\>java QuoteClient localhost
Received: Quote number 1.
E:\>java QuoteClient localhost
Received: Quote number 2.
Example : QuoteServer
public QuoteServer() {
import java.io.* ;
import java.net.* ;
try { in = new BufferedReader(new FileReader("lines.txt")) ;
import java.util.* ;
} catch (IOException e) { System.err.println("Cannot open
public class QuoteServer {
file lines.txt.") ; }
protected DatagramSocket socket = null ;
}
protected BufferedReader in = null ;
public String getNextQuote() {
protected boolean moreQuotes = true ;
String retVal = null ;
public void run() throws IOException {
if (in==null) {
socket = new DatagramSocket(4445) ;
retVal = "Error in opening file." ;
while (moreQuotes) {
moreQuotes = false ;
try {
} else {
byte[] buf = new byte[256] ;
try {
// Request
if ((retVal=in.readLine())==null) {
DatagramPacket packet = new DatagramPacket(buf,buf.length) ;
in.close() ;
socket.receive(packet) ;
retVal = "No more quotes." ;
// Response
moreQuotes = false ;
String response = getNextQuote() ;
}
buf = response.getBytes() ;
} catch (IOException e) {
// Send the response
retVal = "Exception in server." ;
InetAddress address = packet.getAddress() ;
moreQuotes = false ;
int port = packet.getPort() ;
}
packet = new DatagramPacket(buf,buf.length,address,port) ;
}
socket.send(packet) ;
return retVal ;
} catch(IOException e) {
}
e.printStackTrace() ;
public static void main(String[]args) throws IOException {
moreQuotes = false ;
QuoteServer qs = new QuoteServer() ;
} }
qs.run() ;
socket.close() ;
}
}
}
Example: QuoteClient
import java.io.* ;
import java.net.* ;
import java.util.* ;
public class QuoteClient {
public static void main(String[]args) throws IOException {
if (args.length!=1) {
System.err.println("Usage: java QuoteClient hostname") ;
return ;
}
DatagramSocket socket = new DatagramSocket() ;
byte[] buf=new byte[256] ;
InetAddress address = InetAddress.getByName(args[0]) ;
DatagramPacket packet = new DatagramPacket(buf,buf.length,address,4445) ;
socket.send(packet) ;
packet=new DatagramPacket(buf,buf.length) ;
socket.receive(packet) ;
String received=new String(packet.getData()) ;
System.out.println("Received: "+received) ;
socket.close() ;
}
}
SMTP : Sending e-mail

SMTP : Simple Mail Transfer Protocol



A client delivers mail using a mail-server by opening a socket
(TCP) connection to port 25 of it.
Once the connection is made, the client sends some commands
for sending e-mail messages
For each command, Server sends back a message
starting with a number



Numbers 200-299: A successful command
Numbers 300-399: Initially successful, but more information
needed to complete it.
Numbers 400-499,500-599: Error
SMTP Commands

SMTP Commands




HELO : Greeting from the client to server
MAIL FROM: sender’s address
RCPT TO: recipient address
DATA



To read the message one line at a time.
“.” to end the message
Example session (may be with telnet connection)
HELO
250 ….
MAIL FROM: bill
250 bill… sender ok
RCPT TO: mark
250 mark… Recipient ok
DATA
354 Enter main, end with “.” on a line by itself
Subject: Hey there…
This is a trial message
.
250 VAA07456 Message accepted for delivery
POP3 protocol

POP3 : Post Office Protocol version 3.


Allows you to access your mailbox remotely
Responses start with





‘+’ for successful commands
‘-’ in case of any error
Sometimes it returns multi-line responses, that terminate with “.”
line.
Usually it sits on port number 110.
POP3 logging


USER your_user_name
PASS your_password
POP3 commands

POP3 access commands






STAT : Retrieves the message count
LIST : Gets a list of active message numbers
TOP : To examine the beginning of a message
RETR : To read an entire message
DELE : To delete a message
Example: (Telnet session)
+OK …ready
USER mark
+OK please send PASS command
PASS abc?012
+OK 1 messages ready for mark in /usr/spool/mail/mark
LIST
+OK 1 messages; msg# and size for undeleted messages
1 461
.
RETR 1
+OK message 1
…. // The whole message content
.
DELE 1
+OK message 1 marked for deletion
LIST
+OK 1 messages; msg# and size for undeleted messages
.
QUIT
+OK … shutdown