SlideShare a Scribd company logo
JAVA UDP Sockets
JAVA - Internet Addresses
 java.net.InetAddress class

 You get an address by using static methods:
 Create InetAddress object representing the local machine
  InetAddress myAddress = InetAddress.getLocalHost();

 Create InetAddress object representing some remote machine
  InetAddress ad = InetAddress.getByName(hostname);
JAVA - Printing Internet Addresses

 You get information from an InetAddress
 by using methods:

 ad.getHostName();
 ad.getHostAddress();
JAVA - The InetAddress Class
 Handles Internet addresses both as host names and as IP addresses
 Static Method getByName returns the IP address of a specified host name as
 an InetAddress object
 Methods for address/name conversion:
  public static InetAddress getByName(String host) throws
      UnknownHostException
  public static InetAddress[] getAllByName(String host) throws
      UnknownHostException
  public static InetAddress getLocalHost() throws UnknownHostException

  public boolean isMulticastAddress()
  public String getHostName()
  public byte[] getAddress()
  public String getHostAddress()
  public int hashCode()
  public boolean equals(Object obj)
  public String toString()
import java.net.*;
import java.io.*;

public class IPFinder
{
          public static void main(String[] args) throws IOException
          {
                    String host;
                    BufferedReader input =
                      new BufferedReader(
                              new InputStreamReader(System.in));

                   System.out.print("nnEnter host name: ");
                   host = input.readLine();
                   try
                   {
                             InetAddress address = InetAddress.getByName(host);
                   System.out.println("IP address: " + address.toString());
                   }
          catch (UnknownHostException e)
          {
                             System.out.println("Could not find " + host);
                   }
          }
}
Retrieving the address of the local machine
import java.net.*;

public class MyLocalIPAddress
{
   public static void main(String[] args)
    {
        try
        {
             InetAddress address = InetAddress.getLocalHost();
             System.out.println (address);
        }
        catch (UnknownHostException e)
        {
             System.out.println("Could not find local address!");
        }
     }
}
The UDP classes
2 classes:
    java.net.DatagramSocket class
        is a connection to a port that does the sending and receiving. A
        DatagramSocket can send to multiple, different addresses.The address
        to which data goes is stored in the packet, not in the socket.
        public DatagramSocket() throws SocketException
        public DatagramSocket(int port) throws SocketException
        public DatagramSocket(int port, InetAddress laddr) throws
        SocketException
    java.net.DatagramPacket class
         is a wrapper for an array of bytes from which data will be sent or into
        which data will be received. It also contains the address and port to
        which the packet will be sent.
        public DatagramPacket(byte[] data, int length)
        public DatagramPacket(byte[] data, int length, InetAddress host, int
        port)
Datagram Sockets
SERVER:
1. Create a DatagramSocket object
   DatagramSocket dgramSocket =
                new DatagramSocket(1234);
2. Create a buffer for incoming datagrams
   byte[] buffer = new byte[256];
3. Create a DatagramPacket object for the incoming datagram
   DatagramPacket inPacket =
                new DatagramPacket(buffer, buffer.length);
4. Accept an incoming datagram
   dgramSocket.receive(inPacket)
Datagram Sockets
SERVER:
5. Accept the sender’s address and port from the packet
   InetAddress clientAddress = inPacket.getAddress();
   int clientPort = inPacket.getPort();
6. Retrieve the data from the buffer
   string message =
     new String(inPacket.getData(), 0, inPacket.getLength());
7. Create the response datagram
   DatagramPacket outPacket =
                new DatagramPacket(
                                response.getBytes(), response.length(),
                                clientAddress, clientPort);
8. Send the response datagram
   dgramSocket.send(outPacket)
9. Close the DatagramSocket: dgram.close();
Datagram Sockets
CLIENT:
1.  Create a DatagramSocket object
    DatagramSocket dgramSocket = new DatagramSocket;
2.  Create the outgoing datagram
    DatagramPacket outPacket = new DatagramPacket(
                                           message.getBytes(),
                                           message.length(),
                                           host, port);
