InetAddress Class - PowerPoint PPT Presentation

1 / 50
About This Presentation
Title:

InetAddress Class

Description:

There may be several levels of directories separated by forward slashes. ... Java Programs use Client Sockets in the following fashion: ... – PowerPoint PPT presentation

Number of Views:364
Avg rating:3.0/5.0
Slides: 51
Provided by: prasa90
Category:

less

Transcript and Presenter's Notes

Title: InetAddress Class


1
InetAddress Class
2
Demonstrating InetAddress Class
3
Network File Access
4
URL Class- Example Constructor Calls
5
Methods in URL Class
6
Demonstration of URL Class Methods
7
Java Sockets
NETWORK COMMUNICATIONS USING SOCKETS Socket
- abstraction used to facilitate TCP/IP network
communications Formally a socket consists of an
IP address and a port number. Java 1.1 supports
most of the Berkley Sockets standard. (This has
its roots in the BSD UNIX specification) PORT
NUMBERS
8
COMMON WELL-KNOWN PORTS
  • Service Port Function
  • HTTP 80 WebHTTPS 443 Web (secure)FTP 20,21
    File transferFTPS 989,990 File transfer
    (secure)Telnet 23 Remote loginSSH 22 Remote
    login (secure)DNS 53 Host naming
  • SMTP 25 Internet mailPOP3 110 Client
    accessIMAP 143 Client access
  • NNTP 119 Usenet newsgroupsNNTPS 563 Usenet
    newsgroups (secure)IRC 194 Chat
  • NTP 123 Network time
  • SNMP 161,162 Network managementCMIP 163,164
    Network management
  • Kerberos 88 AuthenticationNetBIOS 137-139
    DOS/Windows naming
  • http//www.iss.net/security_center/advice/Exploits
    /Ports/default.htm

9
Sockets for Clients
  • Sockets are higher level abstraction of hosts
    native networking software
  • Sockets allow a programmer to treat a network
    connection as to just another stream
  • Onto which bytes can be written
  • From which bytes can be read
  • Sockets shield the programmer with lower level
    details of network , such as error detection,
    packet sizes, packet retransmission etc.

10
Socket Basics
  • A Socket is a connection between two hosts. It
    can perform seven basic operations
  • Connect to a remote machine
  • Send Data
  • Receive Data
  • Close a Connection
  • Javas Socket Class, which is used by both client
    and servers has methods corresponding to these
    four operations.

11
Socket Basics
  • The remaining three operations needed by servers,
    which wait for clients to connect to them are
    implemented by ServerSocket Class.
  • Bind to a port
  • Listen for incoming data
  • Accept connections from remote machines on the
    bound port.

12
Java Programs /Client Sockets
  • Java Programs use Client Sockets in the following
    fashion
  • The program creates a new socket with a
    constructor
  • The Socket attempts to connect to a remote host.
  • Once the connection is established, the local and
    remote hosts get input and output streams from
    the socket and use those streams to send and data
    to each other
  • When transmission of data is complete, one or
    both sides close the connection.

13
The Socket Class
  • The java.net.Socket Class is javas fundamental
    class for performing client-side TCP operations.
    Methods of this class can be classified into
  • The Constructors
  • Getting Information about the Socket
  • Closing the Socket
  • Setting Socket Options
  • Class of Service

14
The Constructors
  • Each Socket Constructor lets you specify
  • The Host and Port you want to connect to.
  • Hosts maybe specified as an InetAddress or a
    String.
  • Ports are always specified as int values from 0
    to 65535.
  • Two of the constructors lets you specify the
    local address and the local port from which data
    will be sent.

15
Constructor 1
  • public Socket(String host, int port) throws
    UnknownHostException, I0Exception
  • try
  • Socket s new Socket(www.uwstout.edu,
    80)
  • //send receive data
  • catch (UnknownHostException ex)
  • System.err.println(ex)
  • break
  • catch (IOException ex)
  • System.err.println(ex)

