Corso di Reti di Calcolatori. java.net.inetaddress



Similar documents
Socket Programming in Java

NETWORK PROGRAMMING IN JAVA USING SOCKETS

Network/Socket Programming in Java. Rajkumar Buyya

Application Development with TCP/IP. Brian S. Mitchell Drexel University

Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1

Creating a Simple, Multithreaded Chat System with Java

Building a Multi-Threaded Web Server

TP1 : Correction. Rappels : Stream, Thread et Socket TCP

CISC 4700 L01 Network & Client- Server Programming Spring Harold, Chapter 8: Sockets for Clients

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

Java Network. Slides prepared by : Farzana Rahman

Network Communication

Mail User Agent Project

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

Advanced Network Programming Lab using Java. Angelos Stavrou

JAVA Program For Processing SMS Messages

Socket-based Network Communication in J2SE and J2ME

!"# $ %!&' # &! ())*!$

Sockets. Programação de Sockets em Java. Socket Abstractions. Camada de Transporte

Lesson: All About Sockets

Assignment 4 Solutions

Transport layer protocols. Message destination: Socket +Port. Asynchronous vs. Synchronous. Operations of Request-Reply. Sockets

Threads in der Client/Server-Programmierung mit Java

String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivepacket.getaddress(); int port = receivepacket.

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

Java Programming: Sockets in Java

ExempleRMI.java. // Fichier de defintion des droits et proprietes // System.setProperty("java.security.policy","../server.java.

The difference between TCP/IP, UDP/IP and Multicast sockets. How servers and clients communicate over sockets

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

Division of Informatics, University of Edinburgh

Domain Name System (DNS) Omer F. Rana. Networks and Data Communications 1

! "# $%&'( ) * ).) "%&' 1* ( %&' ! "%&'2 (! ""$ 1! ""3($

INPUT AND OUTPUT STREAMS

Capitolo 14: Flussi. Capitolo 14. Flussi Apogeo srl Horstmann-Concetti di informatica e fondamenti di Java 2

Agenda. Network Programming and Java Sockets. Introduction. Internet Applications Serving Local and Remote Users

CHAPTER 6. Transmission Control Protocol. 6.1 Overview

CS 1302 Ch 19, Binary I/O

AVRO - SERIALIZATION

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Socket Programming. A er learning the contents of this chapter, the reader will be able to:

Preface. Intended Audience

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

public class neurale extends JFrame implements NeuralNetListener {

public static void main(string[] args) { System.out.println("hello, world"); } }

D06 PROGRAMMING with JAVA

What is an I/O Stream?

DNS: Domain Names. DNS: Domain Name System. DNS: Root name servers. DNS name servers

An Android-based Instant Message Application

The Application Layer. CS158a Chris Pollett May 9, 2007.

Communicating with a Barco projector over network. Technical note

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

When the transport layer tries to establish a connection with the server, it is blocked by the firewall. When this happens, the RMI transport layer

Input / Output Framework java.io Framework

Abstract Stream Socket Service

Socket Programming. Announcement. Lectures moved to

Chapter 02 Networking in Java

Tecnologie e Protocolli per Internet 1 Introduzione al NAT Network Address Translation

TDD da un capo all altro. Matteo Vaccari (cc) Alcuni diritti riservati

CS506 Web Design and Development Solved Online Quiz No. 01

Files and input/output streams

Data Communication & Networks G

Manual. Programmer's Guide for Java API

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Network Programming using sockets

Apéndice C: Código Fuente del Programa DBConnection.java

TP N 10 : Gestion des fichiers Langage JAVA

Rappels programma,on réseau Java- suite. C. Delporte M2- Internet Rappel Java 1

JAVA - FILES AND I/O

13 File Output and Input

Socket programming. Complement for the programming assignment INFO-0010

Network-based Applications. Pavani Diwanji David Brown JavaSoft

Continuous Integration Part 2

Network Programming. CS 282 Principles of Operating Systems II Systems Programming for Android