3.  Send the datagram message
    dgramSocket.send(outPacket)
4.  Create a buffer for incoming datagrams
     byte[] buffer = new byte[256];
Datagram Sockets
CLIENT:
5.  Create a DatagramPacket object for the incoming datagram
    DatagramPacket inPacket =
               new DatagramPacket(buffer, buffer.length);
6.  Accept an incoming datagram
    dgramSocket.receive(inPacket)
7.  Retrieve the data from the buffer
    string response = new String(inPacket.getData(), 0,
                                     inPacket.getLength());
8.  Close the DatagramSocket:
        dgram.close();
Sending UDP packets

 When you receive a packet, the IP and
 port number of the sender are set in the
 DatagramPacket.

 You can use the same packet to reply, by
 overwriting the data, using the method:
   packet.setData(newbuffer);
Non-blocking I/O receiving UDP
packets
 You can set a time-out in milliseconds to
 determine how long a read operation
 blocks, before throwing an exception.
   socket.setSoTimeout(duration);
 If the duration given in milliseconds is
 exceeded, an exception is thrown:
   java.io.InterruptedException
References
 Cisco Networking Academy Program (CCNA), Cisco Press.

 CSCI-5273 : Computer Networks, Dirk Grunwald, University of Colorado-Boulder

 CSCI-4220: Network Programming, Dave Hollinger, Rensselaer Polytechnic Institute.

 TCP/IP Illustrated, Volume 1, Stevens.

 Java Network Programming and Distributed Computing, Reilly & Reilly.

 Computer Networks: A Systems Approach, Peterson & Davie.

 http://www.firewall.cx

 http://www.javasoft.com

More Related Content

PDF
ikh331-06-distributed-programming
PPTX
Socket.io v.0.8.3
PDF
Java- Datagram Socket class & Datagram Packet class
PPT
Socket Programming
PPT
C# Application program UNIT III
PPTX
Java networking
PPTX
#5 (Remote Method Invocation)
PPT
Network
ikh331-06-distributed-programming
Socket.io v.0.8.3
Java- Datagram Socket class & Datagram Packet class
Socket Programming
C# Application program UNIT III
Java networking
#5 (Remote Method Invocation)
Network

What's hot (19)

PPTX
Java весна 2013 лекция 2
ODP
Jersey Guice AOP
PDF
DCN Practical
PPTX
Jafka guide
PDF
Writing Domain-Specific Languages for BeepBeep
PDF
Core java pract_sem iii
PPT
iOS Development with Blocks
PPTX
ADO.NETObjects
DOC
PPTX
分散式系統
PDF
Active Software Documentation using Soul and IntensiVE
PDF
The Ring programming language version 1.5.2 book - Part 39 of 181
PDF
In-depth caching in Varnish - GOG Varnish Meetup, march 2019
PPTX
Php sql-android
PPTX
Hadoop Puzzlers
PDF
The Ring programming language version 1.5.3 book - Part 85 of 184
PDF
concurrency with GPars
ODP
GPars (Groovy Parallel Systems)
Java весна 2013 лекция 2
Jersey Guice AOP
DCN Practical
Jafka guide
Writing Domain-Specific Languages for BeepBeep
Core java pract_sem iii
iOS Development with Blocks
ADO.NETObjects
分散式系統
Active Software Documentation using Soul and IntensiVE
The Ring programming language version 1.5.2 book - Part 39 of 181
In-depth caching in Varnish - GOG Varnish Meetup, march 2019
Php sql-android
Hadoop Puzzlers
The Ring programming language version 1.5.3 book - Part 85 of 184
concurrency with GPars
GPars (Groovy Parallel Systems)
Ad

Viewers also liked (17)

