Presentation is loading. Please wait.

Presentation is loading. Please wait.

Moshe Fresko Bar-Ilan University

Similar presentations


Presentation on theme: "Moshe Fresko Bar-Ilan University"— Presentation transcript:

1 Moshe Fresko Bar-Ilan University
Networking Basics Moshe Fresko Bar-Ilan University

2 Networking Basics Uses of Networks Resource Sharing High Reliability
Saving Money Communication Medium Access to remote information

3 Network Layers Application Layer (http,ftp,telnet,smtp,dns,…)
Transport Layer (TCP,UDP,…) Network Layer (IP,…) Physical + Data Link Layer (Arpanet,SatNet,Lan, …)

4 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. Radio, Clock Server, Ping,

5 IP Address IP (Internet Protocol) : Network layer protocol.
IP Address : A unique 32 bit number. Dotted Decimal Notation : Range : – 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 : This host : Broadcast on local network 127.?.?.? : Loopback

6 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: 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

7 URLs URL : Uniform Resource Locater : It is a reference (an address) to a resource on the Internet. A URL has two main components Protocol Identifier Resource Name Example : 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)

8 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 By Constructor : URL(String) URL myurl = new URL(“ ; Creating a URL relative to another Used for relative hyperlinks in an HTML page <A HREF=“MyPres.html”>Presentations</A> By Constructor : URL(URL,String) URL myurl = new URL(“ ; 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)

9 URLs Parsing a URL Example Output 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(" ”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

10 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(" ; BufferedReader br = new BufferedReader ( new InputStreamReader(url.openStream())) ; String line ; while ((line=br.readLine())!=null) System.out.println(line) ; br.close() ; } URL.openStream ==  Opens a connection to this URL and returns an InputStream for reading from that connection.

11 URL Connection Connecting to a URL Reading from a URL connection
URL’s openConnection() method URLConnection openConnection() throws IOException ; Example: try { URL url = new URL(" ; 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 { BufferedReader br=new BufferedReader(new InputStreamReader(uc.getInputStream())); String line ; while ((line=br.readLine())!=null) System.out.println(line) ; br.close() ;

12 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(" ; 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) ; } }

13 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

14 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) ; } 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 } }

15 Socket Connection for Client
Basic program flow for Client 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

16 Socket Connection for Server
Basic program flow for Server 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

17 Example: Knock Knock Example, the Knock Knock jokes Classes:
Server : “Knock! Knock!” Client : “Who’s there?” Server : “Dexter” Client : “Dexter who?” Server : “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

18 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 ; 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 ; theOutput = "Bye." ; state = WAITING ; } } return theOutput ;

19 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) ; if (outputLine.equals("Bye.")) break ; } out.close() ; in.close() ; clientSocket.close() ; serverSocket.close() ; } }

20 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() ; } }

21 KnockKnock Run Server Side Client Side E:\>java KnockKnockServer
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.

22 Supporting Multiple Clients
In the Server Side while (true) { accept a connection ; create a thread to deal with the client ; }

23 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) ; if (outputLine.equals("Bye.")) break ; out.close() ; in.close() ; socket.close() ; } catch (IOException e) { e.printStackTrace() ; } } }

24 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() ;

25 Remote Connections Identifying a Machine Local Host (for testing)
IP (Internet Protocol) adress DNS (Domain Name System) : Dotted Quad Form : 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(“ ”); InetAddress ia=InetAddress.getLocalHost()

26 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/

27 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

28 DatagramPacket class Constructors Methods
DatagramPacket(byte buf[], int offset, int length) DatagramPacket(byte buf[], int length) DatagramPacket(byte buf[], int offset, int length, InetAddress address, int port) DatagramPacket(byte buf[], int offset, int length, SocketAddress address) DatagramPacket(byte buf[], int length, InetAddress address, int port) DatagramPacket(byte 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)

29 Example: Quote Server - Client
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. Received: Quote number 2.

30 Example : QuoteServer public QuoteServer() {
try { in = new BufferedReader(new FileReader("lines.txt")) ; } catch (IOException e) { System.err.println("Cannot open file lines.txt.") ; } } public String getNextQuote() { String retVal = null ; if (in==null) { retVal = "Error in opening file." ; moreQuotes = false ; } else { try { if ((retVal=in.readLine())==null) { in.close() ; retVal = "No more quotes." ; } catch (IOException e) { retVal = "Exception in server." ; return retVal ; public static void main(String[]args) throws IOException { QuoteServer qs = new QuoteServer() ; qs.run() ; import java.io.* ; import java.net.* ; import java.util.* ; public class QuoteServer { protected DatagramSocket socket = null ; protected BufferedReader in = null ; protected boolean moreQuotes = true ; public void run() throws IOException { socket = new DatagramSocket(4445) ; while (moreQuotes) { try { byte[] buf = new byte[256] ; // Request DatagramPacket packet = new DatagramPacket(buf,buf.length) ; socket.receive(packet) ; // Response String response = getNextQuote() ; buf = response.getBytes() ; // Send the response InetAddress address = packet.getAddress() ; int port = packet.getPort() ; packet = new DatagramPacket(buf,buf.length,address,port) ; socket.send(packet) ; } catch(IOException e) { e.printStackTrace() ; moreQuotes = false ; } } socket.close() ; }

31 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() ;

32 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 messages For each command, Server sends back a message starting with a number Numbers : A successful command Numbers : Initially successful, but more information needed to complete it. Numbers , : Error

33 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 354 Enter main, end with “.” on a line by itself Subject: Hey there… This is a trial message . 250 VAA07456 Message accepted for delivery

34 POP3 protocol POP3 : Post Office Protocol version 3. POP3 logging
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

35 POP3 commands POP3 access commands Example: (Telnet session)
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 QUIT +OK … shutdown


Download ppt "Moshe Fresko Bar-Ilan University"

Similar presentations


Ads by Google