Network Programming. Java provides easy-to-use classes for network programming. These classes integrate nicely with the rest of the language.

Tutorial Reference Manual. Java WireFusion 4.1

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

An Overview of Java. overview-1

Threads & Tasks: Executor Framework

Building a Java chat server

Course Intro Instructor Intro Java Intro, Continued

8. Java Network Programming

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Readings and References. Topic #10: Java Input / Output. "Streams" are the basic I/O objects. Input & Output. Streams. The stream model A-1.

Web Services in Eclipse. Sistemi Informativi Aziendali A.A. 2012/2013

CS108, Stanford Handout #33. Sockets

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Event-Driven Programming

EVALUATION OF TOOLS FOR CYBER SECURITY

Transcription:

Corso di Reti di Calcolatori UNICAL Facoltà di Ingegneria a.a. 2002/2003 Esercitazione sul networking in Java (1 a parte) paolo.trunfio@deis.unical.it 1 java.net.inetaddress static InetAddress getbyname(string host) restituisce l indirizzo IP di un dato host static InetAddress[] getallbyname(string host) restituisce tutti gli indirizzi IP di un dato host static InetAddress getlocalhost() restituisce l indirizzo IP di localhost byte[] getaddress() restituisce l indirizzo IP sotto forma array di byte String gethostaddress() restituisce l indirizzo IP sotto forma di stringa (p.es. 192.168.35.75 ) String gethostname() restituisce l host name associato all indirizzo IP 2