PPTX
Presentación1
PPT
журнал клёпа
PDF
Ppt -optimal_healthusa
DOC
Exercise pada pasien stemi
PPTX
Presentation constructing an information panel
PPTX
Optimal health products
PDF
48 nguyen tac chu chot cua quyen luc (robert greene & joost elffers)
PDF
Mutual Funds - 2013 Gold Monitor Award Winners
PPTX
Exam preparation tips
PPTX
Shokovy
PPTX
Tradicii
PPT
Hokkaido.pm.casual #03 slide
PPTX
Barzykin Alexandre
PPTX
Resultater fra omnichannel surveyen
PPTX
Annuity and Life Insurance Product Update - Q1 2015
PPTX
Новости недвижимости майами май 2016
Presentación1
журнал клёпа
Ppt -optimal_healthusa
Exercise pada pasien stemi
Presentation constructing an information panel
Optimal health products
48 nguyen tac chu chot cua quyen luc (robert greene & joost elffers)
Mutual Funds - 2013 Gold Monitor Award Winners
Exam preparation tips
Shokovy
Tradicii
Hokkaido.pm.casual #03 slide
Barzykin Alexandre
Resultater fra omnichannel surveyen
Annuity and Life Insurance Product Update - Q1 2015
Новости недвижимости майами май 2016
Ad

Similar to Lecture6 (20)

PPTX
Advance Java-Network Programming
PPT
Udp Programming
PPT
Udp Programming
PPTX
PDF
java sockets
PPT
Chapter 4 slides
PPTX
Javanetworkingbasicssocketsoverview
PPTX
Java networking basics & sockets overview
PPT
UDP-Dept Businesss Computing university .ppt
PPT
Ppt of socket
PPT
Md13 networking
PPT
Network programming in Java
PPTX
Network programming in java - PPT
DOCX
Lab manual cn-2012-13
PDF
28 networking
PPT
Socket Programming it-slideshares.blogspot.com
PPTX
Networking in Java
PPT
TCP IP
PPTX
Socket & Server Socket
PPT
Java Socket Programming
Advance Java-Network Programming
Udp Programming
Udp Programming
java sockets
Chapter 4 slides
Javanetworkingbasicssocketsoverview
Java networking basics & sockets overview
UDP-Dept Businesss Computing university .ppt
Ppt of socket
Md13 networking
Network programming in Java
Network programming in java - PPT
Lab manual cn-2012-13
28 networking
Socket Programming it-slideshares.blogspot.com
Networking in Java
TCP IP
Socket & Server Socket
Java Socket Programming

More from vantinhkhuc (20)

PDF
Url programming
PDF
Servlets intro
PDF
Servlet sessions
PDF
Security overview
PDF
PDF
PDF
Lecture17
PDF
Lecture11 b
PDF
Lecture10
PDF
Lecture9
PDF
PDF
Jsf intro
PDF
Jsp examples
PDF
PDF
Ejb examples
PDF
PDF
PDF
Ejb intro
PPT
Chc6b0c6a1ng 12
PPT
Url programming
Servlets intro
Servlet sessions
Security overview
Lecture17
Lecture11 b
Lecture10
Lecture9
Jsf intro
Jsp examples
Ejb examples
Ejb intro
Chc6b0c6a1ng 12