It creates a TCP Socket to the specified port on
the specified host.
16
Low-Port Scanner using Constructor 1
Find out which of the first 1,024 ports seem to
be hosting TCP servers on a specified host
  • import java.net.
  • import java.io.
  • public class LowPortScanner
  • public static void main(String args)
  • String host "localhost"
  • if (args.length gt 0)
  • host args0
  • for (int i 1 i lt 1024 i)
  • try
  • Socket s new Socket(host, i)
  • System.out.println(
  • "There is a server on port " i " of
    " host)
  • catch (UnknownHostException e)
  • System.err.println(e)
  • break
  • catch (IOException e)

17
What can this program do?
  • Helps you understand what your system is doing
  • You can find possible entrance points for
    attackers.
  • Someone is running a server on some port that is
    consuming bandwidth.
  • Dont use this program to probe a machine that
    you dont own.

18
Constructor 2
  • public Socket(InetAddress host, int port) throws
    I0Exception
  • try
  • InetAddress theAddress InetAddress.getByN
    ame(www.uwstout.edu)
  • Socket theSocket new Socket(theAddress,
    80)
  • //send receive data
  • catch (UnknownHostException ex)
  • System.err.println(ex)
  • catch (IOException ex)
  • System.err.println(ex)
  • It creates a TCP Socket to the specified port on
    the specified host.
  • It differs from previous constructor by using a
    InetAddress object to specify the host name
    tather than host name

19
High-Port Scanner using Constructor 2
  • import java.net.
  • import java.io.
  • public class HighPortScanner
  • public static void main(String args)
  • String host "localhost"
  • if (args.length gt 0)
  • host args0
  • try
  • InetAddress theAddress InetAddress.getByNa
    me(host)
  • for (int i 1024 i lt 65536 i)
  • try
  • Socket theSocket new
    Socket(theAddress, i)
  • System.out.println("There is a server
    on port " i " of " host)
  • catch (IOException ex)
  • // must not be a server on this port
  • // end for

Find out which of the ports at or above 1,024
seem to be hosting TCP servers.
20
Constructor 3
  • public Socket(String host, int port, InetAddress
    interface, int localport) throws I0Exception,
    UnknownHostException
  • It creates a TCP Socket to the specified port on
    the specified host.
  • It connects to the host and port specified in the
    first two arguments.
  • It connects from the local network interface and
    port specified by the last two arguments.
  • If 0 is passed for the localPort argument, Java
    chooses a random available port between 1,024 to
    65535.

21
Constructor 4
  • public Socket(InetAddress host, int port,
    InetAddress interface, int localport) throws
    I0Exception, UnknownHostException
  • It creates a TCP Socket to the specified port on
    the specified host.
  • It connects to the host and port specified in the
    first two arguments.
  • It connects from the local network interface and
    port specified by the last two arguments.
  • If 0 is passed for the localPort argument, Java
    chooses a random available port between 1,024 to
    65535.
  • Identical to previous one except that host to
    connect to is passed as an InetAddress, not a
    String

22
Getting Information About a Socket
  • Getting Address of Remote Host
  • Getting Port Information to which the Socket
    is connected to on the remote host.
  • Getting Address of Local Host
  • Getting Port Information of local host from
    which the Socket is connected.
  • To read data from the socket into the program
  • To write data into the socket from your
    application

23
Getting Address of Remote Host
  • public InetAddress getInetAddress( )
  • try
  • Socket theSocket new Socket(java.sun.com
    , 80)
  • InetAddress host theSocket.getInetAddress(
    )
  • System.out.println(Connected to remote host
    host)
  • //end try
  • catch (UnknownHostException ex)
  • System.err.println(ex)
  • catch (IOException ex)
  • System.err.println(ex)

24
Port Information on Remote Host
  • public int getPort( )
  • try
  • Socket theSocket new Socket(java.sun.com
    , 80)
  • int port theSocket.getPort( )
  • System.out.println(Connected to remote port
    port)
  • //end try
  • catch (UnknownHostException ex)
  • System.err.println(ex)
  • catch (IOException ex)
  • System.err.println(ex)

25
Port Information of Local Host
  • public int getLocalPort( )
  • try
  • Socket theSocket new Socket(java.sun.com
    , 80)
  • int localPort theSocket.getLocalPort( )
  • System.out.println(Connected from local
    port localPort)
  • //end try
  • catch (UnknownHostException ex)
  • System.err.println(ex)
  • catch (IOException ex)
  • System.err.println(ex)

26
Getting Address of Local Host
  • public InetAddress getLocalAddress( )
  • try
  • Socket theSocket new Socket(hostname,
    80)
  • InetAddress localAddress theSocket.getLocalA
    ddress( )
  • System.out.println(Connected from local
    Address localAddress)
  • //end try
  • catch (UnknownHostException ex)
  • System.err.println(ex)
  • catch (IOException ex)
  • System.err.println(ex)

27
Get a Sockets Information
  • import java.net.
  • import java.io.
  • public class SocketInfo
  • public static void main(String args)
  • for (int i 0 i lt args.length i)
  • try
  • Socket theSocket new Socket(argsi,
    80)
  • System.out.println("Connected to "
    theSocket.getInetAddress()
  • " on port " theSocket.getPort() "
    from port "
  • theSocket.getLocalPort() " of "
  • theSocket.getLocalAddress())
  • // end try
  • catch (UnknownHostException ex)
  • System.err.println("I can't find "
    argsi)
  • catch (SocketException ex)
  • Read a list of hostnames from the command lines.
  • Attempt to open a socket to each one.
  • Use the four methods to print the remote host,
    the remote part, the local host and the local port

28
Reading Data From Program
  • public InputStream getInputStream( ) throws
    IOException
  • getInputStream( ) returns an input stream that
    can read data from socket into the program.
  • Chain this InputStream to a filter stream or
    reader that offers more functionality
    DataInputStream or InputStreamReader.
  • Buffer the input by chaining it to a
    BufferedInputStream and/or a BufferedReader.

29
Writing Data into Socket
  • public OutputStream getOutputStream( ) throws
    IOException
  • Writer out
  • try
  • Socket http new Socket(www.uwstout.edu,80)
  • OutputStream raw http.getOutputStream()
  • OutputStream buffered new BufferedOutputStream(
    raw)
  • out new OutputStreamWriter(buffered,ASCII)
  • out.write(GET /HTTP 1.0 \r\n\r\n)
  • //read the server response
  • catch(Exception ex)
  • System.err.println(ex)
  • Finally
  • try
  • out.close()
  • catch(Exception ex
  • getOutputStream( ) returns a raw OutputStream for
    writing data from your application to the other
    end of socket.
  • Chain this OutputStream to a more convenient
    class DataOutputStream or OutputStreamWriter.
  • Also, if possible use buffers.

30
An Echo Client
  • import java.net.
  • import java.io.
  • public class EchoClient
  • public static void main(String args)
  • String hostname "localhost"
  • if (args.length gt 0)
  • hostname args0
  • PrintWriter out null
  • BufferedReader networkIn null
  • try
  • Socket theSocket new Socket(hostname, 7)
  • networkIn new BufferedReader(
  • new InputStreamReader(theSocket.getInputStr
    eam()))
  • BufferedReader userIn new BufferedReader(

31
An Echo Client
  • while (true)
  • String theLine userIn.readLine()
  • if (theLine.equals(".")) break
  • out.println(theLine)
  • out.flush()
  • System.out.println(networkIn.readLine())
  • // end try
  • catch (IOException ex)
  • System.err.println(ex)
  • finally
  • try
  • if (networkIn ! null) networkIn.close()
  • if (out ! null) out.close()
  • catch (IOException ex)

32
Closing the Socket
  • Socket closes automatically when
  • One of its two streams closes.
  • When the program ends
  • When its garbage collected
  • It is a bad practice to assume a system will
    close the sockets for you, especially for
    programs that might run for an indefinite period
    of time.
  • When you are through with a socket you should
    call its close() method to disconnect
  • public void close() throws IOException

33
Closing the Socket
  • Socket connection null
  • try
  • connection new Socket( www.java.com, 13)
  • // interact with the socket
  • //end try
  • catch(UnknownHostException ex)
  • System.err.println(ex)
  • finally
  • if(connection ! null) connection.close()
  • Once a Socket has been closed, its InetAddress,
    port number, local address, and local port number
    are still accessible through getNAME methods.
  • However, although you can still call
    getInputStream() and getOutputStream(),
    attempting to read data from the InputStream or
    write data to the OutputStream throws an
    IOException

34
Socket Status Methods
  • public boolean isClosed()
  • If the socket has never been connected in the
    first place, it returns false
  • public boolean isConnected()
  • It does not tell you if the socket is currently
    connected to a remote host.
  • It tells you if a socket has ever been connected
    to a remote host.
  • To tell if a socket is currently open, you need
    to check that
  • isConnected() returns TRUE
  • isClosed() returns FALSE

35
Sockets for Servers
  • Why Server Sockets?
  • Client Sockets by themselves are not enough
    unless they can talk to a server.
  • Socket discussed earlier is not sufficient for
    writing servers.
  • To create a Socket you need to know the Internet
    host you want to connect to
  • When you are writing a server
  • You do know who would contact you
  • When they would contact you.

36
ServerSocket Class
  • Java provides ServerSocket Class that represents
    server sockets.
  • A server socket runs on the server and listens
    for incoming TCP connections.
  • Each Server socket listens on a particular port
    on the server machine.
  • When a client on a remote host attempts to
    connect to that port
  • The server wakes up
  • Negotiates the connection between the client and
    the server.
  • Returns a regular Socket object representing the
    socket between the two hosts.

37
Server Socket Behavior Overview
  • Server sockets waits for connections, while
    client sockets initiate connections.
  • Once a ServerSocket has set up a connection
  • The server uses a regular Socket object to send
    data to the client
  • Data always travel over the regular socket.

38
Life cycle of a server program
  • A new ServerSocket is created on a particular
    port using a ServerSocket() constructor.
  • The ServerSocket listens for incoming connection
    attempts on that port using its accept() method.
    accept() blocks until a client attempts o make a
    connection, at which point accept() returns a
    Socket object connecting the client and Server

39
Life cycle of a server program
  • Depending on the type of server, either the
    Sockets getInputStream() method,
    getOutputStream() method, or both are called to
    get input and output streams that communicate
    with the client.
  • He server and the client interact according to an
    agreed-upon protocol until it is time to close
    the connection.
  • The server, the client , or both close the
    connection.
  • The server returns to step 2 and waits for the
    next connection.

40
The Constructors
  • public ServerSocket(int port) throws
    BindException, IOException
  • public ServerSocket(int port, int queueLength)
    throws BindException, IOException
  • public ServerSocket(int port, int queueLength,
    InetAddress bindAddress) throws IOException
  • public ServerSocket() throws IOException

41
Constructor 1
  • public ServerSocket(int port) throws
    BindException, IOException
  • Creates a Server Socket on the port specified by
    the argument
  • try
  • ServerSocket httpd new ServerSocket(80)
  • catch (IOException ex)
  • System.err.println(ex)
  • // end catch

42
Local Port Scanner
  • import java.net.
  • import java.io.
  • public class LocalPortScanner
  • public static void main(String args)
  • for (int port 1 port lt 65535 port)
  • try
  • // the next line will fail and drop into
    the catch block if
  • // there is already a server running on
    the port
  • ServerSocket server new
    ServerSocket(port)
  • catch (IOException ex)
  • System.out.println("There is a server on
    port " port ".")
  • // end catch
  • // end for

43
Constructor 2
  • public ServerSocket(int port, int queueLength)
    throws BindException, IOException
  • Creates a Server Socket on the port specified
    with a queue length of your choosing.
  • queueLength Length of queue for incoming
    connection requests
  • try
  • ServerSocket httpd new ServerSocket(5776,100)
  • catch (IOException ex)
  • System.err.println(ex)
  • // end catch

44
Constructor 3
  • public ServerSocket(int port, int queueLength,
    InetAddress bindAddress) throws BindException,
    IOException
  • Binds a Server Socket to the port specified with
    a specified queue length.
  • queueLength Length of queue for incoming
    connection requests
  • try
  • ServerSocket httpd new ServerSocket(5776,10,Ine
    tAddress.getByName(192.168.210.122)
  • catch (IOException ex)
  • System.err.println(ex)
  • // end catch

45
Constructor 4
  • public ServerSocket() throws IOException
  • It creates a ServerSocket object but does not
    actually bind to a port so it cannot initially
    accept connections.
  • It can be bound later using the bind() functions
  • public void bind(SocketAddress endpoint) throws
    IOException
  • public void bind(SocketAddress endpoint, int
    queueLength) throws IOException
  • ServerSocket ss new ServerSocket()
  • SocketAddress http new InetSocketAddress(80)
  • ss.bind(http)

46
Accepting and Closing Connections
  • public Socket accept() throws IOException
  • This method blocks it stops the flow of
    execution and waits until a client connects.
  • When a client does connect, the accept() method
    returns a Socket object.
  • You use the streams returned by this Sockets
    getInputStream() and getOutputStream() methods to
    communicate with the client

47
Example Code
  • ServerSocket server new ServerSocket(5776)
  • while(true)
  • Socket connection server.accept()
  • OutputStreamWriter out new OutputStreamWriter(c
    onnection.getOutputStream())
  • out.write(Youve connected to this server.
    Bye-Bye now.\r\n)
  • connection.close()

48
Closing the Socket
  • public void close() throws IOException
  • Close the server socket so that it frees up port
    for other programs to use it.
  • Closing ServerSocket is different than closing
    Socket
  • ServerSockets are automatically closed when a
    program dies.
  • public boolean isClosed()
  • public boolean isBound()
  • public static boolean isOpen(ServerSocket ss)
  • returns ss.isBound() ! ss.isClosed()

49
Other Methods
  • public InetAddress getInetAddress()
  • Returns the address being used by the server.
  • ServerSocket httpd new ServerSocket(80)
  • InetAddress ia httpd.getInetAddress()
  • public int getLocalPort()
  • Lets you find out what port you are listening on
  • public void setSoTimeOut(int timeout) throws
    SocketException
  • public int getSoTimeOut() throws IOException

50
Example illustrating get Methods
  • import java.net.
  • import java.io.
  • public class RandomPort
  • public static void main(String args)
  • try
  • ServerSocket server new ServerSocket(0)
  • System.out.println("This server runs on
    port "
  • server.getLocalPort())
  • catch (IOException ex)
  • System.err.println(ex)
Write a Comment
User Comments (0)
About PowerShow.com