Lookup di indirizzi locali e remoti static void printlocaladdress () { InetAddress myself = InetAddress.getLocalHost (); System.out.println ("My name : " + myself.gethostname ()); System.out.println ("My IP : " + myself.gethostaddress ()); catch (UnknownHostException ex) { System.out.println ("Failed to find myself:"); static void printremoteaddress (String name) { InetAddress machine = InetAddress.getByName (name); System.out.println ("Host name : " + machine.gethostname ()); System.out.println ("Host IP : " + machine.gethostaddress ()); catch (UnknownHostException ex) { System.out.println ("Failed to lookup " + name); 3 java.net.socket Socket(String host, int port) Socket(InetAddress address, int port) void close() InetAddress getinetaddress() indirizzo a cui è connesso il socket int getport() porta remota a cui è connesso il socket int getlocalport() porta locale del socket InputStream getinputstream() OutputStream getoutputstream() void setsotimeout(int timeout) timeout per operazioni di lettura dal socket. Genera InterruptedIOException String tostring() restituisce una rappresentazione del socket del tipo: Socket[addr=hostname/192.168.35.75,port=3575,localport=1026] 4

Un semplice client public class ClientTest { public static void main(string[] args) { Socket s = new Socket("www.deis.unical.it",80); PrintWriter out = new PrintWriter (s.getoutputstream(),true); BufferedReader in = new BufferedReader (new InputStreamReader(s.getInputStream())); out.println ("GET / HTTP/1.0"); out.println (); boolean more = true; while (more) { String line = in.readline(); if (line == null) more = false; else System.out.println(line); catch (IOException e) { System.out.println("Error"+e); 5 Socket s = new Socket ( ); s.setsotimeout(10000); Timeout di socket Le operazioni di lettura che seguono generano una InterruptedIOException quando è stato raggiunto il timeout. String line; while (line = in.readline())!= null) { process line catch (InterrupedIOException e) { react to timeout Questo timeout può essere settato su un socket già istanziato. Tuttavia si potrebbe verificare un blocco indefinito già in fase di creazione del socket, fino a quando non si stabilisce la connessione con l host. 6

SocketOpener (1) public class SocketOpenerTest { public static void main(string[] args) { String host = "www.deis.unical.it"; int port = 80; int timeout = 10000; Socket s = SocketOpener.openSocket(host, port, timeout); if (s == null) System.out.println("The socket could not be opened."); else System.out.println(s); class SocketOpener extends Thread { private String host; private int port; private Socket socket; 7 SocketOpener (2) public static Socket opensocket (String host, int port, int timeout) { SocketOpener opener = new SocketOpener(host, port); opener.start(); opener.join(timeout); catch (InterruptedException e) { System.err.println (e); return opener.getsocket(); public SocketOpener(String host, int port) { this.host = host; this.port = port; socket = null; public Socket getsocket() { return socket; public void run() { socket = new Socket(host, port); catch (IOException e) { System.err.println (e); 8

ServerSocket(int port) java.net.serversocket Socket accept() rimane in attesa di una connessione, e restituisce un socket tramite il quale si effettua la comunicazione void close() InetAddress getinetaddress() indirizzo locale di questo server socket int getlocalport() porta locale di questo server socket 9 EchoServer (1) public class EchoServer { public static void main(string[] args ) { ServerSocket s = new ServerSocket(8189); Socket incoming = s.accept( ); BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getoutputstream(), true /* autoflush */); out.println( "Hello! Enter BYE to exit." ); 10

EchoServer (2) boolean done = false; while (!done) { String line = in.readline(); if (line == null) done = true; else { out.println("echo: " + line); if (line.trim().equals("bye")) done = true; // while incoming.close(); catch (Exception e) { System.err.println(e); // main // class 11 Gestione di connessioni multiple while (true) { Socket incoming = s.accept(); Thread t = new ThreadedEchoHandler(incoming); t.start(); class ThreadedEchoHandler extends Thread { public void run () { BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getoutputstream(), true); String line; while ((line=in.readline())!= null) { process line incoming.close(); catch (Exception e) { handle exception 12

Trasmissione di oggetti serializzati (1) public class Studente implements Serializable { private int matricola; private String nome, cognome, corsodilaurea; public Studente (int matricola, String nome, String cognome, String corsodilaurea) { this.matricola = matricola; this.nome = nome; this.cognome = cognome; this.corsodilaurea = corsodilaurea; public int getmatricola () { return matricola; public String getnome () { return nome; public String getcognome () { return cognome; public String getcorsodilaurea () { return corsodilaurea; 13 Trasmissione di oggetti serializzati (2) public class SendObject { public static void main (String args[]) { ServerSocket server = new ServerSocket (3575); Socket client = server.accept(); ObjectOutputStream output = new ObjectOutputStream (client.getoutputstream ()); output.writeobject("<welcome>"); Studente studente = new Studente (14520,"Leonardo","da Vinci","Ingegneria Informatica"); output.writeobject(studente); output.writeobject("<goodbye>"); client.close(); server.close(); catch (Exception e) { System.err.println (e); 14

Trasmissione di oggetti serializzati (3) public class ReceiveObject { public static void main (String args[]) { Socket socket = new Socket ("localhost",3575); ObjectInputStream input = new ObjectInputStream (socket.getinputstream ()); String beginmessage = (String)input.readObject(); System.out.println (beginmessage); Studente studente = (Studente)input.readObject(); System.out.print (studente.getmatricola()+" - "); System.out.print (studente.getnome()+" "+studente.getcognome()+" - "); System.out.print (studente.getcorsodilaurea()+"\n"); String endmessage = (String)input.readObject(); System.out.println (endmessage); socket.close(); catch (Exception e) { System.err.println (e); 15 HttpWelcome (1) import java.util.*; public class HttpWelcome { private static int port = 80; private static String HtmlWelcomeMessage () { return "<html>\n"+ " <head>\n"+ " <title>unical - Facoltà di Ingegneria</title>\n"+ " </head>\n"+ " <body>\n"+ " <h2 align=\"center\">\n"+ " <font color=\"#0000ff\">benvenuti al Corso di"+ " Reti di Calcolatori</font>\n"+ " </h2>\n"+ " </body>\n"+ "</html>"; 16

HttpWelcome (2) public static void main (String args[]) { ServerSocket server = new ServerSocket(port); System.out.println("HTTP server running on port: "+port); while (true) { Socket client = server.accept(); BufferedReader in = new BufferedReader (new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter (new OutputStreamWriter(client.getOutputStream())); String request = in.readline(); System.out.println("Request: "+request); StringTokenizer st = new StringTokenizer(request); 17 HttpWelcome (3) if ((st.counttokens()>=2) && st.nexttoken().equals("get")) { String message = HtmlWelcomeMessage(); // Start of response headers out.println ("HTTP/1.0 200 OK"); out.println ("Content-Length: "+message.length()); out.println ("Content-Type: text/html"); out.println (); // End of response headers out.println (message); else { out.println("400 Bad Request"); out.flush(); client.close(); catch (Exception e) { System.err.println(e); // main // class 18

HttpServer (1) import java.util.*; public class HttpServer { private static final int port = 3575; public static void main (String args[]) throws IOException { ServerSocket server = new ServerSocket(port); System.out.println("HTTP server running on port: "+port); while(true) { Socket client = server.accept(); ThreadedServer cc = new ThreadedServer(client); catch(ioexception e) { System.err.println(e); 19 HttpServer (2) class ThreadedServer extends Thread { private Socket client; private BufferedReader is; private DataOutputStream os; public ThreadedServer (Socket s) { client = s; is = new BufferedReader (new InputStreamReader(client.getInputStream())); os = new DataOutputStream (client.getoutputstream()); catch (IOException e) { client.close(); catch (IOException ex) { System.err.println(""+ex); return; this.start(); 20

HttpServer (3) public void run() { // get a request and parse it. String request = is.readline(); System.out.println("Request: "+request); StringTokenizer st = new StringTokenizer(request); if ((st.counttokens()>=2) && st.nexttoken().equals("get")) { if ((request = st.nexttoken()).startswith("/")) request = request.substring( 1 ); if (request.endswith("/") request.equals("")) request = request + "index.html"; // per impedire che si possa scrivere: http://hostname/../../../etc/passwd // oppure: http://hostname//etc/passwd if ((request.indexof("..")!= -1) (request.startswith("/"))) { os.writebytes("403 Forbidden. "+ "You do not have enough privileges to read: "+request+"\r\n"); else { File f = new File(request); reply (os, f); 21 HttpServer (4) else { os.writebytes("400 Bad Request\r\n"); client.close(); catch (IOException e1) { System.err.println("I/O error: "+e1); catch (Exception e2) { System.err.println("Exception: "+e2); public static void reply (DataOutputStream out, File f) throws Exception { DataInputStream in = new DataInputStream(new FileInputStream(f)); int len = (int)f.length(); byte buf[] = new byte[len]; in.readfully(buf); out.writebytes("http/1.0 200 OK\r\n"); out.writebytes("content-length: "+buf.length+"\r\n"); out.writebytes("content-type: text/html\r\n\r\n"); out.write(buf); out.flush(); in.close(); catch (FileNotFoundException e) { out.writebytes("404 Not Found\r\n"); // class ThreadedServer 22

MailSender (1) public class MailSender { private static PrintWriter out; private static BufferedReader in; public static void main(string[] args) { BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); System.out.print ("SMTP server: "); String smtp = console.readline (); System.out.print ("From: "); String from = console.readline (); System.out.print ("To: "); String to = console.readline (); System.out.println ("Message: "); String message = ""; boolean flag = true; do { String line = console.readline (); if (line.length() > 0 && Character.getType(line.charAt(0)) == Character.CONTROL) flag = false; else message += line+"\n"; while (flag); 23 MailSender (2) Socket s = new Socket(smtp, 25); out = new PrintWriter(s.getOutputStream()); in = new BufferedReader(new InputStreamReader(s.getInputStream())); String hostname = InetAddress.getLocalHost().getHostName(); send (null); send ("HELO "+hostname); send ("MAIL FROM: "+from); send ("RCPT TO: "+to); send ("DATA"); out.println (message); send ("."); s.close (); catch (Exception e) { System.err.println (e); public static void send (String s) throws IOException { if (s!= null) { System.out.println(">> "+s); out.println(s); out.flush(); String line = in.readline(); if (line!= null) System.out.println("<< "+line+"\n"); // class 24