Lecture6

  • 2. JAVA - Internet Addresses java.net.InetAddress class You get an address by using static methods: Create InetAddress object representing the local machine InetAddress myAddress = InetAddress.getLocalHost(); Create InetAddress object representing some remote machine InetAddress ad = InetAddress.getByName(hostname);
  • 3. JAVA - Printing Internet Addresses You get information from an InetAddress by using methods: ad.getHostName(); ad.getHostAddress();
  • 4. JAVA - The InetAddress Class Handles Internet addresses both as host names and as IP addresses Static Method getByName returns the IP address of a specified host name as an InetAddress object Methods for address/name conversion: public static InetAddress getByName(String host) throws UnknownHostException public static InetAddress[] getAllByName(String host) throws UnknownHostException public static InetAddress getLocalHost() throws UnknownHostException public boolean isMulticastAddress() public String getHostName() public byte[] getAddress() public String getHostAddress() public int hashCode() public boolean equals(Object obj) public String toString()
  • 5. import java.net.*; import java.io.*; public class IPFinder { public static void main(String[] args) throws IOException { String host; BufferedReader input = new BufferedReader( new InputStreamReader(System.in)); System.out.print("nnEnter host name: "); host = input.readLine(); try { InetAddress address = InetAddress.getByName(host); System.out.println("IP address: " + address.toString()); } catch (UnknownHostException e) { System.out.println("Could not find " + host); } } }
  • 6. Retrieving the address of the local machine import java.net.*; public class MyLocalIPAddress { public static void main(String[] args) { try { InetAddress address = InetAddress.getLocalHost(); System.out.println (address); } catch (UnknownHostException e) { System.out.println("Could not find local address!"); } } }
  • 7. The UDP classes 2 classes: java.net.DatagramSocket class is a connection to a port that does the sending and receiving. A DatagramSocket can send to multiple, different addresses.The address to which data goes is stored in the packet, not in the socket. public DatagramSocket() throws SocketException public DatagramSocket(int port) throws SocketException public DatagramSocket(int port, InetAddress laddr) throws SocketException java.net.DatagramPacket class is a wrapper for an array of bytes from which data will be sent or into which data will be received. It also contains the address and port to which the packet will be sent. public DatagramPacket(byte[] data, int length) public DatagramPacket(byte[] data, int length, InetAddress host, int port)
  • 8. Datagram Sockets SERVER: 1. Create a DatagramSocket object DatagramSocket dgramSocket = new DatagramSocket(1234); 2. Create a buffer for incoming datagrams byte[] buffer = new byte[256]; 3. Create a DatagramPacket object for the incoming datagram DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length); 4. Accept an incoming datagram dgramSocket.receive(inPacket)
  • 9. Datagram Sockets SERVER: 5. Accept the sender’s address and port from the packet InetAddress clientAddress = inPacket.getAddress(); int clientPort = inPacket.getPort(); 6. Retrieve the data from the buffer string message = new String(inPacket.getData(), 0, inPacket.getLength()); 7. Create the response datagram DatagramPacket outPacket = new DatagramPacket( response.getBytes(), response.length(), clientAddress, clientPort); 8. Send the response datagram dgramSocket.send(outPacket) 9. Close the DatagramSocket: dgram.close();
  • 10. Datagram Sockets CLIENT: 1. Create a DatagramSocket object DatagramSocket dgramSocket = new DatagramSocket; 2. Create the outgoing datagram DatagramPacket outPacket = new DatagramPacket( message.getBytes(), message.length(), host, port); 3. Send the datagram message dgramSocket.send(outPacket) 4. Create a buffer for incoming datagrams byte[] buffer = new byte[256];
  • 11. Datagram Sockets CLIENT: 5. Create a DatagramPacket object for the incoming datagram DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length); 6. Accept an incoming datagram dgramSocket.receive(inPacket) 7. Retrieve the data from the buffer string response = new String(inPacket.getData(), 0, inPacket.getLength()); 8. Close the DatagramSocket: dgram.close();
  • 12. Sending UDP packets When you receive a packet, the IP and port number of the sender are set in the DatagramPacket. You can use the same packet to reply, by overwriting the data, using the method: packet.setData(newbuffer);
  • 13. Non-blocking I/O receiving UDP packets You can set a time-out in milliseconds to determine how long a read operation blocks, before throwing an exception. socket.setSoTimeout(duration); If the duration given in milliseconds is exceeded, an exception is thrown: java.io.InterruptedException
  • 14. References Cisco Networking Academy Program (CCNA), Cisco Press. CSCI-5273 : Computer Networks, Dirk Grunwald, University of Colorado-Boulder CSCI-4220: Network Programming, Dave Hollinger, Rensselaer Polytechnic Institute. TCP/IP Illustrated, Volume 1, Stevens. Java Network Programming and Distributed Computing, Reilly & Reilly. Computer Networks: A Systems Approach, Peterson & Davie. http://www.firewall.cx http://www.javasoft.com