Networking Basics Moshe Fresko BarIlan University Networking Basics
Networking Basics Moshe Fresko Bar-Ilan University
Networking Basics n 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, Sat. Net, Lan, …)
TCP vs UDP n 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: n n 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: n Radio, Clock Server, Ping,
IP Address n n IP (Internet Protocol) : Network layer protocol. IP Address : A unique 32 bit number. ¨ ¨ n n Every host and router in the Internet has an IP address, which encodes its network number and host number. Classes of IP Addresses ¨ ¨ ¨ n Dotted Decimal Notation : 192. 41. 6. 20 Range : 0. 0 – 255 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 : This host 255 : Broadcast on local network 127. ? . ? : Loopback
Ports n n n 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 ¨ n 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 n n URL : Uniform Resource Locater : It is a reference (an address) to a resource on the Internet. A URL has two main components n n ¨ Example : http: //java. sun. com/ n n n Protocol Identifier Resource Name http : is the Protocol Identifier //java. sun. com/ : is the Resource Name The Resource Name may contain Host. Name : The name of the machine File. Name : 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 n Two classes for URL processing in Java ¨ ¨ n java. net. URL : Represents a URL resource java. net. URLConnection : An opened connection to a URL resource Creating an absolute URL object n n n Creating a URL relative to another n n By Constructor : URL(String) URL myurl = new URL(“http: //cs. biu. ac. il/”) ; Used for relative hyperlinks in an HTML page <A HREF=“My. Pres. html”>Presentations</A> By Constructor : URL(URL, String) URL myurl = new URL(“http: //cs. biu. ac. il/~freskom 1/”) ; URL mypres = new URL(myurl, “My. Pres. html”) ; Other URL Constructors ¨ All constructors throw Malformed. URLException n n 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 n Parsing a URL String get. Protocol() String get. Host() int get. Port() String get. File() String get. Ref() n Example import java. net. * ; public class Parse. URL { public static void main(String[]args) throws Malformed. URLException { URL url = new URL("http: //java. sun. com: 80/docs/”+ ”books/tutorial/intro. html#DOWNLOADING") ; System. out. println("Protocol = "+url. get. Protocol()) ; System. out. println("Host = "+url. get. Host()) ; System. out. println("File. Name = "+url. get. File()) ; System. out. println("Port = "+url. get. Port()) ; System. out. println("Reference= "+url. get. Ref()) ; } } ¨ Output Protocol = http Host = java. sun. com File. Name = /docs/books/tutorial/intro. html Port = 80 Reference= DOWNLOADING
URLs n Reading directly from a URL using open. Stream() method that returns an Input. Stream ¨ 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/~freskom 1/") ; Buffered. Reader br = new Buffered. Reader ( new Input. Stream. Reader(url. open. Stream())) ; String line ; while ((line=br. read. Line())!=null) System. out. println(line) ; br. close() ; } }
URL Connection n Connecting to a URL ¨ URL’s open. Connection() method URLConnection open. Connection() throws IOException ; ¨ Example: try { URL url = new URL("http: //www. cs. biu. ac. il/~freskom 1/") ; URLConnection uc = url. open. Connection() ; } catch (Malformed. URLException e) { … } catch (IOException e) { … } n Reading from a URL connection import java. net. * ; import java. io. * ; public class URLConnection. Reader { public static void main(String[] args) throws Exception { URL url = new URL("http: //www. cs. biu. ac. il/~freskom 1/") ; URLConnection uc = url. open. Connection() ; Buffered. Reader br=new Buffered. Reader(new Input. Stream. Reader(uc. get. Input. Stream())); String line ; while ((line=br. read. Line())!=null) System. out. println(line) ; br. close() ; } }
Writing to a URLConnection n Like HTML forms. ¨ ¨ ¨ n 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 string. To. Reverse = URLEncoder. encode(args[0], "UTF-8") ; URL url = new URL("http: //java. sun. com/cgi-bin/backwards") ; URLConnection uc = url. open. Connection() ; uc. set. Do. Output(true) ; Print. Writer out = new Print. Writer(uc. get. Output. Stream()) ; out. println("string="+string. To. Reverse) ; out. close() ; Buffered. Reader in = new Buffered. Reader(new Input. Stream. Reader(uc. get. Input. Stream())) ; String line ; while ((line=in. read. Line())!=null) System. out. println(line) ; }}
Sockets n n 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 ¨ Server. Socket : For server n ¨ On connection returns a new Socket : For client n Have get. Input. Stream() and get. Output. Stream() functions
Socket Example – Echo import java. io. * ; import java. net. * ; public class Echo. Client { public static void main(String[]args) throws IOException { Socket socket = null ; Print. Writer out = null ; Buffered. Reader in = null ; String host = "localhost" ; try { socket = new Socket(host, 7) ; // Port number 7 out = new Print. Writer(socket. get. Output. Stream(), true) ; in = new Buffered. Reader(new Input. Stream. Reader(socket. get. Input. Stream())) ; } catch (Unknown. Host. Exception 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) ; } Buffered. Reader stdin = new Buffered. Reader(new Input. Stream. Reader(System. in)) ; String input ; while ((input=stdin. read. Line())!=null) { out. println(input) ; System. out. println("echo: "+in. read. Line()) ; } out. close() ; in. close() ; stdin. close() ; socket. close() ; // Order important } }
Socket Connection for Client Basic program flow for Client n 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 n Basic program flow for Server 1. 2. 3. 4. 5. 6. 7. ¨ Create a Server. Socket Call Server. Socket. 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 n Example, the Knock jokes Server Client Server n : “Knock!” : “Who’s there? ” : “Dexter who? ” : “Dexter halls with boughs of holly” Classes: Knock. Protocol : To implement the protocol Knock. Server : Has main method for the Server and listens to the port Knock. Client : Connects to the server
Knock. Protocol import java. net. * ; import java. io. * ; public class Knock. Protocol { private static final int WAITING = 0 , SENTKNOCK = 1 , SENTCLUE = 2 , ANOTHER = 3 ; private static final int NUMJOKES = 5 ; private int state = WAITING ; private int current. Joke = 0 ; private String[] clues = { "Turnip", "Little Old Lady", "Atch", "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 process. Input(String the. Input) { String the. Output=null; if (state==WAITING) { the. Output="Knock!" ; state = SENTKNOCK ; } else if (state==SENTKNOCK) { if (the. Input. equals. Ignore. Case("Who's there? ")) { the. Output = clues[current. Joke] ; state = SENTCLUE ; } else { the. Output = "You're supposed to say 'Who's there? ' Try again. Knock!" ; } } else if (state==SENTCLUE) { if (the. Input. equals. Ignore. Case(clues[current. Joke]+" who? ")) { the. Output = answers[current. Joke] + " Want another? (y/n)" ; state = ANOTHER ; } else { the. Output = "You're supposed to say '"+clues[current. Joke]+" who? '"+" ! Try again. Knock!" ; state = SENTKNOCK ; } } else if (state==ANOTHER) { if (the. Input. equals. Ignore. Case("y")) { the. Output = "Knock!" ; if ((++current. Joke)==NUMJOKES) current. Joke=0 ; state = SENTKNOCK ; } else { the. Output = "Bye. " ; state = WAITING ; }} return the. Output ; }}
Knock. Server import java. net. * ; import java. io. * ; public class Knock. Server { public static void main(String[]args) throws IOException { Server. Socket server. Socket = null ; try { server. Socket = new Server. Socket(4444) ; } catch (IOException e) { System. err. println("Cannot listen on port 4444") ; System. exit(-1) ; } Socket client. Socket = null ; try { client. Socket = server. Socket. accept() ; } catch (IOException e) { System. err. println("Accept failed") ; System. exit(-1) ; } Print. Writer out = new Print. Writer(client. Socket. get. Output. Stream(), true) ; Buffered. Reader in = new Buffered. Reader(new Input. Stream. Reader(client. Socket. get. Input. Stream())) ; String input. Line, output. Line ; Knock. Protocol kkp = new Knock. Protocol() ; output. Line = kkp. process. Input(null) ; out. println(output. Line) ; while((input. Line=in. read. Line())!=null) { output. Line = kkp. process. Input(input. Line) ; out. println(output. Line) ; if (output. Line. equals("Bye. ")) break ; } out. close() ; in. close() ; client. Socket. close() ; server. Socket. close() ; }}
Knock. Client import java. io. * ; import java. net. * ; public class Knock. Client { public static void main(String[]args) throws IOException { Socket kk. Socket = null ; Print. Writer out = null ; Buffered. Reader in = null ; try { kk. Socket = new Socket("localhost", 4444) ; out = new Print. Writer(kk. Socket. get. Output. Stream(), true) ; in = new Buffered. Reader(new Input. Stream. Reader(kk. Socket. get. Input. Stream())) ; } catch (Unknown. Host. Exception 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) ; } Buffered. Reader stdin = new Buffered. Reader(new Input. Stream. Reader(System. in)) ; String from. Server, from. User ; while ((from. Server=in. read. Line())!=null) { System. out. println("Server: "+from. Server) ; if (from. Server. equals("Bye. ")) break ; from. User = stdin. read. Line() ; if (from. User!=null) { System. out. println("Client: "+from. User) ; out. println(from. User) ; }} out. close() ; in. close() ; stdin. close() ; kk. Socket. close() ; } }
Knock Run n Server Side E: >java Knock. Server n Client Side E: >java Knock. Client Server: Knock! who is? Client: who is? Server: You're supposed to say 'Who's there? ' Try again. Knock! Who's there? Client: Who's there? Server: 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 n In the Server Side while (true) { accept a connection ; create a thread to deal with the client ; }
Server Thread - KKMulti. Server. Thread import java. net. * ; import java. io. * ; public class KKMulti. Server. Thread extends Thread { private Socket socket = null ; public KKMulti. Server. Thread(Socket socket) { this. socket = socket ; } public void run() { try { Buffered. Reader in = new Buffered. Reader(new Input. Stream. Reader(socket. get. Input. Stream())) ; Print. Writer out = new Print. Writer(socket. get. Output. Stream(), true) ; String input. Line, output. Line ; Knock. Protocol kkp = new Knock. Protocol() ; output. Line = kkp. process. Input(null) ; out. println(output. Line) ; while ((input. Line=in. read. Line())!=null) { output. Line = kkp. process. Input(input. Line) ; out. println(output. Line) ; if (output. Line. equals("Bye. ")) break ; } out. close() ; in. close() ; socket. close() ; } catch (IOException e) { e. print. Stack. Trace() ; } } }
Server Class - KKMulti. Server import java. net. * ; import java. io. * ; public class KKMulti. Server { public static void main(String[]args) throws IOException { Server. Socket server. Socket = null ; boolean listening = true ; try { server. Socket = new Server. Socket(4444) ; } catch (IOException e) { System. err. println("Could not listen on port 4444") ; System. exit(-1) ; } while (listening) new KKMulti. Server. Thread(server. Socket. accept()). start() ; server. Socket. close() ; } }
Remote Connections n Identifying a Machine ¨ IP (Internet Protocol) adress 1. 2. ¨ n DNS (Domain Name System) : www. cs. biu. ac. il Dotted Quad Form : 123. 255. 28. 120 Inet. Address ia=Inet. Address. get. By. Name(…); Local Host (for testing) ¨ All these three forms connect to local host n n Inet. Address ia=Inet. Address. get. By. Name(null) ; Inet. Address ia=Inet. Address. get. By. Name(“localhost”); Inet. Address ia=Inet. Address. get. By. Name(“ 127. 0. 0. 1”); Inet. Address ia=Inet. Address. get. Local. Host()
Identifying a Machine import java. net. *; public class Who. Am. I { public static void main(String[] args) throws Exception { if(args. length != 1) { System. err. println("Usage: Who. Am. I Machine. Name"); System. exit(1); } Inet. Address a = Inet. Address. get. By. Name(args[0]); System. out. println(a); } } To run: java Who. Am. I my. Machine/127. 0. 0. 1
UDP communication n n UDP : Delivers independent packages whose arrival and order of arrival is not guaranteed. Packets sent by UDP protocol are called Datagrams. ¨ Data. Gram : Is an independent, self-contained message sent over the network whose arrival, and content are not guaranteed. n Classes for UDP connection ¨ Datagram. Packet ¨ Datagram. Socket ¨ Multicast. Socket
Datagram. Packet class n Constructors ¨ ¨ ¨ n Datagram. Packet(byte buf[], int offset, int length) Datagram. Packet(byte buf[], int offset, int length, Inet. Address address, int port) Datagram. Packet(byte buf[], int offset, int length, Socket. Address address) Datagram. Packet(byte buf[], int length, Inet. Address address, int port) Datagram. Packet(byte buf[], int length, Socket. Address address) Methods ¨ ¨ ¨ void set. Address(Inet. Address iaddr) Inet. Address get. Address() void set. Socket. Address(Socket. Address address) Socket. Address get. Socket. Address() void set. Port(int iport) int get. Port() byte[] get. Data() int get. Offset() int get. Length() { void set. Data(byte[] buf, int offset, int length) void set. Data(byte[] buf) void set. Length(int length)
Example: Quote Server - Client n Quote. Server ¨ ¨ ¨ n Quote. Client ¨ ¨ n Waits to get a Data. Gram Reads the next line from file “lines. txt” Sends it as a Data. Gram Sends a Data. Gram to Server Listens to the Server for getting a Data. Gram with the Quote Lines. txt file Quote number 1. Quote number 2. Quote number 3. Quote number 4. … n Run: ¨ ¨ E: >java Quote. Client localhost Received: Quote number 1. E: >java Quote. Client localhost Received: Quote number 2.
Example : Quote. Server public Quote. Server() { import java. io. * ; try { in = new Buffered. Reader(new File. Reader("lines. txt")) ; import java. net. * ; import java. util. * ; } catch (IOException e) { System. err. println("Cannot open public class Quote. Server { file lines. txt. ") ; } protected Datagram. Socket socket = null ; } protected Buffered. Reader in = null ; public String get. Next. Quote() { protected boolean more. Quotes = true ; String ret. Val = null ; public void run() throws IOException { if (in==null) { socket = new Datagram. Socket(4445) ; ret. Val = "Error in opening file. " ; while (more. Quotes) { more. Quotes = false ; try { } else { byte[] buf = new byte[256] ; try { // Request if ((ret. Val=in. read. Line())==null) { Datagram. Packet packet = new Datagram. Packet(buf, buf. length) ; in. close() ; socket. receive(packet) ; ret. Val = "No more quotes. " ; // Response more. Quotes = false ; String response = get. Next. Quote() ; } buf = response. get. Bytes() ; } catch (IOException e) { // Send the response ret. Val = "Exception in server. " ; Inet. Address address = packet. get. Address() ; more. Quotes = false ; int port = packet. get. Port() ; } packet = new Datagram. Packet(buf, buf. length, address, port) ; } socket. send(packet) ; return ret. Val ; } catch(IOException e) { } e. print. Stack. Trace() ; public static void main(String[]args) throws IOException { more. Quotes = false ; Quote. Server qs = new Quote. Server() ; } } qs. run() ; socket. close() ; } } }
Example: Quote. Client import java. io. * ; import java. net. * ; import java. util. * ; public class Quote. Client { public static void main(String[]args) throws IOException { if (args. length!=1) { System. err. println("Usage: java Quote. Client hostname") ; return ; } Datagram. Socket socket = new Datagram. Socket() ; byte[] buf=new byte[256] ; Inet. Address address = Inet. Address. get. By. Name(args[0]) ; Datagram. Packet packet = new Datagram. Packet(buf, buf. length, address, 4445) ; socket. send(packet) ; packet=new Datagram. Packet(buf, buf. length) ; socket. receive(packet) ; String received=new String(packet. get. Data()) ; System. out. println("Received: "+received) ; socket. close() ; } }
SMTP : Sending e-mail n 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 ¨ n 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 n SMTP Commands ¨ ¨ HELO : Greeting from the client to server MAIL FROM: sender’s address RCPT TO: recipient address DATA n n n 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 VAA 07456 Message accepted for delivery
POP 3 protocol n POP 3 : Post Office Protocol version 3. Allows you to access your mailbox remotely ¨ Responses start with ¨ n n ‘+’ 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. ¨ n POP 3 logging USER your_user_name ¨ PASS your_password ¨
POP 3 commands n POP 3 access commands ¨ ¨ ¨ n 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
- Slides: 35