SlideShare a Scribd company logo
Java – Networking                              Page 1



                                 Java – Networking
                                       PROGRAMS
Program 1: Write a program that obtains the IP address of a site.

/* Program to find the IP address of a website */
// Mukesh N Tekwani

import java.io.*;
import java.net.*;

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

              System.out.print("Enter a website name: ");
              String site = br.readLine();

              try
              {
                     InetAddress ip = InetAddress.getByName(site);
                     System.out.print("The IP address is: " + ip);
              }
              catch(UnknownHostException e)
              {
                   System.out.println("WebSite not found");
              }
       }
}

/* Output:

C:JavaPrgs>java AddressDemo
Enter a website name: www.google.com
The IP address is: www.google.com/74.125.235.50
*/

Modification:
Modify the above program so that it takes the website name (e.g., http://www.yahoo.com) from the
command line. If the website address is not given at command line, use the default address
http://www.google.com.




mukeshtekwani@hotmail.com [Mobile:9869 488 356]                        Prof. Mukesh N. Tekwani
2                                         Java - Networking


Program 2: Write a program that connects to the home page of www.yahoo.com (read
from a URL).

//Program to connect to the home page of www.yahoo.com
// Mukesh N Tekwani

import java.net.*;
import java.io.*;

public class URLReader
{
     public static void main(String[] args) throws Exception
     {
          URL myurl = new URL("http://www.yahoo.com/");
          BufferedReader in = new BufferedReader(new
                             InputStreamReader(myurl.openStream()));
          String inputLine;

              while ((inputLine = in.readLine()) != null)
                   System.out.println(inputLine);
              in.close();
       }
}

Output:
When this program is run, it displays the complete HTML code of the web page.

Possible Error: If we give site address simply as www.yahoo.com, we get MalformedURLException.
The protocol http must also be given in the complete URL.

Modification:
Modify the above program so that it takes the website name (e.g., http://www.yahoo.com) from the
command line. If the website address is not given at command line, use the default address
http://www.google.com.




Prof. Mukesh N Tekwani                     mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                        Page 3


Program 3: Write a program that parses a URL address into its components.

//Program to parse a URL address into its components
// Mukesh N Tekwani

import java.net.*;
import java.io.*;

public class ParseAddress
{
     public static void main (String[] args)
     {
          if (args.length !=1)
          {
                System.out.println ("Error: missing url argument");
                System.out.println ("Usage: java ParseURL <url>");
                System.exit (0);
          }
          try
          {
                URL siteurl = new URL (args[0]);
                System.out.println ("Protocol = " +
                                     siteurl.getProtocol ());
                System.out.println("Host = " + siteurl.getHost ());
                System.out.println("File name= " + siteurl.getFile());
                System.out.println("Port = " + siteurl.getPort ());
                System.out.println("Target = " + siteurl.getRef ());
          }
          catch (MalformedURLException e)
          {
                System.out.println ("Bad URL = " + args[0]);
          }
     } // main
} // class ParseAddress

Output:
C:JavaPrgs>java ParseAddress http://www.microsoft.com
Protocol = http
Host = www.microsoft.com
File name =
Port = -1
Target = null




mukeshtekwani@hotmail.com [Mobile:9869 488 356]                 Prof. Mukesh N. Tekwani
4                                   Java - Networking


Program 4: Write a program to translate an IP address into host name or a host name to
an IP address.
// Translate IP address to hostname or vice-versa
// Mukesh N Tekwani
import java.net.*;
import java.io.*;

class TranslateAddress
{
     public static void main (String args[])
     {
          if (args.length != 1)
          {
                System.out.println ("Error! No IP or host name
                                     address");
                System.out.println ("Usage: java TranslateAddress
                                     java.sun.com");
                System.out.println ("    or java TranslateAddress
                                     209.249.116.143");
                System.exit (0);
          }
          try
          {
                // When the argument passed is a host name(e.g.
                // sun.com), the corresponding IP address is returned.
                // If passed an IP address, then only the IP address
                // is returned.

                    InetAddress ipadd = InetAddress.getByName (args[0]);
                    System.out.println ("Address " + args[0] + " = " +
                                    ipadd);

                    // To get the hostname when passed an IP address use
                    // getHostName (), which will return the host name
                    // string.
                    System.out.println ("Name of " + args[0] + " = " +
                                    ipadd.getHostName ());
            }
            catch    (UnknownHostException e)
            {
                    System.out.println ("Unable to translate the
                                         address.");
           }
      } // main
   } // class TranslateAddress
/* Output:
C:JavaPrgs>java TranslateAddress 130.237.34.133
Address 130.237.34.133 = /130.237.34.133
Name of 130.237.34.133 = ns1.particle.kth.se
*/




Prof. Mukesh N Tekwani               mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                               Page 5


Program 5: Write a program to print all the addresses of www.microsoft.com

// Get all IP addresses by name of site
// Mukesh N Tekwani

import java.net.*;

public class AllAddressesOfMicrosoft
{
       public static void main (String[] args)
     {
           try
           {
                InetAddress[] ipadd =
                      InetAddress.getAllByName("www.microsoft.com");
                for (int i = 0; i < ipadd.length; i++)
                {
                      System.out.println(ipadd[i]);
                }
           }
           catch (UnknownHostException ex)
           {
               System.out.println("Could not find www.microsoft.com");
           }
     }
}

/*Output:

C:JavaPrgs>java AllAddressesOfMicrosoft

www.microsoft.com/64.4.31.252
www.microsoft.com/65.55.12.249
www.microsoft.com/65.55.21.250
www.microsoft.com/207.46.131.43
www.microsoft.com/207.46.170.10
www.microsoft.com/207.46.170.123
*/

Modification: Write a program that prints the Internet Address of the local host if we do not
specify any command-line parameters or all Internet addresses of another host if we specify the host
name on the command line.




mukeshtekwani@hotmail.com [Mobile:9869 488 356]                           Prof. Mukesh N. Tekwani
6                                    Java - Networking


Program 6: Write a program to obtain the IP address of the local machine.

// Find the IP address of the local machine
// Mukesh n Tekwani

import java.net.*;
public class MyOwnAddress
{
       public static void main (String[] args)
     {
           try
           {
                InetAddress me = InetAddress.getLocalHost();
                String myadd = me.getHostAddress();
                System.out.println("My address is " + myadd);
           }
           catch (UnknownHostException e)
           {
                System.out.println("I'm sorry. I don't know my own
                           address; really lost!!!.");
           }
     }
}

/* Output:
C:JavaPrgs>java MyOwnAddress
My address is 192.168.1.7
*/




Prof. Mukesh N Tekwani                mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                          Page 7


Program 7: Write a program that accepts an IP address and finds the host name.

// Given the IP address, find the host name
// Mukesh N Tekwani

import java.net.*;
public class ReverseTest
{
     public static void main (String[] args)
     {
          try
          {
                InetAddress ia =
                     InetAddress.getByName("65.55.21.250");

                   System.out.println(ia.getHostName());
                   System.out.println(ia);
             }
             catch (Exception e)
             {
                  System.out.println(e);
             }
      }
}

/* Output:
C:JavaPrgs>java ReverseTest
wwwco1vip.microsoft.com
wwwco1vip.microsoft.com/65.55.21.250
*/




mukeshtekwani@hotmail.com [Mobile:9869 488 356]                  Prof. Mukesh N. Tekwani
8                                   Java - Networking


Program 8: Write a program to download a file from the Internet and either copy it as a
file on the local machine or display it on the screen.
// Program-download a file & copy it as a file or display it on screen
// Mukesh N Tekwani
import java.io.*;
import java.net.*;
public class DownLoadFile
{
     public static void main(String args[])
     {
          InputStream in = null;
          OutputStream out = null;
            try
            {
                   if ((args.length != 1) && (args.length != 2))
                        throw new IllegalArgumentException("Wrong no. of
                             arguments");

                   URL siteurl = new URL(args[0]);
                   in = siteurl.openStream();
                   if(args.length == 2)
                        out = new FileOutputStream(args[1]);
                   else
                        out = System.out; //display on client machine
                   byte [] buffer = new byte[4096];
                   int bytes_read;
                   while((bytes_read = in.read(buffer)) != -1)
                   out.write(buffer, 0, bytes_read);
            }
            catch (Exception ex)
            {
                 System.out.println(ex);
            }
            finally
            {
                 try
                 {
                      in.close(); out.close();
                 }
                 catch (Exception ae)
                 {
                      System.out.println(ae);
                 }
            }
     }
}
/* Output:
C:JavaPrgs>java DownLoadFile http://www.yahoo.com test.txt
*/


Prof. Mukesh N Tekwani               mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                           Page 9


                       CLIENT-SERVER PROGRAMS (Using Sockets)

              Client                                           Server
 Create TCP Socket                             Create TCP Socket
 Socket       cs     = new                     ServerSocket        ss           =        new
 Socket(hostname, port);                       ServerSocket(port);

 Client initiates the communication            Wait for client connection
 by reading the user input                     Socket        listen_socket                 =
 Str                              =            ss.accept();
 userinput.readLine();                         Then reads the client on listen_socket.

 Then sends it to server                       Server listens client
 Server_out.writeBytes(str                     client_str                                  =
 + ‘n’);                                      client_input.readLine();

 Client listens to server using client         Server sends reply to client
 socket


 Close client socket




mukeshtekwani@hotmail.com [Mobile:9869 488 356]                     Prof. Mukesh N. Tekwani
10                                   Java - Networking


 Program 9: Write a client/server program in which a client sends a single string to the
 server. The server just displays this string. (Echo)

 Server Program:
 //Server Program
 //Works with file Client1
 //Mukesh N Tekwani

 import java.io.*;
 import java.net.*;

 class Server1
 {
      public static void main(String args[]) throws Exception
      {
            //create server socket
            ServerSocket ss = new ServerSocket(4444);

             while (true)
             {
                  Socket listen_socket = ss.accept();
                  BufferedReader client_input = new BufferedReader(new
                        InputStreamReader(listen_socket.getInputStream()));

                    String client_str;      //to store string rcvd from client

                    client_str = client_input.readLine();
                    System.out.println(client_str);
             }
       }
 }

 Client Program:
 //Client Program
 //Works with file Server1
 //Mukesh N Tekwani

 import java.io.*;
 import java.net.*;

 class Client1
 {
      public static void main(String args[]) throws Exception
      {
            //create client socket
            Socket cs = new Socket("localhost", 4444);

             BufferedReader user_input = new BufferedReader(new
                        InputStreamReader(System.in));

             DataOutputStream server_out = new
                        DataOutputStream(cs.getOutputStream());



 Prof. Mukesh N Tekwani               mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                         Page 11


             String str;

             str = user_input.readLine();

             server_out.writeBytes(str + 'n');

             cs.close();
      }
}

Program : Write a TCP/IP client / server program that sends a string in lowercase to the
server which sends the equivalent uppercase string back to the client.

Server Program:
//The server code Server.java:

import java.io.*;
import java.net.*;

public class ServerLower
{

      // the socket used by the server
      private ServerSocket serverSocket;
      ServerLower(int port)            // server constructor
      {
           /* create socket server and wait for connection requests */
           try
           {
                 serverSocket = new ServerSocket(port);
                 System.out.println("Server waiting for client on port " +
                            serverSocket.getLocalPort());

                   while(true)
                   {
                        Socket socket = serverSocket.accept();
                        System.out.println("New client asked for a
                              connection");
                        TcpThread t = new TcpThread(socket);
                        System.out.println("Starting a thread for a new
                              Client");
                        t.start();
                   }
             }
             catch (IOException e)
             {
                  System.out.println("Exception on new ServerSocket:" + e);
             }
      }

      public static void main(String[] arg)
      {
           new ServerLower(4444);
      }

mukeshtekwani@hotmail.com [Mobile:9869 488 356]                  Prof. Mukesh N. Tekwani
12                                 Java - Networking



       /** One instance of this thread will run for each client */
       class TcpThread extends Thread
       {
            Socket socket;        // the socket where to listen/talk
            ObjectInputStream Sinput;
            ObjectOutputStream Soutput;

             TcpThread(Socket socket)
             {
                  this.socket = socket;
             }

             public void run()
             {
                  /* Creating both Data Streams */
                  System.out.println("Thread trying to create Object
                                   Input/Output Streams");
                  try
                  {
                        // create output first
                        Soutput = new
                             ObjectOutputStream(socket.getOutputStream());
                        Soutput.flush();
                        Sinput = new
                             ObjectInputStream(socket.getInputStream());
                  }
                  catch (IOException e)
                  {
                        System.out.println("Exception creating new
                                   Input/output Streams: " + e);
                        return;
                  }
                  System.out.println("Thread waiting for a String from the
                             Client");
                  // read a String (which is an object)
                  try
                  {
                        String str = (String) Sinput.readObject();

                          str = str.toUpperCase(); //convert lower 2 uppercase

                          Soutput.writeObject(str);
                          Soutput.flush();
                   }
                   catch (IOException e)
                   {
                        System.out.println("Exception reading/writing
                              Streams: " + e);
                        return;
                   }
                   catch (ClassNotFoundException e1)
                   {    //nothing needed here
                   }
                   finally

 Prof. Mukesh N Tekwani             mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                  Page 13


                   {
                         try
                         {
                                Soutput.close();
                                Sinput.close();
                         }
                         catch (Exception e2)
                         {    //nothing needed here

                         }
                   }
            }
      }
}


Client Program:
//The client code that sends a string in lowercase to the server

import java.net.*;
import java.io.*;

public class ClientLower
{
     ObjectInputStream Sinput; // to read the socker
     ObjectOutputStream Soutput; // towrite on the socket
     Socket socket;

      // Constructor connection receiving a socket number
      ClientLower(int port)
      {
           try
           {
                 socket = new Socket("localhost", port);
           }
           catch(Exception e)
           {
                 System.out.println("Error connectiong to server:" + e);
                 return;
           }
           System.out.println("Connection accepted " +
                 socket.getInetAddress() + ":" + socket.getPort());

            /* Creating both Data Streams */
            try
            {
                 Sinput = new ObjectInputStream(socket.getInputStream());
                 Soutput = new
                       ObjectOutputStream(socket.getOutputStream());
            }
            catch (IOException e)
            {
                 System.out.println("Exception creating I/O Streams:"+ e);
                 return;
            }

mukeshtekwani@hotmail.com [Mobile:9869 488 356]           Prof. Mukesh N. Tekwani
14                                           Java - Networking



                String test = "aBcDeFgHiJkLmNoPqRsTuVwXyZ";

                // send the string to the server
                System.out.println("Client sending "" + test + "" to
                     server");
                try
                {
                     Soutput.writeObject(test);
                     Soutput.flush();
                }
                catch(IOException e)
                {
                     System.out.println("Error writting to the socket: " + e);
                     return;
                }
                // read back the answer from the server
                String response;
                try
                {
                     response = (String) Sinput.readObject();
                     System.out.println("Read back from server: " + response);
                }
                catch(Exception e)
                {
                     System.out.println("Problem reading back from server: " + e);
                }

                try
                {
                        Sinput.close();
                        Soutput.close();
                }
                catch(Exception e)
                {    // nothing needed here
                }
        }

        public static void main(String[] arg)
        {
             new ClientLower(4444);
        }
 }

 Modifications:
 1. Modify the Server program in this example so that it is not multithreaded.
 2. Modify the client program so that the input string is entered by the user from keyboard when program
    runs, instead of storing it within the program.




 Prof. Mukesh N Tekwani                        mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                       Page 15


Program 17:
Write a client-server socket application in which
(i)   A client reads a character from the keyboard and sends the character out of its
      socket to the server.
(ii)  The server reads the character from its connection socket
(iii) The server finds the ASCII value of the character.
(iv) The server sends the ASCII value out of its connection socket to the client.
(v)   The client reads the result from its socket and prints the result on its standard
      output device.

Server Program:
//Server sends the ASCII code of a character to client
//Mukesh N Tekwani
import java.io.*;
import java.net.*;
class ServerASCII
{
     public static void main(String args[]) throws Exception
     {
           String clientstr, serverstr;

              ServerSocket ss = new ServerSocket(4444);

              while(true)
              {
                   Socket cs = ss.accept();
                   System.out.println("Connected to client...");

                        BufferedReader inFromClient = new BufferedReader(new
                                   InputStreamReader(cs.getInputStream()));

                        DataOutputStream outToClient = new
                                   DataOutputStream(cs.getOutputStream());

                        clientstr = inFromClient.readLine();

                        //read the first character from input
                        char c = clientstr.charAt(0);

                        /* Find the ASCII code; note the type casting */
                        serverstr = "The ASCII code of " + clientstr + " is        " +
                                   (int)c + 'n';

                        outToClient.writeBytes(serverstr);
              }
       }
}
Output at Client end:
C:JavaPrgs>java ClientASCII
Enter a character
B
From server: The ASCII code of B is          66

mukeshtekwani@hotmail.com [Mobile:9869 488 356]                 Prof. Mukesh N. Tekwani
16                                              Java - Networking


                                         PORTS AND SOCKETS

 Understanding Ports
 Generally speaking, a computer has a single physical connection to the network. All data destined for a
 particular computer arrives through that connection. However, the data may be intended for different
 applications running on the computer. So how does the computer know to which application to forward the
 data? Through the use of ports.

 Data transmitted over the Internet is accompanied by addressing information that identifies the computer and
 the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver
 data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use
 to deliver the data to the right application.

 In connection-based communication such as TCP, a server application binds a socket to a specific port
 number. This has the effect of registering the server with the system to receive all data destined for that port.
 A client can then rendezvous with the server at the server's port, as illustrated here:




 Definition: The TCP and UDP protocols use ports to map incoming data to a particular process
 running on a computer.

 In datagram-based communication such as UDP, the datagram packet contains the port number of its
 destination and UDP routes the packet to the appropriate application, as illustrated in this figure:




 Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers
 ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP
 and other system services. These ports are called well-known ports. Your applications should not attempt to
 bind to them.


 Understanding Sockets

 In client-server applications, the server provides some service, such as processing database queries or sending
 out current stock prices. The client uses the service provided by the server, either displaying database query
 results to the user or making stock purchase recommendations to an investor. The communication that occurs
 between the client and the server must be reliable. That is, no data can be dropped and it must arrive on the
 client side in the same order in which the server sent it.

 Prof. Mukesh N Tekwani                          mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                                   Page 17


TCP provides a reliable, point-to-point communication channel that client-server applications on the Internet
use to communicate with each other. To communicate over TCP, a client program and a server program
establish a connection to one another. Each program binds a socket to its end of the connection. To
communicate, the client and the server each reads from and writes to the socket bound to the connection.

What Is a Socket?
A socket is one end-point of a two-way communication link between two programs running on the network.
Socket classes are used to represent the connection between a client program and a server program. The
java.net package provides two classes--Socket and ServerSocket--that implement the client side of the
connection and the server side of the connection, respectively.




mukeshtekwani@hotmail.com [Mobile:9869 488 356]                                 Prof. Mukesh N. Tekwani

More Related Content

What's hot (20)

Networking in java
Networking in javaNetworking in java
Networking in java
shravan kumar upadhayay
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
ashok hirpara
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
Mousmi Pawar
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
UC San Diego
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
sureshkarthick37
 
Java sockets
Java socketsJava sockets
Java sockets
Stephen Pradeep
 
Java- Datagram Socket class & Datagram Packet class
Java- Datagram Socket class  & Datagram Packet classJava- Datagram Socket class  & Datagram Packet class
Java- Datagram Socket class & Datagram Packet class
Ruchi Maurya
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
rajshreemuthiah
 
Java Programming - 07 java networking
Java Programming - 07 java networkingJava Programming - 07 java networking
Java Programming - 07 java networking
Danairat Thanabodithammachari
 
A Short Java Socket Tutorial
A Short Java Socket TutorialA Short Java Socket Tutorial
A Short Java Socket Tutorial
Guo Albert
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
Tushar B Kute
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
Nitish Nagar
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
elliando dias
 
Java Networking
Java NetworkingJava Networking
Java Networking
68SachinYadavSYCS
 
A.java
A.javaA.java
A.java
JahnaviBhagat
 
Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
Amandeep Kaur
 
Multiplayer Java Game
Multiplayer Java GameMultiplayer Java Game
Multiplayer Java Game
karim baidar
 
Socket programming
Socket programmingSocket programming
Socket programming
chandramouligunnemeda
 
Sockets
SocketsSockets
Sockets
sivindia
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
ashok hirpara
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
Mousmi Pawar
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
UC San Diego
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
sureshkarthick37
 
Java- Datagram Socket class & Datagram Packet class
Java- Datagram Socket class  & Datagram Packet classJava- Datagram Socket class  & Datagram Packet class
Java- Datagram Socket class & Datagram Packet class
Ruchi Maurya
 
A Short Java Socket Tutorial
A Short Java Socket TutorialA Short Java Socket Tutorial
A Short Java Socket Tutorial
Guo Albert
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
Nitish Nagar
 
Multiplayer Java Game
Multiplayer Java GameMultiplayer Java Game
Multiplayer Java Game
karim baidar
 

Similar to Java networking programs socket based (20)

Unit8 java
Unit8 javaUnit8 java
Unit8 java
mrecedu
 
CHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptxCHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptx
DhrumilSheth3
 
Advanced Java Programming: Introduction and Overview of Java Networking 1. In...
Advanced Java Programming: Introduction and Overview of Java Networking 1. In...Advanced Java Programming: Introduction and Overview of Java Networking 1. In...
Advanced Java Programming: Introduction and Overview of Java Networking 1. In...
KuntalVasoya
 
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
vasishtharishi07
 
Network programming1
Network programming1Network programming1
Network programming1
Soham Sengupta
 
Module 1 networking basics-2
Module 1   networking basics-2Module 1   networking basics-2
Module 1 networking basics-2
Ankit Dubey
 
List of computer network programs
List of computer network programsList of computer network programs
List of computer network programs
mamta4817
 
Lecture6
Lecture6Lecture6
Lecture6
vantinhkhuc
 
Presentation_1367055761045
Presentation_1367055761045Presentation_1367055761045
Presentation_1367055761045
Alexander Nevidimov
 
Presentation_1367055457962
Presentation_1367055457962Presentation_1367055457962
Presentation_1367055457962
Alexander Nevidimov
 
Session 6
Session 6Session 6
Session 6
Parthipan Parthi
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
Sasi Kala
 
Chapter 2 : Inet Address & Data Stream
Chapter 2 : Inet Address & Data StreamChapter 2 : Inet Address & Data Stream
Chapter 2 : Inet Address & Data Stream
Ministry of Higher Education
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
suraj pandey
 
Networking
NetworkingNetworking
Networking
Jafar Nesargi
 
Networking slide
Networking slideNetworking slide
Networking slide
Asaduzzaman Kanok
 
Java networking
Java networkingJava networking
Java networking
ssuser3a47cb
 
Networking Basics1ofjavaprogramming.pptx.pdf
Networking Basics1ofjavaprogramming.pptx.pdfNetworking Basics1ofjavaprogramming.pptx.pdf
Networking Basics1ofjavaprogramming.pptx.pdf
omkarthombare4989
 
Java networking
Java networkingJava networking
Java networking
Arati Gadgil
 
Unit-6-java basic for java programing.pptx
Unit-6-java basic for java programing.pptxUnit-6-java basic for java programing.pptx
Unit-6-java basic for java programing.pptx
086ChintanPatel1
 
Unit8 java
Unit8 javaUnit8 java
Unit8 java
mrecedu
 
CHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptxCHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptx
DhrumilSheth3
 
Advanced Java Programming: Introduction and Overview of Java Networking 1. In...
Advanced Java Programming: Introduction and Overview of Java Networking 1. In...Advanced Java Programming: Introduction and Overview of Java Networking 1. In...
Advanced Java Programming: Introduction and Overview of Java Networking 1. In...
KuntalVasoya
 
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
vasishtharishi07
 
Module 1 networking basics-2
Module 1   networking basics-2Module 1   networking basics-2
Module 1 networking basics-2
Ankit Dubey
 
List of computer network programs
List of computer network programsList of computer network programs
List of computer network programs
mamta4817
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
Sasi Kala
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
suraj pandey
 
Networking Basics1ofjavaprogramming.pptx.pdf
Networking Basics1ofjavaprogramming.pptx.pdfNetworking Basics1ofjavaprogramming.pptx.pdf
Networking Basics1ofjavaprogramming.pptx.pdf
omkarthombare4989
 
Unit-6-java basic for java programing.pptx
Unit-6-java basic for java programing.pptxUnit-6-java basic for java programing.pptx
Unit-6-java basic for java programing.pptx
086ChintanPatel1
 
Ad

More from Mukesh Tekwani (20)

The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
Mukesh Tekwani
 
Circular motion
Circular motionCircular motion
Circular motion
Mukesh Tekwani
 
Gravitation
GravitationGravitation
Gravitation
Mukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
Mukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
Mukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
Mukesh Tekwani
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
Mukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
Mukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
Mukesh Tekwani
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
Mukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
Mukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
Mukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Mukesh Tekwani
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
Mukesh Tekwani
 
XML
XMLXML
XML
Mukesh Tekwani
 
Social media
Social mediaSocial media
Social media
Mukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
Mukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
Mukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
Mukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
Mukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
Mukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
Mukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
Mukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
Mukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Mukesh Tekwani
 
Ad

Recently uploaded (20)

Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke WarnerPublishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...
Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...
Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...
Himalayan Group of Professional Institutions (HGPI)
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
LDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student NewsLDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student News
LDM & Mia eStudios
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation SamplerLDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil DisobediencePaper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptxSPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Revista digital preescolar en transformación
Revista digital preescolar en transformaciónRevista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdfABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 EmployeesOverview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo SlidesOverview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POSHow to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke WarnerPublishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
LDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student NewsLDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student News
LDM & Mia eStudios
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation SamplerLDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil DisobediencePaper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptxSPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Revista digital preescolar en transformación
Revista digital preescolar en transformaciónRevista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdfABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 EmployeesOverview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo SlidesOverview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POSHow to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 

Java networking programs socket based

  • 1. Java – Networking Page 1 Java – Networking PROGRAMS Program 1: Write a program that obtains the IP address of a site. /* Program to find the IP address of a website */ // Mukesh N Tekwani import java.io.*; import java.net.*; class AddressDemo { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a website name: "); String site = br.readLine(); try { InetAddress ip = InetAddress.getByName(site); System.out.print("The IP address is: " + ip); } catch(UnknownHostException e) { System.out.println("WebSite not found"); } } } /* Output: C:JavaPrgs>java AddressDemo Enter a website name: www.google.com The IP address is: www.google.com/74.125.235.50 */ Modification: Modify the above program so that it takes the website name (e.g., http://www.yahoo.com) from the command line. If the website address is not given at command line, use the default address http://www.google.com. [email protected] [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 2. 2 Java - Networking Program 2: Write a program that connects to the home page of www.yahoo.com (read from a URL). //Program to connect to the home page of www.yahoo.com // Mukesh N Tekwani import java.net.*; import java.io.*; public class URLReader { public static void main(String[] args) throws Exception { URL myurl = new URL("http://www.yahoo.com/"); BufferedReader in = new BufferedReader(new InputStreamReader(myurl.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } } Output: When this program is run, it displays the complete HTML code of the web page. Possible Error: If we give site address simply as www.yahoo.com, we get MalformedURLException. The protocol http must also be given in the complete URL. Modification: Modify the above program so that it takes the website name (e.g., http://www.yahoo.com) from the command line. If the website address is not given at command line, use the default address http://www.google.com. Prof. Mukesh N Tekwani [email protected] [Mobile:9869 488 356]
  • 3. Java - Networking Page 3 Program 3: Write a program that parses a URL address into its components. //Program to parse a URL address into its components // Mukesh N Tekwani import java.net.*; import java.io.*; public class ParseAddress { public static void main (String[] args) { if (args.length !=1) { System.out.println ("Error: missing url argument"); System.out.println ("Usage: java ParseURL <url>"); System.exit (0); } try { URL siteurl = new URL (args[0]); System.out.println ("Protocol = " + siteurl.getProtocol ()); System.out.println("Host = " + siteurl.getHost ()); System.out.println("File name= " + siteurl.getFile()); System.out.println("Port = " + siteurl.getPort ()); System.out.println("Target = " + siteurl.getRef ()); } catch (MalformedURLException e) { System.out.println ("Bad URL = " + args[0]); } } // main } // class ParseAddress Output: C:JavaPrgs>java ParseAddress http://www.microsoft.com Protocol = http Host = www.microsoft.com File name = Port = -1 Target = null [email protected] [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 4. 4 Java - Networking Program 4: Write a program to translate an IP address into host name or a host name to an IP address. // Translate IP address to hostname or vice-versa // Mukesh N Tekwani import java.net.*; import java.io.*; class TranslateAddress { public static void main (String args[]) { if (args.length != 1) { System.out.println ("Error! No IP or host name address"); System.out.println ("Usage: java TranslateAddress java.sun.com"); System.out.println (" or java TranslateAddress 209.249.116.143"); System.exit (0); } try { // When the argument passed is a host name(e.g. // sun.com), the corresponding IP address is returned. // If passed an IP address, then only the IP address // is returned. InetAddress ipadd = InetAddress.getByName (args[0]); System.out.println ("Address " + args[0] + " = " + ipadd); // To get the hostname when passed an IP address use // getHostName (), which will return the host name // string. System.out.println ("Name of " + args[0] + " = " + ipadd.getHostName ()); } catch (UnknownHostException e) { System.out.println ("Unable to translate the address."); } } // main } // class TranslateAddress /* Output: C:JavaPrgs>java TranslateAddress 130.237.34.133 Address 130.237.34.133 = /130.237.34.133 Name of 130.237.34.133 = ns1.particle.kth.se */ Prof. Mukesh N Tekwani [email protected] [Mobile:9869 488 356]
  • 5. Java - Networking Page 5 Program 5: Write a program to print all the addresses of www.microsoft.com // Get all IP addresses by name of site // Mukesh N Tekwani import java.net.*; public class AllAddressesOfMicrosoft { public static void main (String[] args) { try { InetAddress[] ipadd = InetAddress.getAllByName("www.microsoft.com"); for (int i = 0; i < ipadd.length; i++) { System.out.println(ipadd[i]); } } catch (UnknownHostException ex) { System.out.println("Could not find www.microsoft.com"); } } } /*Output: C:JavaPrgs>java AllAddressesOfMicrosoft www.microsoft.com/64.4.31.252 www.microsoft.com/65.55.12.249 www.microsoft.com/65.55.21.250 www.microsoft.com/207.46.131.43 www.microsoft.com/207.46.170.10 www.microsoft.com/207.46.170.123 */ Modification: Write a program that prints the Internet Address of the local host if we do not specify any command-line parameters or all Internet addresses of another host if we specify the host name on the command line. [email protected] [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 6. 6 Java - Networking Program 6: Write a program to obtain the IP address of the local machine. // Find the IP address of the local machine // Mukesh n Tekwani import java.net.*; public class MyOwnAddress { public static void main (String[] args) { try { InetAddress me = InetAddress.getLocalHost(); String myadd = me.getHostAddress(); System.out.println("My address is " + myadd); } catch (UnknownHostException e) { System.out.println("I'm sorry. I don't know my own address; really lost!!!."); } } } /* Output: C:JavaPrgs>java MyOwnAddress My address is 192.168.1.7 */ Prof. Mukesh N Tekwani [email protected] [Mobile:9869 488 356]
  • 7. Java - Networking Page 7 Program 7: Write a program that accepts an IP address and finds the host name. // Given the IP address, find the host name // Mukesh N Tekwani import java.net.*; public class ReverseTest { public static void main (String[] args) { try { InetAddress ia = InetAddress.getByName("65.55.21.250"); System.out.println(ia.getHostName()); System.out.println(ia); } catch (Exception e) { System.out.println(e); } } } /* Output: C:JavaPrgs>java ReverseTest wwwco1vip.microsoft.com wwwco1vip.microsoft.com/65.55.21.250 */ [email protected] [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 8. 8 Java - Networking Program 8: Write a program to download a file from the Internet and either copy it as a file on the local machine or display it on the screen. // Program-download a file & copy it as a file or display it on screen // Mukesh N Tekwani import java.io.*; import java.net.*; public class DownLoadFile { public static void main(String args[]) { InputStream in = null; OutputStream out = null; try { if ((args.length != 1) && (args.length != 2)) throw new IllegalArgumentException("Wrong no. of arguments"); URL siteurl = new URL(args[0]); in = siteurl.openStream(); if(args.length == 2) out = new FileOutputStream(args[1]); else out = System.out; //display on client machine byte [] buffer = new byte[4096]; int bytes_read; while((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); } catch (Exception ex) { System.out.println(ex); } finally { try { in.close(); out.close(); } catch (Exception ae) { System.out.println(ae); } } } } /* Output: C:JavaPrgs>java DownLoadFile http://www.yahoo.com test.txt */ Prof. Mukesh N Tekwani [email protected] [Mobile:9869 488 356]
  • 9. Java - Networking Page 9 CLIENT-SERVER PROGRAMS (Using Sockets) Client Server Create TCP Socket Create TCP Socket Socket cs = new ServerSocket ss = new Socket(hostname, port); ServerSocket(port); Client initiates the communication Wait for client connection by reading the user input Socket listen_socket = Str = ss.accept(); userinput.readLine(); Then reads the client on listen_socket. Then sends it to server Server listens client Server_out.writeBytes(str client_str = + ‘n’); client_input.readLine(); Client listens to server using client Server sends reply to client socket Close client socket [email protected] [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 10. 10 Java - Networking Program 9: Write a client/server program in which a client sends a single string to the server. The server just displays this string. (Echo) Server Program: //Server Program //Works with file Client1 //Mukesh N Tekwani import java.io.*; import java.net.*; class Server1 { public static void main(String args[]) throws Exception { //create server socket ServerSocket ss = new ServerSocket(4444); while (true) { Socket listen_socket = ss.accept(); BufferedReader client_input = new BufferedReader(new InputStreamReader(listen_socket.getInputStream())); String client_str; //to store string rcvd from client client_str = client_input.readLine(); System.out.println(client_str); } } } Client Program: //Client Program //Works with file Server1 //Mukesh N Tekwani import java.io.*; import java.net.*; class Client1 { public static void main(String args[]) throws Exception { //create client socket Socket cs = new Socket("localhost", 4444); BufferedReader user_input = new BufferedReader(new InputStreamReader(System.in)); DataOutputStream server_out = new DataOutputStream(cs.getOutputStream()); Prof. Mukesh N Tekwani [email protected] [Mobile:9869 488 356]
  • 11. Java - Networking Page 11 String str; str = user_input.readLine(); server_out.writeBytes(str + 'n'); cs.close(); } } Program : Write a TCP/IP client / server program that sends a string in lowercase to the server which sends the equivalent uppercase string back to the client. Server Program: //The server code Server.java: import java.io.*; import java.net.*; public class ServerLower { // the socket used by the server private ServerSocket serverSocket; ServerLower(int port) // server constructor { /* create socket server and wait for connection requests */ try { serverSocket = new ServerSocket(port); System.out.println("Server waiting for client on port " + serverSocket.getLocalPort()); while(true) { Socket socket = serverSocket.accept(); System.out.println("New client asked for a connection"); TcpThread t = new TcpThread(socket); System.out.println("Starting a thread for a new Client"); t.start(); } } catch (IOException e) { System.out.println("Exception on new ServerSocket:" + e); } } public static void main(String[] arg) { new ServerLower(4444); } [email protected] [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 12. 12 Java - Networking /** One instance of this thread will run for each client */ class TcpThread extends Thread { Socket socket; // the socket where to listen/talk ObjectInputStream Sinput; ObjectOutputStream Soutput; TcpThread(Socket socket) { this.socket = socket; } public void run() { /* Creating both Data Streams */ System.out.println("Thread trying to create Object Input/Output Streams"); try { // create output first Soutput = new ObjectOutputStream(socket.getOutputStream()); Soutput.flush(); Sinput = new ObjectInputStream(socket.getInputStream()); } catch (IOException e) { System.out.println("Exception creating new Input/output Streams: " + e); return; } System.out.println("Thread waiting for a String from the Client"); // read a String (which is an object) try { String str = (String) Sinput.readObject(); str = str.toUpperCase(); //convert lower 2 uppercase Soutput.writeObject(str); Soutput.flush(); } catch (IOException e) { System.out.println("Exception reading/writing Streams: " + e); return; } catch (ClassNotFoundException e1) { //nothing needed here } finally Prof. Mukesh N Tekwani [email protected] [Mobile:9869 488 356]
  • 13. Java - Networking Page 13 { try { Soutput.close(); Sinput.close(); } catch (Exception e2) { //nothing needed here } } } } } Client Program: //The client code that sends a string in lowercase to the server import java.net.*; import java.io.*; public class ClientLower { ObjectInputStream Sinput; // to read the socker ObjectOutputStream Soutput; // towrite on the socket Socket socket; // Constructor connection receiving a socket number ClientLower(int port) { try { socket = new Socket("localhost", port); } catch(Exception e) { System.out.println("Error connectiong to server:" + e); return; } System.out.println("Connection accepted " + socket.getInetAddress() + ":" + socket.getPort()); /* Creating both Data Streams */ try { Sinput = new ObjectInputStream(socket.getInputStream()); Soutput = new ObjectOutputStream(socket.getOutputStream()); } catch (IOException e) { System.out.println("Exception creating I/O Streams:"+ e); return; } [email protected] [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 14. 14 Java - Networking String test = "aBcDeFgHiJkLmNoPqRsTuVwXyZ"; // send the string to the server System.out.println("Client sending "" + test + "" to server"); try { Soutput.writeObject(test); Soutput.flush(); } catch(IOException e) { System.out.println("Error writting to the socket: " + e); return; } // read back the answer from the server String response; try { response = (String) Sinput.readObject(); System.out.println("Read back from server: " + response); } catch(Exception e) { System.out.println("Problem reading back from server: " + e); } try { Sinput.close(); Soutput.close(); } catch(Exception e) { // nothing needed here } } public static void main(String[] arg) { new ClientLower(4444); } } Modifications: 1. Modify the Server program in this example so that it is not multithreaded. 2. Modify the client program so that the input string is entered by the user from keyboard when program runs, instead of storing it within the program. Prof. Mukesh N Tekwani [email protected] [Mobile:9869 488 356]
  • 15. Java - Networking Page 15 Program 17: Write a client-server socket application in which (i) A client reads a character from the keyboard and sends the character out of its socket to the server. (ii) The server reads the character from its connection socket (iii) The server finds the ASCII value of the character. (iv) The server sends the ASCII value out of its connection socket to the client. (v) The client reads the result from its socket and prints the result on its standard output device. Server Program: //Server sends the ASCII code of a character to client //Mukesh N Tekwani import java.io.*; import java.net.*; class ServerASCII { public static void main(String args[]) throws Exception { String clientstr, serverstr; ServerSocket ss = new ServerSocket(4444); while(true) { Socket cs = ss.accept(); System.out.println("Connected to client..."); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(cs.getInputStream())); DataOutputStream outToClient = new DataOutputStream(cs.getOutputStream()); clientstr = inFromClient.readLine(); //read the first character from input char c = clientstr.charAt(0); /* Find the ASCII code; note the type casting */ serverstr = "The ASCII code of " + clientstr + " is " + (int)c + 'n'; outToClient.writeBytes(serverstr); } } } Output at Client end: C:JavaPrgs>java ClientASCII Enter a character B From server: The ASCII code of B is 66 [email protected] [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 16. 16 Java - Networking PORTS AND SOCKETS Understanding Ports Generally speaking, a computer has a single physical connection to the network. All data destined for a particular computer arrives through that connection. However, the data may be intended for different applications running on the computer. So how does the computer know to which application to forward the data? Through the use of ports. Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right application. In connection-based communication such as TCP, a server application binds a socket to a specific port number. This has the effect of registering the server with the system to receive all data destined for that port. A client can then rendezvous with the server at the server's port, as illustrated here: Definition: The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer. In datagram-based communication such as UDP, the datagram packet contains the port number of its destination and UDP routes the packet to the appropriate application, as illustrated in this figure: Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP and other system services. These ports are called well-known ports. Your applications should not attempt to bind to them. Understanding Sockets In client-server applications, the server provides some service, such as processing database queries or sending out current stock prices. The client uses the service provided by the server, either displaying database query results to the user or making stock purchase recommendations to an investor. The communication that occurs between the client and the server must be reliable. That is, no data can be dropped and it must arrive on the client side in the same order in which the server sent it. Prof. Mukesh N Tekwani [email protected] [Mobile:9869 488 356]
  • 17. Java - Networking Page 17 TCP provides a reliable, point-to-point communication channel that client-server applications on the Internet use to communicate with each other. To communicate over TCP, a client program and a server program establish a connection to one another. Each program binds a socket to its end of the connection. To communicate, the client and the server each reads from and writes to the socket bound to the connection. What Is a Socket? A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes--Socket and ServerSocket--that implement the client side of the connection and the server side of the connection, respectively. [email protected] [Mobile:9869 488 356] Prof. Mukesh N. Tekwani