· 9 years ago · Apr 24, 2017, 05:44 AM
1UNIT – 5
2CHAPTER – 18
3Remote Method Invocation
4RMI PACKAGES
5Java.rmi package
6ï¶ The java.rmi package contains the classes that are seen by clients (objects that invoke remote methods).
7ï¶ Below are the classes(methods), interface and exceptions available in this package
8• Remote Interface - The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine.
9• Naming Class - The Naming class provides methods for storing and obtaining references to remote objects in a remote object registry.
10o String[] list(String url) - Returns an array of the names bound in the registry.
11o lookup(String url) - Returns a reference, a stub, for the remote object associated with the specified name.
12o void bind(String url, Remote object) - Binds the specified name to a remote object.
13o void unbind(String url) - Destroys the binding for the specified name that is associated with a remote object.
14o void rebind(String url, Remote object) - Rebinds the specified name to a new remote object.
15• RMISecurityManager - Class allows applications to implement a security policy.
16• Remote Exceptions
17o AccessExceptionClient tried todo something that only local objects are allowed to do
18o AlreadyBoundException The URL is already bound to another object.
19o ConnectException The server refused the connection.
20o ConnectIOException An I/O error occurred while trying to make the connection between the local and the remote host.
21o MarshalException An I/O error occurred while attempting to marshal (serialize) arguments to a remote method. A corrupted I/O stream could cause this exception; making the remote method call again might be successful.
22o UnmarshalException An I/O error occurred while attempting to unmarshal (deserialize) the value returned by a remote method. A corrupted I/O stream could cause this exception; making the remote method call again might be successful.
23o NoSuchObjectException The object reference is invalid or obsolete. This might occur if the remote host becomes unreachable while the program is running, perhaps because of network congestion, system crash, or other malfunction.
24o NotBoundException The URL is not bound to an object. This might be thrown when you try to reference an object whose URL was rebound out from under it.
25o RemoteException The generic superclass for all exceptions having to do with remote methods.
26o ServerError Despite the name, this is indeed an exception, not an error. It indicates that the server threw an error while executing the remote method.
27o ServerException A RemoteException was thrown while the remote method was executing.
28o StubNotFoundException The stub for a class could not be found. The stub file may be in the wrong directory on the server, there could be a namespace collision between the class that the stub substitutes for and some other class, or the client could have requested the wrong URL.
29o UnexpectedException Something unforeseen happened.
30o UnknownHostException The host cannot be found.
31Java.rmi.registry package
32ï¶ A registry advertises the availability of the server’s remote objects.
33ï¶ Clients query the registry to find out what remote objects are available and to get remote references to those objects.
34Registry Interface
35• List() - to bind a name to a specific remote object
36• Lookup() - to find a specific remote object given its URL
37• Bind() - to bind a name to a specific remote object
38• Unbind() - to remove a name from the registry
39• Rebind() - to bind a name to a different remote object
40LocateRegistry Class
41• getRegistry() - returns aRegistryobject that can be used to get remote objects by name
42• createRegistry() -create a registry and start it listening on the specified port.
43
44Java.rmi.server Package
45ï¶ Used for building remote objects.
46ï¶ Used by objects whose methods will be invoked by clients.
47• The RemoteObject Class
48o getRef() - returns a remote reference to the class
49o toStub() - converts a given remote object into the equivalent stub object for use in the client virtual machine
50• The RemoteServer Class
51o Constructors
52ï‚§ RemoteServer( ), RemoteServer(RemoteRef r)
53
54o Getting information about the client
55ï‚§ getClientHost( ) - returns aStringthat contains the hostname of the client that invoked the currently running method.
56o Logging
57 getLog(), setLog(OutputStream out) – Read/write log
58• The UnicastRemoteObject Class
59o Constructors
60ï‚§ UnicastRemoteObject( )
61ï‚§ UnicastRemoteObject(int port)
62ï‚§ UnicastRemoteObject(int port, RMIClientSocketFactory csf,)
63o Clone() - creates a clone of the remote object.
64o RemoteStub exportObject(Remote r) throws RemoteException - to use the infrastructure that Uni-castRemoteObject provides for an object that can’t subclassUnicastRemoteObject.
65o Remote exportObject(Remote r, int port) - Exports the remote object to make it available to receive incoming calls using an anonymous port.
66o Remote exportObject(Remote r, int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) - Exports the remote object to make it available to receive incoming calls using the specified port.
67o unexportObject(Remote r, boolean force) - to stop a particular remote object from listening for invocations.
68• Exception
69o ExportException When trying to export a remote object on a port that’s already in use.
70o ServerNotActiveException An attempt was made to invoke a method in a remote object that wasn’t running.
71o ServerCloneException An attempt to clone a remote object on the server failed.
72o SocketSecurityException This subclass of ExportException is thrown when theSecurityManager prevents a remote object from being exported on the requested port.
73RMI IMPLEMENTATION
741. Write the program code for interface (Example: Add.java).
75import java.rmi.*;
76public interface Add extends Remote
77{
78 public int getSum() throws RemoteException;
79}
802. Write the program code for implementation (Example: AddImpl.java).
81import java.rmi.*;
82import java.rmi.server.UnicastRemoteObject;
83public class AddImpl extends UnicastRemoteObject implements Add
84{
85 public AddImpl() throws RemoteException
86 {
87 super();
88 }
89 public int getSum() throws RemoteException
90 {
91 System.out.println("Calculating the sum..");
92 int a=10; int b=15; int sum;
93 sum=a+b;
94 return sum;
95 }
96}
973. Write the program code for server (Example: AddServer.java).
98import java.net.*;
99import java.rmi.*;
100public class AddServer
101{
102 public static void main(String[] args)
103 {
104 try
105 {
106 AddImpl f = new AddImpl();
107 Naming.rebind("add", f);
108 System.out.println("Addition Server ready.");
109 }
110 catch (RemoteException rex)
111 {
112 System.out.println("Exception in AddImpl.main: " + rex);
113 }
114 catch (MalformedURLException ex)
115 {
116 System.out.println("MalformedURLException " + ex);
117 }
118 }
119}
1204. Write the program code for client (Example: AddClient.java).
121import java.rmi.*;
122import java.net.*;
123public class AddClient
124{
125 public static void main(String args[])
126 {
127 try
128 {
129 Object o = Naming.lookup("add");
130 Add calculator = (Add) o;
131 int f = calculator.getSum();
132 System.out.println("The sum is: "+f);
133 }
134 catch (NotBoundException ex)
135 {
136 System.err.println("Could not find the requested remote object
137 on the server");
138 }
139 catch (RemoteException ex)
140 {
141System.err.println("Could not find the requested remote object on the server");
142 }
143 catch (MalformedURLException ex)
144 {
145System.err.println("Could not find the requested remote object on the server");
146 }
147 }
148}
1495. Compile interface, implementation, server and client programs.
1506. Create the stub (Syntax: rmic AddImpl).
1517. Start RMI registry (Syntax: start rmiregistry).
1528. Run the server program.
1539. Run the client program.
154RMI IMPLEMENTATION (with database connectivity)
155Step 1: Create the database
156 Example: MS Access.
157• Open MS Access
158• Select BLANK DATABASE
159• Name the DB and Select path for storing the DB
160• Create a table and name it
161• Open the table design view – add attributes, select their datatype and configure their properties.
162Step 2: Connect database to ODBC driver
163• Open control panel – administrative tool – data source (ODBC)
164• In user DSN, click ADD - Select Microsoft Access Driver (mdb, accdb) – click FINISH
165• Enter a DATA SOURCE NAME
166• SELECT database to be connected using the select option and then choosing path of DB – click OK – click OK
167Step 3: Implement the JDBC program
168• Register the driver (say JDBC:ODBC driver)
169• Connect the driver to the URL of the data source using the DSN (data source name)
170• Create a statement
171• Write SQL query
172• Using EXECUTEUPDATE and the STATEMENT object, execute the query.
173• If necessary, return the results using the RESULTSET object.
174
175
176
177EXAMPLE : ADDITION OF 2 NOS WITH DB CONNECTIVITY
178
179AddDB.java
180import java.rmi.*;
181import java.sql.*;
182public interface AddDB extends Remote
183{
184 public int getSum() throws RemoteException, ClassNotFoundException, SQLException;
185}
186
187AddImplDB.java
188import java.rmi.*;
189import java.rmi.server.UnicastRemoteObject;
190import java.sql.*;
191
192public class AddImplDB extends UnicastRemoteObject implements AddDB
193{
194 public AddImplDB() throws RemoteException
195 {
196 super();
197 }
198 public int getSum() throws RemoteException, ClassNotFoundException, SQLException
199 {
200 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
201 Connection con= DriverManager.getConnection("jdbc:odbc:trial");
202 Statement select = con.createStatement();
203
204 ResultSet rs=select.executeQuery("select * from chand");
205 while(rs.next())
206 System.out.println(rs.getInt("result"));
207
208 System.out.println("Enter 2 values: ");
209 int a = Integer.parseInt(System.console().readLine());
210 int b = Integer.parseInt(System.console().readLine());
211 int sum;
212 sum=a+b;
213 String query = "INSERT INTO chand values("+sum+")";
214 System.out.println("Sum = "+sum+"..Inserted..");
215 select.executeUpdate(query);
216
217 rs=select.executeQuery("select * from chand");
218 while(rs.next())
219 System.out.println(rs.getInt("result"));
220
221
222 System.out.println("Enter 2 values to update");
223 int num1 = Integer.parseInt(System.console().readLine());
224 int num2 = Integer.parseInt(System.console().readLine());
225 query="update chand set result="+num2+" where result="+num1;
226 select.executeUpdate(query);
227 System.out.println(num1+"..Updated to.."+num2);
228
229 rs=select.executeQuery("select * from chand");
230 while(rs.next())
231 System.out.println(rs.getInt("result"));
232
233
234 System.out.println("Enter a values to delete: ");
235 int del = Integer.parseInt(System.console().readLine());
236 query="delete from chand where result="+del;
237 select.executeUpdate(query);
238 System.out.println(del+"..Deleted..");
239
240 rs=select.executeQuery("select * from chand");
241 while(rs.next())
242 System.out.println(rs.getInt("result"));
243
244
245 return 1;
246 }
247}
248
249AddServerDB.java
250import java.net.*;
251import java.rmi.*;
252public class AddServerDB
253{
254 public static void main(String[] args)
255 {
256 try
257 {
258 AddImplDB f = new AddImplDB();
259 Naming.rebind("add", f);
260 System.out.println("Addition Server ready.");
261 }
262 catch (RemoteException rex)
263 {
264 System.out.println("Exception in AddImpl.main: " + rex);
265 }
266 catch (MalformedURLException ex)
267 {
268 System.out.println("MalformedURLException " + ex);
269 }
270 }
271}
272
273
274
275
276
277
278
279AddClientDB.java
280import java.rmi.*;
281import java.net.*;
282import java.sql.*;
283public class AddClientDB
284{
285 public static void main(String args[])
286 {
287 try
288 {
289 Object o = Naming.lookup("add");
290 AddDB calculator = (AddDB) o;
291 int f = calculator.getSum();
292 System.out.println("The sum is: "+f);
293 }
294 catch (SQLException ex)
295 {
296 System.err.println("SQL");
297 }
298 catch (ClassNotFoundException ex)
299 {
300 System.err.println("classEX");
301 }
302 catch (NotBoundException ex)
303 {
304 System.err.println("Could not find the requested remote object on the server");
305 }
306 catch (RemoteException ex)
307 {
308 System.err.println("Could not find the requested remote object on the server");
309 }
310 catch (MalformedURLException ex)
311 {
312 System.err.println("Could not find the requested remote object on the server");
313 }
314 }
315}
316
317UDP DATAGRAMS AND SOCKETS
318THE DATAGRAMPACKET CLASS
319
3201. THE CONSTRUCTORS
321
322Constructors for receiving Datagrams
323These two constructors create new DatagramPacket objects for receiving data from the network:
324DatagramPacket(byte[] buffer, int length)
325DatagramPacket(byte[] buffer, int offset, int length)
326For Example:
327This code fragment creates a new DatagramPacket for receiving a datagram of up to 8,192 bytes:
328byte[] buffer = new byte[8192];
329DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
330
331Constructors for Sending Datagrams
332These two constructors create new DatagramPacket objects for sending data across the network:
333DatagramPacket(byte[] data, int length, InetAddress destination, int port)
334DatagramPacket(byte[] data, int offset, int length, InetAddress destination, int port)
335For Example:
336InetAddress ia = InetAddress.getByName("metalab.unc.edu");
337int port = 1227;
338DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);
339// send the packet...
340
3412. GET METHODS
342InetAddress getAddress( )
343Returns an InetAddress object containing the address of the remote host.
344
345SocketAddress getSocketAddress( )
346Returns a SocketAddress object containing the IP address and port of the remote host.
347int getPort( )
348Returns an integer specifying the remote port.
349
350byte[ ] getData( )
351Returns a byte array containing the data from the datagram.
352
353int getLength( )
354Returns the number of bytes of data in the datagram.
355
356int getOffset( )
357This method simply returns the point in the array returned by getData( ) where the data from the datagram begins.
358
359Example:
360import java.net.*;
361public class DatagramExample
362{
363public static void main(String[] args)
364{
365String s = "This is a test.";
366byte[] data = s.getBytes( );
367try
368{
369InetAddress ia = InetAddress.getByName("metalab.unc.edu");
370int port = 2177;
371DatagramPacket dp= new DatagramPacket (data, data.length, ia, port);
372System.out.println("This packet is addressed to "+ dp.getAddress() + " on port " + dp.getPort( ));
373System.out.println("This packet is addressed to "+ dp.getSocketAddress());
374System.out.println("There are " + dp.getLength( )+ " bytes of data in the packet");
375System.out.println(new String(dp.getData(), dp.getOffset(), dp.getLength( )));
376}
377catch (UnknownHostException e)
378{
379System.err.println(e);
380}
381}
382}
383
3843. SET METHODS
385
386void setData(byte[ ] data)
387Changes the payload of the UDP datagram.
388
389public void setData(byte[ ] data, int offset, int length)
390Used for sending a large quantity of data.
391Example:
392int offset = 0;
393DatagramPacket dp=new DatagramPacket(bigarray,offset,512);
394int bytesSent = 0;
395while (bytesSent < bigarray.length)
396{
397socket.send(dp);
398bytesSent += dp.getLength( );
399int bytesToSend = bigarray.length - bytesSent;
400int size = (bytesToSend > 512) ? 512 : bytesToSend;
401dp.setData(bigarray, bytesSent, 512);
402}
403
404
405
406
407public void setAddress(InetAddress remote)
408Changes the address a datagram packet is sent to.
409Example:
410String s = "Really Important Message";
411byte[] data = s.getBytes("ASCII");
412DatagramPacket dp = new DatagramPacket(data, data.length);
413dp.setPort(2000);
414int network = "128.238.5.";
415for (int host = 1; host < 255; host++)
416{
417try
418{
419InetAddress remote = InetAddress.getByName(network + host);
420dp.setAddress(remote);
421socket.send(dp);
422}
423catch (Exception e)
424{}
425}
426
427void setPort(int port)
428Changes the port a datagram is addressed to.
429
430void setLength(int length)
431Changes the number of bytes of data in the internal buffer .
432
433
434
435
436
437
438THE DATAGRAMSOCKET CLASS
439A datagram socket is created and accessed through the DatagramSocket class.
440
4411. THE CONSTRUCTORS
442
443DatagramSocket( )
444Creates a socket that is bound to an anonymous port.
445Example:
446try
447{
448DatagramSocket client = new DatagramSocket( );
449// send packets...
450}
451catch (SocketException e)
452{
453System.err.println(e);
454}
455
456DatagramSocket(int port)
457Creates a socket that listens for incoming datagrams on a specific port.
458
459DatagramSocket(int port, InetAddress address)
460Creates a socket that listens for incoming datagrams on a specific port and network interface.
461
4622. SENDING AND RECEIVING DATAGRAMS
463void send(DatagramPacket dp)
464Example:
465theSocket.send(theOutput);
466
467
468void receive(DatagramPacket dp)
469Receives a single UDP datagram from the network and stores it in DatagramPacket object.
470
471void close( )
472Frees the port occupied by that socket.
473Example:
474try
475{
476DatagramSocket theServer = new DatagramSocket( );
477theServer.close( );
478}
479catch (SocketException e)
480{
481System.err.println(e);
482}
483
484int getLocalPort( )
485Returns an int that represents the local port on which the socket is listening.
486Example:
487try
488{
489DatagramSocket ds = new DatagramSocket( );
490System.out.println("The socket is using port " +
491ds.getLocalPort( ));
492}
493catch (SocketException e)
494{
495}
496
497
498
4993. MANAGING CONNECTIONS
500void connect (InetAddress host, int port)
501Specify that the DatagramSocket will send packets to and receive packets from only the specified remote host on the specified remote port.
502
503void disconnect( )
504Breaks the "connection" of a connected DatagramSocket so that it can once again send packets to and receive packets from any host and port.
505
506int getPort( )
507Returns the remote port to which it is connected. Otherwise, it returns -1.
508
509InetAddress getInetAddress( )
510Returns the address of the remote host to which it is connected. Otherwise, it returns null.
511
5124. SOCKET OPTIONS
513SO_TIMEOUT
514SO_TIMEOUT is the amount of time, in milliseconds, that receive( ) waits for an incoming datagram before throwing an InterruptedIOException.
515void setSoTimeout(int timeout)
516int getSoTimeout( )
517
518SO_RCVBUF
519Determines the size of the buffer used for network I/O.
520void setReceiveBufferSize(int size)
521int getReceiveBufferSize( )
522
523SO_SNDBUF
524Get and set the suggested send buffer size used for network output:
525void setSendBufferSize(int size)
526int getSendBufferSize( )
527SO_REUSEADDR
528Control whether multiple datagram sockets can bind to the same port and address at the same time.
529void setReuseAddress(boolean on)
530boolean getReuseAddress( )
531
532SO_BROADCAST
533Controls whether a socket is allowed to send packets to and receive packets from broadcast addresses.
534void setBroadcast(boolean on)
535boolean getBroadcast( )
536
5375. TRAFFIC CLASS
538int getTrafficClass( )
539void setTrafficClass(int trafficClass)
540
541• 0x02: Low cost
542• 0x04: High reliability
543• 0x08: Maximum throughput
544• 0x10: Minimum delay
545Example:
546DatagramSocket s = new DatagramSocket ( );
547s.setTrafficClass(0x02);
548DatagramSocket s = new DatagramSocket ( );
549s.setTrafficClass(0x08 | 0x10);
550
551
552
553
554
555
556DATAGRAM CHANNEL
557DatagramChannel class are used in non-blocking UDP applications.
558
5591. OPENING A SOCKET
560DatagramChannel open( )
561Example:
562DatagramChannel channel = DatagramChannel .open( );
563
564This channel is bound to a port by accessing the channel’s peer DatagramSocket object using the socket( ) method:
565DatagramSocket socket( )
566Example:
567SocketAddress address = new InetSocketAddress(3141);
568DatagramSocket socket = channel.socket( );
569socket.bind(address);
570
5712. CONNECTING
572DatagramChannel can be configured to only receive datagrams from and send datagrams to one host.
573DatagramChannel connect(SocketAddress remote)
574
575isConnected( ) - returns true if and only if the DatagramSocket is connected
576boolean isConnected( )
577
578disconnect( ) method breaks the connection
579DatagramChannel disconnect( )
580
581
582
583
5843. RECEIVING
585Reads one datagram packet from the channel into a ByteBuffer.
586 SocketAddress receive(ByteBuffer dst)
587
5884. SENDING
589Writes one datagram packet into the channel from a ByteBuffer to the address specified as the second argument.
590 int send(ByteBuffer src, SocketAddress target)
591
5925. READING
593int read(ByteBuffer dst)
594long read(ByteBuffer[] dsts)
595long read(ByteBuffer[] dsts, int offset, int length)
596Before invoking one of these methods, connect( ) must be invoked to glue the channel to a particular remote host. Each of these three methods only reads a single datagram packet from the network. As much data from that datagram as possible is stored in the argument ByteBuffer(s). Each method returns the number of bytes read or –1 if the channel has been closed. This method may return 0 for any of several reasons, including:
597• The channel is non-blocking and no packet was ready.
598• A datagram packet contained no data.
599• The buffer is full.
600
6016. WRITING
602DatagramChannel has the three write methods.
603int write(ByteBuffer src)
604long write(ByteBuffer[] dsts)
605long write(ByteBuffer[] dsts, int offset, int length)
606These methods can only be used on connected channels; otherwise they don’t know where to send the packet. Each of these methods sends a single datagram packet over the connection.
607
6087. CLOSING
609A channel should be closed when done with it to free up the port and any other resources it may be using.
610void close( )
611isOpen( ) checks whether a channel has been closed.
612boolean isOpen( )
613This returns false if the channel is closed, true if it’s open.
614
615Example: UDP echo using DatagramChannel
616Server side
617import java.nio.channels.*;
618Class UDPServer
619{
620public static void main(String[] args)
621{
622DatagramChannel channel = DatagramChannel.open();
623DatagramSocket socket = channel.socket();
624SocketAddress addr = new InetSocketAddress(port);
625Socket.bind(addr);
626ByteBuffer buffer = ByteBuffer.allocate(size);
627SocketAddress client = channel.receive(buffer);
628Channel.send(buffer, client);
629}
630}
631
632
633
634Client side
635import java.nio.channels.*;
636Class UDPClient
637{
638public static void main(String[] args)
639{
640DatagramChannel channel = DatagramChannel.open();
641DatagramSocket socket = channel.socket();
642SocketAddress addr = new InetSocketAddress(port);
643Socket.bind(addr);
644ByteBuffer buffer = ByteBuffer.allocate(size);
645String str = “Helloâ€;
646buffer.put(str.getBytes());
647SocketAddress server = new InetSocketAddress(“localhostâ€, port);
648channel.send(buffer, server);
649channel.receive(buffer);
650while(buffer.hasRemaining()) System.out.println(new String(buffer.get()));
651}
652}
653DATAGRAMCHANNEL ADVANTAGES:
654• Receive() is non-blocking
655• Packets can be reused
656DATAGRAMCHANNEL LIMITATIONS:
657Cannot handle overflow
658• During Receive(), the extra data is dropped.
659• During send(), if extra data is available, nothing will be sent (all/nothing).
660
661Write a program to download the contents associated with a HTTP URL
662and save it in a file.
663import java.io.BufferedInputStream;
664import java.io.FileOutputStream;
665import java.io.IOException;
666import java.net.*;
667import java.io.*;
668public class cs2q1 {
669public static void downloadUsingStream(String urlStr, String file)
670throws IOException{
671URL url = new URL(urlStr);
672BufferedInputStream bis = new BufferedInputStream(url.openStream());
673FileOutputStream fis = new FileOutputStream(file);
674byte[] buffer = new byte[1024];
675int count=0;
676while((count = bis.read(buffer,0,1024)) != -1)
677{
678fis.write(buffer, 0, count);
679}
680fis.close();
681bis.close();
682}
683public static void main(String[] args) {
684String url = "http://campuscoke.blogspot.in/2015/01/ip-header-injava.
685html";
686try {
687cs2q1 a = new cs2q1();
688a.downloadUsingStream(url, "Lab/demo.txt");
689} catch (IOException e) {
690e.printStackTrace();
691}
692}
693}
694\cs 2
695close();
696}
697public static void main(String[] args) {
698String url = "http://campuscoke.blogspot.in/2015/01/ip-header-injava.
699html";
700try {
701cs2q1 a = new cs2q1();
702a.downloadUsingStream(url, "Lab/demo.txt");
703} catch (IOException e) {
704e.printStackTrace();
705}
706}
707}
7082. Write an application to analyse the details of HTTP header using the
709classes and methods supported by java API.
710import java.io.*;
711public class IPHeader {
712public static void main(String[] args) throws IOException {
713BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
714System.out.println("Please enter the Hex Dump:");
715String input = br.readLine();
716String IPVer = input.substring(0,1);
717if(IPVer.equals("4"))
718System.out.println("IP Version: 4");
719if(IPVer.equals("6"))
720System.out.println("IP Version: 6");
721String h_len = input.substring(1,2);
722System.out.println("Header Length: " + (4 * Integer.parseInt(h_len,16)));
723String s_type = input.substring(2,4);
724String s_t_bin = Integer.toBinaryString(Integer.parseInt(s_type,16));
725while(s_t_bin.length() < 8)
726s_t_bin = "0" + s_t_bin;
727System.out.println("Precedence: " +
728Integer.parseInt(s_t_bin.substring(0,3),2));
729if(s_t_bin.charAt(3) == '1')
730System.out.println("Minimize Delay Requested");
731if(s_t_bin.charAt(4) == '1')
732System.out.println("Maximize Throughput Requested");
733if(s_t_bin.charAt(5) == '1')
734System.out.println("Maximize Reliability Requested");
735if(s_t_bin.charAt(6) == '1')
736System.out.println("Minimize Cost Requested");
737String tot_len = input.substring(4,8);
738System.out.println("Total Length: " + Integer.parseInt(tot_len,16) + "
739Bytes");
740String id = input.substring(8,12);
741System.out.println("Identification: " + Integer.parseInt(id,16));
742String frag = input.substring(12,16);
743String frag_bin = Integer.toBinaryString(Integer.parseInt(frag,16));
744while(frag_bin.length() < 16)
745frag_bin = "0" + frag_bin;
746String frag_flags = frag_bin.substring(0,3);
747if(frag_flags.charAt(1) == '1')
748System.out.println("Do not Fragment Packet");
749else
750System.out.println("Can be Fragmented");
751if(frag_flags.charAt(2) == '1')
752System.out.println("More Fragments pending");
753else
754System.out.println("No more Fragments pending");
755System.out.println("Fragmentation Offset: " + ((8 *
756Integer.parseInt(frag_bin.substring(3, 16),2)) - (4 *
757Integer.parseInt(h_len,16))));
758String ttl = input.substring(16,18);
759System.out.println("Time to live: " + Integer.parseInt(ttl,16) + " Hops");
760String protocol = input.substring(18,20);
761System.out.print("Protocol: ");
762if(Integer.parseInt(protocol,16) == 1)
763System.out.println("ICMP");
764if(Integer.parseInt(protocol,16) == 2)
765System.out.println("IGMP");
766if(Integer.parseInt(protocol,16) == 89)
767System.out.println("OSPF");
768if(Integer.parseInt(protocol,16) == 6)
769System.out.println("TCP");
770if(Integer.parseInt(protocol,16) == 17)
771System.out.println("UDP");
772String checksum = input.substring(20,24);
773System.out.println("Header Checksum: " + Integer.parseInt(checksum,16));
774String s_ip = input.substring(24,32);
775String s_ip_bin = Long.toBinaryString(Long.parseLong(s_ip,16));
776while(s_ip_bin.length() < 32)
777s_ip_bin = "0" + s_ip_bin;
778System.out.print("Source IP Address: ");
779System.out.print(Integer.parseInt(s_ip_bin.substring(0,8),2) + ".");
780System.out.print(Integer.parseInt(s_ip_bin.substring(8,16),2) + ".");
781System.out.print(Integer.parseInt(s_ip_bin.substring(16,24),2) + ".");
782System.out.println(Integer.parseInt(s_ip_bin.substring(24,32),2));
783String d_ip = input.substring(32,40);
784String d_ip_bin = Long.toBinaryString(Long.parseLong(d_ip,16));
785while(d_ip_bin.length() < 32)
786d_ip_bin = "0" + d_ip_bin;
787System.out.print("Destination IP Address: ");
788System.out.print(Integer.parseInt(d_ip_bin.substring(0,8),2) + ".");
789System.out.print(Integer.parseInt(d_ip_bin.substring(8,16),2) + ".");
790System.out.print(Integer.parseInt(d_ip_bin.substring(16,24),2) + ".");
791System.out.println(Integer.parseInt(d_ip_bin.substring(24,32),2));
792}
793}
7943. Write a client server program to get an array of 10 integers in client side
795pass it to server and sort the array in descending order on server side and
796display the sorted array[TCP/UDP]]
797import java.io.*;
798import java.net.*;
799import java.util.*;
800class ServerSort
801{
802public static void main(String[] args)throws Exception
803{
804ServerSocket ss = new ServerSocket(7898);
805Socket cs = ss.accept();
806Scanner in = new Scanner(cs.getInputStream());
807PrintStream out = new PrintStream(cs.getOutputStream());
808BufferedReader br = new BufferedReader(new
809InputStreamReader(System.in));
810String s; int y;int temp;
811s=in.next();
812y=Integer.parseInt(s);
813System.out.print("Size of the Received from Clients :- " + y);
814int x[] = new int[y];
815for(int i=0;i<y;i++)
816{
817s=in.next();
818x[i]=Integer.parseInt(s);
819//System.out.println(x[i]);
820}
821System.out.println("\nElements of Array Received from Client :- ");
822for(int u=0;u<y;u++)
823{
824System.out.print(x[u]+" ");
825}
826for(int a = 0;a<y;a++)
827{
828for(int b=0;b<y;b++)
829{
830if(x[a]<x[b])
831{
832temp=x[b];
833x[b]=x[a];
834x[a]=temp;
835}
836}
837}
838System.out.println("\nArray After Sorting :- ");
839for(int u=0;u<y;u++)
840{
841System.out.print(x[u]+" ");
842}
843System.out.println();
844ss.close();cs.close();in.close();out.close();
845}
846}
847import java.io.*;
848import java.net.*;
849import java.util.*;
850class ClientSort
851{
852public static void main(String[] args)throws Exception
853{
854Socket cs = new Socket("localhost",7898);
855DataInputStream in = new DataInputStream(cs.getInputStream());
856PrintStream out = new PrintStream(cs.getOutputStream());
857BufferedReader br = new BufferedReader(new
858InputStreamReader(System.in));
859String s; int k;
860Scanner sc = new Scanner(System.in);
861System.out.println("Enter size of the array :- ");
862k=sc.nextInt();
863int n[] = new int[k];
864s=""+k;
865out.println(s);
866System.out.println("Enter a list of numbers :- ");
867for(int i=0;i<k;i++)
868{
869n[i]=sc.nextInt();
870s=""+n[i];
871out.println(s);
872}
873out.close();in.close();cs.close();br.close();
874}
875}
8764. Write a client server program to get an array of 10 strings in client side
877pass it to server and sort the array of strings in server side and display the
878sorted array[TCP/UDP]
879import java.io.*;
880import java.net.*;
881import java.util.*;
882class ClientStringSort
883{
884public static void main(String[] args)throws Exception
885{
886Socket cs = new Socket("localhost",7998);
887DataInputStream in = new DataInputStream(cs.getInputStream());
888PrintStream out = new PrintStream(cs.getOutputStream());
889BufferedReader br = new BufferedReader(new
890InputStreamReader(System.in));
891String s; int k;
892Scanner sc = new Scanner(System.in);
893System.out.println("Enter size of the array :- ");
894k=sc.nextInt();
895String n[] = new String[k];
896s=""+k;
897out.println(s);
898System.out.println("Enter elements of the array :- ");
899for(int i=0;i<k;i++)
900{
901n[i]=sc.next();
902out.println(n[i]);
903}
904out.close();in.close();cs.close();br.close();
905}
906}
907import java.io.*;
908import java.net.*;
909import java.util.*;
910class ServerStringSort
911{
912public static void main(String[] args)throws Exception
913{
914ServerSocket ss = new ServerSocket(7998);
915Socket cs = ss.accept();
916Scanner in = new Scanner(cs.getInputStream());
917PrintStream out = new PrintStream(cs.getOutputStream());
918BufferedReader br = new BufferedReader(new
919InputStreamReader(System.in));
920String s; int y;String temp;
921s=in.next();
922y=Integer.parseInt(s);
923System.out.print("Size of the Received from Clients :- " + y);
924String x[] = new String[y];
925for(int i=0;i<y;i++)
926{
927x[i]=in.next();
928//System.out.println(x[i]);
929}
930System.out.println("\nElements of Array Received from Client :- ");
931for(int u=0;u<y;u++)
932{
933System.out.print(x[u]+" ");
934}
935for(int a = 0;a<y;a++)
936{
937for(int b=0;b<y;b++)
938{
939if((x[a].compareTo(x[b]))<0)
940{
941temp=x[b];
942x[b]=x[a];
943x[a]=temp;
944}
945}
946}
947System.out.println("\nArray After Sorting :- ");
948for(int u=0;u<y;u++)
949{
950System.out.print(x[u]+" ");
951}
952System.out.println();
953ss.close();cs.close();in.close();out.close();
954}
955}
956
957
958
959Socket Programming
960Date: 06/03/2017
9611. Implement a simple bidirectional TCP protocol, dict, defined in a particular port number. In this protocol, the client opens a socket to that port on the dict server and sends commands such as “DEFINE eng-lat goldâ€. This tells the server to send a definition of the word gold using its English-to-Latin dictionary After the first definition is received, the client can ask for another. When it’s done the client sends the command “quitâ€.
962a. Create an empty Socket Object and Use connect() method for socket connection. b. Illustrate the two different ways to retrieve the information about the socket connection.
963---------find soln=
964
965Socket Programming
966Date: 06/03/2017
9671. Implement a simple bidirectional TCP protocol, dict, defined in a particular port number. In this protocol, the client opens a socket to that port on the dict server and sends commands such as “DEFINE eng-lat goldâ€. This tells the server to send a definition of the word gold using its English-to-Latin dictionary After the first definition is received, the client can ask for another. When it’s done the client sends the command “quitâ€.
968a. Create an empty Socket Object and Use connect() method for socket connection. b. Illustrate the two different ways to retrieve the information about the socket connection.
969
970Find solution---------------of above
971
972Task for 20/03/2017
973
9741. Implement a secure echo client-server program using JSSE packages.
9752. The message entered in the client is sent to the server and the server encodes the message and returns it to the client. Encoding is done by replacing a character by the character next to it i.e. a as b, b as c …z as a. This process is done using UDP. Write a program for the above
9763. Display the result of the following DatagramPacket’s getter methods
977a. public InetAddressgetAddress()
978b. public intgetPort()
979c. public SocketAddressgetSocketAddress()
980d. public byte[] getData()
981e. public intgetLength()
982f. public intgetOffset()
9834. Implement a UDP program that send the same datagram to many different recipients (Use set methods)
984
985import java.io.*;
986import javax.net.ssl.SSLSocket;
987import javax.net.ssl.*;
988
989public class ServerSSL {
990 public static void main(String[] args) throws Exception {
991 SSLServerSocket server;
992 try {
993 SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
994 server = (SSLServerSocket) factory.createServerSocket(8999);
995 SSLSocket client = (SSLSocket) server.accept();
996 System.out.println("Securely connected to client...");
997
998
999 DataInputStream dis = new DataInputStream(client.getInputStream());
1000 DataOutputStream dos = new DataOutputStream(client.getOutputStream());
1001
1002 /*String[] cipher = server.getEnabledCipherSuites();
1003 /*int len = cipher.length;
1004 dos.writeUTF(String.valueOf(len));*/
1005
1006 String[] supported = client.getSupportedCipherSuites();
1007 //dos.writeUTF(cipher[5]);
1008 client.setEnabledCipherSuites(supported);
1009
1010
1011 String receive = "";
1012 if((receive = dis.readUTF()) != null)
1013 System.out.println("Received: "+receive);
1014
1015 dos.writeUTF(receive);
1016
1017 server.close();
1018 } catch(Exception ex) {
1019 System.err.println(ex);
1020 }
1021 }
1022}
1023--------------------------------------------------------------------------------------------------------------
1024import javax.net.ssl.*;
1025import java.io.*;
1026
1027public class ClientSSL {
1028 public static void main(String[] args) throws Exception {
1029 try {
1030 SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
1031 SSLSocket client = (SSLSocket) factory.createSocket("127.0.0.1", 8999);
1032 System.out.println("Securely connected to server...");
1033
1034 DataInputStream dis = new DataInputStream(client.getInputStream());
1035 DataOutputStream dos = new DataOutputStream(client.getOutputStream());
1036 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
1037
1038 /*String length = dis.readUTF();
1039 int l = Integer.parseInt(length);
1040 String[] s = new String[l];
1041 for(int i = 0; i < l; i++)
1042 s[i] = dis.readUTF();*/
1043
1044 String[] supported = client.getSupportedCipherSuites();
1045 client.setEnabledCipherSuites(supported);
1046 /*String cipher = dis.readUTF();
1047 String[] selCipher = {"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"};
1048 client.setEnabledCipherSuites(selCipher);*/
1049
1050 String send, receive = "";
1051 send = br.readLine();
1052 dos.writeUTF(send);
1053 System.out.println("Sent : "+send);
1054
1055 if((receive = dis.readUTF()) != null)
1056 System.out.println("Received : "+receive);
1057 } catch(Exception ex) {
1058 System.err.println(ex);
1059 }
1060 }
1061}
1062
10632.
1064import java.io.*;
1065import java.net.*;
1066import java.util.*;
1067
1068class Server {
1069public static void main(String args[]) throws Exception
1070{
1071DatagramSocket serverSocket = new DatagramSocket(9876);
1072byte[] receiveData = new byte[5];
1073byte[] sendData = new byte[5];
1074while(true)
1075{
1076
1077DatagramPacket receivePacket =
1078new DatagramPacket(receiveData, receiveData.length);
1079serverSocket.receive(receivePacket);
1080String sentence = new String(receivePacket.getData());
1081
1082char c[]=sentence.toCharArray();
1083int n=c.length;
1084int i;
1085char zu;
1086String str="";
1087
1088for(i=0;i<n;i++)
1089{
1090if(c[i]=='z')
1091{
1092zu='a';
1093}
1094else{
1095int num=(int)c[i];
1096num++;
1097zu=(char)num;
1098}
1099str=str+zu;
1100
1101}
1102
1103sendData = str.getBytes();
1104
1105
1106InetAddress IPAddress = receivePacket.getAddress();
1107int port = receivePacket.getPort();
1108
1109DatagramPacket sendPacket =
1110new DatagramPacket(sendData, sendData.length, IPAddress,
1111port);
1112serverSocket.send(sendPacket);
1113}
1114}
1115}
1116--------------------------------------------------------------------------------------------
1117import java.io.*;
1118import java.net.*;
1119
1120class Client {
1121public static void main(String args[]) throws Exception
1122{
1123BufferedReader inFromUser =
1124new BufferedReader(new InputStreamReader(System.in));
1125DatagramSocket clientSocket = new DatagramSocket();
1126InetAddress IPAddress = InetAddress.getByName("localhost");
1127byte[] sendData = new byte[1024];
1128byte[] receiveData = new byte[1024];
1129String sentence = inFromUser.readLine();
1130sendData = sentence.getBytes();
1131DatagramPacket sendPacket =
1132new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
1133clientSocket.send(sendPacket);
1134DatagramPacket receivePacket =
1135new DatagramPacket(receiveData, receiveData.length);
1136clientSocket.receive(receivePacket);
1137String modifiedSentence =
1138new String(receivePacket.getData());
1139System.out.println("FROM SERVER:" + modifiedSentence);
1140clientSocket.close();
1141}
1142}
1143
11443.
1145import java.io.*;
1146
1147import java.net.*;
1148
1149class UDPServer {
1150
1151public static void main(String args[]) throws Exception{
1152
1153DatagramSocket serverSocket = new DatagramSocket(9876);//create socket wd only port no
1154
1155int i;
1156
1157char c,cc;
1158
1159byte[] receiveData = new byte[1024];//data to be sent back
1160
1161while(true){
1162
1163DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);//datagram packet created to receive data
1164
1165serverSocket.receive(receivePacket);//we receive the packet from client in the dp object
1166
1167String sentence = new String(receivePacket.getData());//we extract the data out of the packet and convert to string
1168
1169System.out.println("RECEIVED: " + sentence);//print the recieved data as string
1170
1171System.out.println("This packet is addressed to "+ receivePacket.getAddress() + " on port " + receivePacket.getPort());
1172
1173System.out.println("There are " + receivePacket.getLength()
1174
1175+ " bytes of data in the packet");
1176
1177System.out.println(new String(receivePacket.getData(), "UTF-8"));
1178
1179System.out.println(receivePacket.getOffset());
1180
1181System.out.println(receivePacket.getLength());
1182
1183System.out.println(receivePacket.getSocketAddress());
1184
1185}
1186
1187}
1188
1189}
1190-----------------------------------------------------------------------------------------------------------------------
1191
1192Task for 20/03/2017
1193
11941. Implement a secure echo client-server program using JSSE packages.
11952. The message entered in the client is sent to the server and the server encodes the message and returns it to the client. Encoding is done by replacing a character by the character next to it i.e. a as b, b as c …z as a. This process is done using UDP. Write a program for the above
11963. Display the result of the following DatagramPacket’s getter methods
1197a. public InetAddressgetAddress()
1198b. public intgetPort()
1199c. public SocketAddressgetSocketAddress()
1200d. public byte[] getData()
1201e. public intgetLength()
1202f. public intgetOffset()
12034. Implement a UDP program that send the same datagram to many different recipients (Use set methods)
1204
1205import java.io.*;
1206import javax.net.ssl.SSLSocket;
1207import javax.net.ssl.*;
1208
1209public class ServerSSL {
1210 public static void main(String[] args) throws Exception {
1211 SSLServerSocket server;
1212 try {
1213 SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
1214 server = (SSLServerSocket) factory.createServerSocket(8999);
1215 SSLSocket client = (SSLSocket) server.accept();
1216 System.out.println("Securely connected to client...");
1217
1218
1219 DataInputStream dis = new DataInputStream(client.getInputStream());
1220 DataOutputStream dos = new DataOutputStream(client.getOutputStream());
1221
1222 /*String[] cipher = server.getEnabledCipherSuites();
1223 /*int len = cipher.length;
1224 dos.writeUTF(String.valueOf(len));*/
1225
1226 String[] supported = client.getSupportedCipherSuites();
1227 //dos.writeUTF(cipher[5]);
1228 client.setEnabledCipherSuites(supported);
1229
1230
1231 String receive = "";
1232 if((receive = dis.readUTF()) != null)
1233 System.out.println("Received: "+receive);
1234
1235 dos.writeUTF(receive);
1236
1237 server.close();
1238 } catch(Exception ex) {
1239 System.err.println(ex);
1240 }
1241 }
1242}
1243--------------------------------------------------------------------------------------------------------------
1244import javax.net.ssl.*;
1245import java.io.*;
1246
1247public class ClientSSL {
1248 public static void main(String[] args) throws Exception {
1249 try {
1250 SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
1251 SSLSocket client = (SSLSocket) factory.createSocket("127.0.0.1", 8999);
1252 System.out.println("Securely connected to server...");
1253
1254 DataInputStream dis = new DataInputStream(client.getInputStream());
1255 DataOutputStream dos = new DataOutputStream(client.getOutputStream());
1256 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
1257
1258 /*String length = dis.readUTF();
1259 int l = Integer.parseInt(length);
1260 String[] s = new String[l];
1261 for(int i = 0; i < l; i++)
1262 s[i] = dis.readUTF();*/
1263
1264 String[] supported = client.getSupportedCipherSuites();
1265 client.setEnabledCipherSuites(supported);
1266 /*String cipher = dis.readUTF();
1267 String[] selCipher = {"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"};
1268 client.setEnabledCipherSuites(selCipher);*/
1269
1270 String send, receive = "";
1271 send = br.readLine();
1272 dos.writeUTF(send);
1273 System.out.println("Sent : "+send);
1274
1275 if((receive = dis.readUTF()) != null)
1276 System.out.println("Received : "+receive);
1277 } catch(Exception ex) {
1278 System.err.println(ex);
1279 }
1280 }
1281}
1282
12832.
1284import java.io.*;
1285import java.net.*;
1286import java.util.*;
1287
1288class Server {
1289public static void main(String args[]) throws Exception
1290{
1291DatagramSocket serverSocket = new DatagramSocket(9876);
1292byte[] receiveData = new byte[5];
1293byte[] sendData = new byte[5];
1294while(true)
1295{
1296
1297DatagramPacket receivePacket =
1298new DatagramPacket(receiveData, receiveData.length);
1299serverSocket.receive(receivePacket);
1300String sentence = new String(receivePacket.getData());
1301
1302char c[]=sentence.toCharArray();
1303int n=c.length;
1304int i;
1305char zu;
1306String str="";
1307
1308for(i=0;i<n;i++)
1309{
1310if(c[i]=='z')
1311{
1312zu='a';
1313}
1314else{
1315int num=(int)c[i];
1316num++;
1317zu=(char)num;
1318}
1319str=str+zu;
1320
1321}
1322
1323sendData = str.getBytes();
1324
1325
1326InetAddress IPAddress = receivePacket.getAddress();
1327int port = receivePacket.getPort();
1328
1329DatagramPacket sendPacket =
1330new DatagramPacket(sendData, sendData.length, IPAddress,
1331port);
1332serverSocket.send(sendPacket);
1333}
1334}
1335}
1336--------------------------------------------------------------------------------------------
1337import java.io.*;
1338import java.net.*;
1339
1340class Client {
1341public static void main(String args[]) throws Exception
1342{
1343BufferedReader inFromUser =
1344new BufferedReader(new InputStreamReader(System.in));
1345DatagramSocket clientSocket = new DatagramSocket();
1346InetAddress IPAddress = InetAddress.getByName("localhost");
1347byte[] sendData = new byte[1024];
1348byte[] receiveData = new byte[1024];
1349String sentence = inFromUser.readLine();
1350sendData = sentence.getBytes();
1351DatagramPacket sendPacket =
1352new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
1353clientSocket.send(sendPacket);
1354DatagramPacket receivePacket =
1355new DatagramPacket(receiveData, receiveData.length);
1356clientSocket.receive(receivePacket);
1357String modifiedSentence =
1358new String(receivePacket.getData());
1359System.out.println("FROM SERVER:" + modifiedSentence);
1360clientSocket.close();
1361}
1362}
1363
13643.
1365import java.io.*;
1366
1367import java.net.*;
1368
1369class UDPServer {
1370
1371public static void main(String args[]) throws Exception{
1372
1373DatagramSocket serverSocket = new DatagramSocket(9876);//create socket wd only port no
1374
1375int i;
1376
1377char c,cc;
1378
1379byte[] receiveData = new byte[1024];//data to be sent back
1380
1381while(true){
1382
1383DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);//datagram packet created to receive data
1384
1385serverSocket.receive(receivePacket);//we receive the packet from client in the dp object
1386
1387String sentence = new String(receivePacket.getData());//we extract the data out of the packet and convert to string
1388
1389System.out.println("RECEIVED: " + sentence);//print the recieved data as string
1390
1391System.out.println("This packet is addressed to "+ receivePacket.getAddress() + " on port " + receivePacket.getPort());
1392
1393System.out.println("There are " + receivePacket.getLength()
1394
1395+ " bytes of data in the packet");
1396
1397System.out.println(new String(receivePacket.getData(), "UTF-8"));
1398
1399System.out.println(receivePacket.getOffset());
1400
1401System.out.println(receivePacket.getLength());
1402
1403System.out.println(receivePacket.getSocketAddress());
1404
1405}
1406
1407}
1408
1409}
1410-----------------------------------------------------------------------------------
1411import java.io.*;
1412
1413import java.net.*;
1414
1415class UDPClient {
1416
1417public static void main(String args[]) throws Exception {
1418
1419BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));
1420
1421DatagramSocket clientSocket = new DatagramSocket();//for client socket we don't need port no ..to create server socket we need port no.
1422
1423InetAddress IPAddress = InetAddress.getByName("localhost");
1424
1425byte[] sendData = new byte[1024];
1426
1427String sentence = inFromUser.readLine();
1428
1429sendData = sentence.getBytes();
1430
1431DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
1432
1433clientSocket.send(sendPacket);
1434
1435 }
1436
1437 }
1438
14394.
1440import java.net.*;
1441import java.io.*;
1442
1443public class MultiSend {
1444 public static void main(String[] args) {
1445 try {
1446 String s = "Really important message";
1447 byte[] data = s.getBytes();
1448 DatagramPacket dp = new DatagramPacket(data, data.length);
1449 dp.setPort(2000);
1450 DatagramSocket socket = new DatagramSocket();
1451 String network = "128.238.5.";
1452 for(int host = 1; host < 255; host++) {
1453 try {
1454 InetAddress remote = InetAddress.getByName(network + host);
1455 dp.setAddress(remote);
1456 socket.send(dp);
1457 System.out.println("Sent to address : "+ network + host);
1458 } catch(Exception e) {
1459 //skip it, continue with next host
1460 }
1461 }
1462 } catch(Exception ex) {
1463 System.err.println(ex);
1464 }
1465 }
1466}
1467
1468
1469
1470Write a program that displays the content of a web page using URLConnection class.
14711. Display the details of HTTP Response header fields.
1472a. Using Specific header fields
1473b. Using Arbitrary header fields
14742. Implement a program that Configure the Client Request HTTP Header by using setRequestProperty method. Also display the updated request header values using getRequestProperty.
1475
1476....................
1477
1478Q1)Write a program that displays the content of a web page using URLConnection class.
1479OUTPUT:
1480
1481
1482CODE:
1483import java.io.*;
1484import java.net.*;
1485public class program1{
1486public static void main (String[] args) {
1487if (args.length > 0) {
1488try {
1489URL u = new URL(args[0]);
1490URLConnection uc = u.openConnection();
1491try{
1492InputStream raw = uc.getInputStream();
1493InputStream buffer = new BufferedInputStream(raw);
1494Reader reader = new InputStreamReader(buffer);
1495int c;
1496while ((c = reader.read()) != -1) {
1497System.out.print((char) c);
1498}
1499}
1500catch (MalformedURLException ex) {
1501System.err.println(args[0] + " is not a parseable URL");
1502}
1503}
1504catch (IOException ex) {
1505System.err.println(ex); }
1506}
1507 }
1508 }
1509
1510Q2)Display the details of HTTP Response header fields.
1511a.Using Specific header fields
1512 • Content-type
1513• Content-length
1514• Content-encoding
1515• Date
1516• Last-modified
1517• Expires
1518OUTPUT:
1519
1520
1521
1522CODE:
1523
1524import java.io.*;
1525import java.net.*;
1526import java.util.*;
1527public class program2a{
1528public static void main (String[] args) {
1529if (args.length > 0) {
1530try {
1531URL u = new URL(args[0]);
1532URLConnection uc = u.openConnection();
1533try{
1534System.out.println(uc.getContentType());
1535System.out.println(uc.getContentLength());
1536System.out.println(uc.getContentEncoding());
1537Date date1= new Date(uc.getDate());
1538System.out.println(date1);
1539Date expirationdate1= new Date(uc.getExpiration());
1540System.out.println(expirationdate1);
1541Date lastmodifieddate1= new Date(uc.getLastModified());
1542System.out.println(lastmodifieddate1);
1543}
1544catch (Exception ex) {
1545System.err.println(args[0] + " is not a parseable URL");
1546}
1547}
1548catch (IOException ex) {
1549System.err.println(ex); }
1550}
1551 }
1552 }
1553
1554b.Using Arbitrary header fields
1555OUTPUT:
1556
1557CODE:
1558import java.io.*;
1559import java.net.*;
1560public class program2b{
1561public static void main (String[] args) {
1562if (args.length > 0) {
1563try {
1564URL u = new URL(args[0]);
1565URLConnection uc = u.openConnection();
1566try{
1567HttpURLConnection http=(HttpURLConnection)uc;
1568String s,ss;
1569for(int i=0;i>=0;i++)
1570{
1571if(uc.getHeaderField(i)==null)
1572{
1573break;
1574}
1575System.out.println(uc.getHeaderField(i)+" "+uc.getHeaderFieldKey(i));
1576
1577}
1578}
1579catch (Exception ex) {
1580System.err.println(args[0] + " is not a parseable URL");
1581}
1582}
1583catch (IOException ex) {
1584System.err.println(ex); }
1585}
1586 }
1587 }
1588Q3)Implement a program that Configure the Client Request HTTP Header by using setRequestProperty method. Also display the updated request header values using getRequestProperty.
1589OUTPUT:
1590
1591CODE:
1592import java.io.*;
1593import java.net.*;
1594import java.util.*;
1595public class program3{
1596public static void main (String[] args) {
1597if (args.length > 0) {
1598try {
1599URL u = new URL(args[0]);
1600HttpURLConnection http = (HttpURLConnection) u.openConnection();
1601http.setRequestMethod("HEAD");
1602String s=http.getRequestMethod();
1603System.out.println(u + " was last modified at "+ new Date(http.getLastModified()));
1604System.out.println(s);
1605}
1606catch (Exception ex) {
1607System.err.println(args[0] + " is not a parseable URL");
1608}
1609 }
1610 }
1611 }
1612
1613thread using the tcp ip
1614import java.net.*;
1615import java.io.*;
1616class Rand extends Thread{
1617 DataOutputStream dout;
1618 public Rand(DataOutputStream d){
1619 dout=d;
1620 }
1621public void run(){
1622try{
1623while(true){
1624dout.writeInt((int)(Math.random()*100)+1);
1625}
1626}
1627catch(IOException e)
1628{}
1629}
1630}
1631class ServerRandom{
1632public static void main(String args[])throws Exception{
1633ServerSocket ss=new ServerSocket(1111);
1634Socket s=ss.accept();
1635DataOutputStream dout=new DataOutputStream(s.getOutputStream());
1636Rand r=new Rand(dout);
1637r.start();
1638Thread.sleep(3000);
1639System.exit(0);
1640}
1641}
1642
1643client thread sum
1644import java.net.*;
1645import java.io.*;
1646class ClientRandom{
1647public static void main(String args[])
1648{
1649int sum=0;
1650try{
1651Socket s=new Socket("localhost",1111);
1652 DataInputStream din=new DataInputStream(s.getInputStream());
1653
1654 while(true){
1655 int a=din.readInt();
1656 System.out.println(a);
1657 sum=sum+a;
1658 }
1659}
1660catch(Exception e){
1661 System.out.println("sum="+sum);
1662 }
1663}
1664}
1665
1666download file
1667
1668
1669import java.io.File;
1670import java.io.FileOutputStream;
1671import java.io.IOException;
1672import java.io.InputStream;
1673import java.net.HttpURLConnection;
1674import java.net.URL;
1675
1676
1677public class download {
1678 private static final int BUFFER_SIZE = 4096;
1679
1680
1681 public static void downloadFile(String fileURL, String saveDir)
1682 throws IOException {
1683 URL url = new URL(fileURL);
1684 HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
1685 int responseCode = httpConn.getResponseCode();
1686
1687 // always check HTTP response code first
1688 if (responseCode == HttpURLConnection.HTTP_OK) {
1689 String fileName = "";
1690 String disposition = httpConn.getHeaderField("Content-Disposition");
1691 String contentType = httpConn.getContentType();
1692 int contentLength = httpConn.getContentLength();
1693
1694 if (disposition != null) {
1695 // extracts file name from header field
1696 int index = disposition.indexOf("filename=");
1697 if (index > 0) {
1698 fileName = disposition.substring(index + 10,
1699 disposition.length() - 1);
1700 }
1701 } else {
1702 // extracts file name from URL
1703 fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
1704 fileURL.length());
1705 }
1706
1707 System.out.println("Content-Type = " + contentType);
1708 System.out.println("Content-Disposition = " + disposition);
1709 System.out.println("Content-Length = " + contentLength);
1710 System.out.println("fileName = " + fileName);
1711
1712 // opens input stream from the HTTP connection
1713 InputStream inputStream = httpConn.getInputStream();
1714 String saveFilePath = saveDir + File.separator + fileName;
1715
1716 // opens an output stream to save into file
1717 FileOutputStream outputStream = new FileOutputStream(saveFilePath);
1718
1719 int bytesRead = -1;
1720 byte[] buffer = new byte[BUFFER_SIZE];
1721 while ((bytesRead = inputStream.read(buffer)) != -1) {
1722 outputStream.write(buffer, 0, bytesRead);
1723 }
1724
1725 outputStream.close();
1726 inputStream.close();
1727
1728 System.out.println("File downloaded");
1729 } else {
1730 System.out.println("No file to download. Server replied HTTP code: " + responseCode);
1731 }
1732 httpConn.disconnect();
1733 }
1734}
1735
1736
1737factorial client
1738
1739import java.io.*;
1740import java.net.*;
1741import java.util.*;
1742class factclient
1743{
1744 public static void main(String args[]) throws Exception
1745 {
1746 Socket s=new Socket("localhost",2400);
1747 DataInputStream din=new DataInputStream(s.getInputStream());
1748 DataOutputStream dout= new DataOutputStream(s.getOutputStream());
1749 BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));
1750 System.out.println("Enter the numebr:");
1751 String str=rd.readLine();
1752 dout.writeUTF(str);
1753 String str2=din.readUTF();
1754 System.out.println(str2);
1755 }
1756}
1757
1758
1759facorial server
1760import java.io.*;
1761import java.net.*;
1762import java.util.*;
1763class factserv
1764{
1765 public static void main(String args[]) throws Exception
1766 {
1767 ServerSocket ss=new ServerSocket(2400);
1768 Socket s=ss.accept();
1769 DataInputStream din=new DataInputStream(s.getInputStream());
1770 DataOutputStream dout=new DataOutputStream(s.getOutputStream());
1771 String str=din.readUTF();
1772 int m=Integer.parseInt(str);
1773 int n=1;
1774 for(int i=1;i<=m;i++)
1775 n=n*i;
1776 String k=Integer.toString(n);
1777 dout.writeUTF(k);
1778 }
1779}
1780
1781
1782
1783
1784client echo udp
1785import java.util.*;
1786import java.net.*;
1787public class ClientEcho{
1788 public static void main( String args[] ) throws Exception {
1789 Scanner sc=new Scanner(System.in);
1790 InetAddress add = InetAddress.getLocalHost();
1791 DatagramSocket dsock = new DatagramSocket(8);
1792 byte arr1[] = new byte[150];
1793 DatagramPacket dpack = new DatagramPacket(arr1,arr1.length);
1794 String s1="",s2="";
1795
1796 while(true){
1797 s1=sc.nextLine();
1798 byte arr[] = s1.getBytes( );
1799 dsock.send(new DatagramPacket(arr, arr.length,add,7)); // send the packet
1800 dsock.receive(dpack); // receive the packet
1801 s2= new String(dpack.getData( ),0,dpack.getLength());
1802 System.out.println(s2);
1803 }
1804 }
1805}
1806
1807Server echo udp
1808import java.net.*;
1809import java.util.*;
1810public class ServerEcho {
1811 public static void main(String args[]) throws Exception {
1812 Scanner sc=new Scanner(System.in);
1813 InetAddress add = InetAddress.getLocalHost();
1814 DatagramSocket dsock = new DatagramSocket(7);
1815 byte arr1[] = new byte[150];
1816 DatagramPacket dpack = new DatagramPacket(arr1,arr1.length);
1817 String s1="",s2="";
1818
1819 while(true) {
1820 dsock.receive(dpack);
1821 s2 = new String(dpack.getData(),0,dpack.getLength());
1822 System.out.println(s2);
1823 s1=sc.nextLine();
1824 byte arr2[]=s1.getBytes();
1825 dsock.send(new DatagramPacket(arr2, arr2.length,add,8));
1826 }
1827 }
1828}
1829
1830password
1831import java.net.*;
1832import java.util.*;
1833public class ServerEcho {
1834 public static void main(String args[]) throws Exception {
1835 Scanner sc=new Scanner(System.in);
1836 InetAddress add = InetAddress.getLocalHost();
1837 DatagramSocket dsock = new DatagramSocket(7);
1838 byte arr1[] = new byte[150];
1839 DatagramPacket dpack = new DatagramPacket(arr1,arr1.length);
1840 String s1="",s2="";
1841
1842 while(true) {
1843 dsock.receive(dpack);
1844 s2 = new String(dpack.getData(),0,dpack.getLength());
1845 System.out.println(s2);
1846 s1=sc.nextLine();
1847 byte arr2[]=s1.getBytes();
1848 dsock.send(new DatagramPacket(arr2, arr2.length,add,8));
1849 }
1850 }
1851}
1852
1853contents server
1854import java.net.*;
1855import java.io.*;
1856public class ContentsServer
1857{
1858public static void main(String args[]) throws Exception{
1859ServerSocket sersock = new ServerSocket(9090);
1860System.out.println("Server ready for connection");
1861Socket sock = sersock.accept(); // binding with port: 4000
1862System.out.println("Connection is successful and wating for chatting");
1863InputStream istream = sock.getInputStream( );
1864BufferedReader fileRead =new BufferedReader(new
1865InputStreamReader(istream));
1866String fname = fileRead.readLine( );
1867BufferedReader contentRead = new BufferedReader(new FileReader(fname) );
1868OutputStream ostream = sock.getOutputStream( );
1869PrintWriter pwrite = new PrintWriter(ostream, true);
1870String str;
1871while((str = contentRead.readLine()) != null) // reading line-by-line from file
1872{
1873pwrite.println(str);
1874}
1875sock.close(); sersock.close();
1876pwrite.close(); fileRead.close(); contentRead.close();
1877}
1878}
1879
1880contents client
1881import java.net.*;
1882import java.io.*;
1883public class ContentsClient
1884{
1885public static void main( String args[ ] ) throws Exception
1886{
1887Socket sock = new Socket( "localhost", 9090);
1888// reading the file name from keyboard. Uses input stream
1889System.out.print("Enter the file name");
1890BufferedReader keyRead = new BufferedReader(new
1891InputStreamReader(System.in));
1892String fname = keyRead.readLine();
1893// sending the file name to server. Uses PrintWriter
1894OutputStream ostream = sock.getOutputStream( );
1895PrintWriter pwrite = new PrintWriter(ostream, true);
1896pwrite.println(fname);
1897// receiving the contents from server. Uses input stream
1898InputStream istream = sock.getInputStream();
1899BufferedReader socketRead = new BufferedReader(new
1900InputStreamReader(istream));
1901String str;
1902while((str = socketRead.readLine()) != null) // reading line-by-line
1903{
1904System.out.println(str);
1905}
1906pwrite.close(); socketRead.close(); keyRead.close();
1907}
1908}
1909
1910
1911port scanner
1912import java.net.*;
1913import java.io.*;
1914public class PortScanner
1915{
1916 public static void main(String args[])
1917 {
1918
1919 for (int i=800; i<1024; i++)
1920 {
1921 try
1922 {
1923 Socket s = new Socket("localhost",i);
1924 System.out.println("There is a server on port " + " of localhost" );
1925 s.close();
1926 }
1927
1928 catch (Exception e)
1929 {
1930 System.out.println("error");
1931 continue;
1932 }
1933 }
1934 }
1935}
1936date client
1937import java.io.*;
1938import java.net.*;
1939class DateClient1{
1940 public static void main(String args[]) throws Exception{
1941 Socket s=new Socket("localhost",5217);
1942 DataInputStream din=new DataInputStream(s.getInputStream());
1943 System.out.println(din.readUTF());
1944
1945 }
1946}
1947
1948
1949date sever
1950import java.net.*;
1951import java.io.*;
1952import java.util.*;
1953class DateServer1
1954 {
1955 public static void main(String args[]) throws Exception{
1956 ServerSocket ss=new ServerSocket(5217);
1957 while(true)
1958 {
1959 System.out.println("Waiting For Connection ...");
1960 Socket s=ss.accept();
1961 DataOutputStream dout=new DataOutputStream(s.getOutputStream());
1962 dout.writeUTF((new Date()).toString());
1963 dout.close();
1964 s.close();
1965 }
1966 }
1967}
1968
1969
1970UDP server
1971 import java.net.*;
1972 import java.io.*;
1973 class stcp
1974{
1975 public static void main(String args[])throws Exception
1976{
1977 ServerSocket ss=new ServerSocket(3333);
1978 Socket s=ss.accept();
1979 DataInputStream din=new DataInputStream(s.getInputStream());
1980 DataOutputStream dout=new DataOutputStream(s.getOutputStream());
1981 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
1982
1983 String str="",str2="";
1984 while(!str.equals("stop"))
1985{
1986 str=din.readUTF();
1987InetAddress add1=InetAddress.getByName(str);
1988 str2=add1.getHostAddress();
1989
1990 dout.writeUTF(str2);
1991 dout.flush();
1992 }
1993 din.close();
1994 s.close();
1995 ss.close();
1996 }
1997}
1998
1999server dns
2000import java.net.*;
2001import java.util.*;
2002public class ServerDNS{
2003 public static void main(String args[]) throws Exception {
2004 Scanner sc=new Scanner(System.in);
2005 InetAddress add = InetAddress.getLocalHost();
2006 DatagramSocket dsock = new DatagramSocket(7);
2007 byte arr1[] = new byte[150];
2008 DatagramPacket dpack = new DatagramPacket(arr1,arr1.length);
2009 String s1="",s2="";
2010
2011 while(true) {
2012 dsock.receive(dpack);
2013 s2 = new String(dpack.getData(),0,dpack.getLength());
2014 System.out.println(s2);
2015 InetAddress add1=InetAddress.getByName(s2);
2016 s1=add1.getHostAddress();
2017 byte arr2[]=s1.getBytes();
2018 dsock.send(new DatagramPacket(arr2, arr2.length,add,8));
2019 }
2020 }
2021}
2022
2023client dns
2024import java.util.*;
2025import java.net.*;
2026public class ClientDNS{
2027 public static void main( String args[] ) throws Exception {
2028 Scanner sc=new Scanner(System.in);
2029 InetAddress add = InetAddress.getLocalHost();
2030 DatagramSocket dsock = new DatagramSocket(8);
2031 byte arr1[] = new byte[150];
2032 DatagramPacket dpack = new DatagramPacket(arr1,arr1.length);
2033 String s1="",s2="";
2034
2035 while(true){
2036 s1=sc.nextLine();
2037 byte arr[] = s1.getBytes( );
2038 dsock.send(new DatagramPacket(arr, arr.length,add,7)); // send the packet
2039 dsock.receive(dpack); // receive the packet
2040 s2= new String(dpack.getData( ),0,dpack.getLength());
2041 System.out.println(s2);
2042 }
2043 }
2044}
2045
2046download
2047import java.io.*;
2048import java.net.*;
2049public class JavaGeturl
2050{
2051 public static void main(String[] args)
2052 {
2053 URL u;
2054 InputStream is=null;
2055 DataInputStream dis;
2056 String s;
2057 try
2058 {
2059 u=new URL("ftp://10.30.2.53");
2060 is=u.openStream();
2061 dis = new DataInputStream(new BufferedInputStream(is));
2062 while((s=dis.readLine())!=null)
2063 {
2064 System.out.println(s);
2065 }
2066 }
2067 catch(MalformedURLException mue)
2068 {
2069 System.out.println("404: Error NOT FOUND");
2070 mue.printStackTrace();
2071 System.exit(1);
2072 }
2073 catch(IOException ioe)
2074 {
2075 System.out.println("404: Error NOT FOUND");
2076 ioe.printStackTrace();
2077 System.exit(1);
2078 }
2079 finally
2080 {
2081 try
2082 {
2083 is.close();
2084 }
2085 catch(IOException ioe)
2086 {
2087 }
2088 }
2089 }
2090}
2091
2092
20931- Wap to display server's date and time details at the client end.
2094
2095DateClient.java
2096import java.io.*;
2097import java.net.Socket;
2098public class dateClient {
2099public static void main(String[] args) throws IOException {
2100Socket s = new Socket("127.0.0.1",9090);
2101BufferedReader input = new BufferedReader(new
2102InputStreamReader(s.getInputStream()));
2103String answer = input.readLine();
2104System.out.println("The date and time details are"+answer);
2105System.exit(0);
2106}
2107
2108
2109
2110DATESERVER.java
2111
2112import java.io.IOException;
2113import java.io.PrintWriter;
2114import java.net.ServerSocket;
2115import java.net.Socket;
2116import java.util.Date;
2117public class dateserver {
2118public static void main(String[] args) throws IOException {
2119ServerSocket listener = new ServerSocket(9090);
2120try {
2121while(true) {
2122Socket socket = listener.accept();
2123try {
2124PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
2125out.println(new Date().toString());
2126}finally {
2127socket.close();
2128}
2129}
2130}
2131finally {
2132listener.close();
2133}
2134}
2135}
2136
2137
2138
21392-> Wap to display the client's address at the server end?
2140
2141import java.io.*;
2142import java.net.*;
2143public class ServerAddr {
2144public static void main(String[] args) throws IOException {
2145try {
2146ServerSocket ss = new ServerSocket(6666);
2147System.out.println("Waiting for client....");
2148Socket s = ss.accept();
2149System.out.println("Connected to client....");
2150DataInputStream in = new DataInputStream(s.getInputStream());
2151String line = null;
2152line = in.readUTF();
2153System.out.println("Client's IP address:" + line);
2154}
2155catch(Exception e) {
2156e.printStackTrace();
2157}}}
2158
2159
2160import java.io.*;
2161import java.net.*;
2162public class ClientAddr {
2163public static void main(String[] args) throws IOException {
2164try {
2165InetAddress ipaddress = InetAddress.getByName("");
2166Socket s = new Socket(ipaddress, 6666);
2167System.out.println("Connected to the server...");
2168DataOutputStream out = new DataOutputStream(s.getOutputStream());
2169String line = null;
2170System.out.println("Sending IP Adrress to server...");
2171line = ipaddress.getHostAddress();
2172out.writeUTF(line);
2173out.flush(); }
2174catch(Exception e) {
2175e.printStackTrace();
2176}}}
2177
2178
2179
21803-> A java program to make a chat application using UDP?
2181
2182
2183import java.io.*;
2184import java.net.*;
2185class UDPServer
2186{
2187public static DatagramSocket serversocket;
2188public static DatagramPacket dp;
2189public static BufferedReader dis;
2190public static InetAddress ia;
2191public static byte buf[] = new byte[1024];
2192public static int cport = 789,sport=790;
2193public static void main(String[] a) throws IOException
2194{
2195serversocket = new DatagramSocket(sport);
2196dp = new DatagramPacket(buf,buf.length);
2197dis = new BufferedReader
2198(new InputStreamReader(System.in));
2199ia = InetAddress.getLocalHost();
2200System.out.println("Server is Running...");
2201while(true)
2202{
2203serversocket.receive(dp);
2204String str = new String(dp.getData(), 0,
2205dp.getLength());
2206if(str.equals("STOP"))
2207{
2208System.out.println("Terminated...");
2209break;
2210}
2211System.out.println("Client: " + str);
2212String str1 = new String(dis.readLine());
2213buf = str1.getBytes();
2214serversocket.send(new
2215DatagramPacket(buf,str1.length(), ia, cport));
2216}
2217}
2218}
2219
2220
2221
2222import java.io.*;
2223import java.net.*;
2224class UDPClient
2225{
2226public static DatagramSocket clientsocket;
2227public static DatagramPacket dp;
2228public static BufferedReader dis;
2229public static InetAddress ia;
2230public static byte buf[] = new byte[1024];
2231public static int cport = 789, sport = 790;
2232public static void main(String[] a) throws IOException
2233{
2234clientsocket = new DatagramSocket(cport);
2235dp = new DatagramPacket(buf, buf.length);
2236dis = new BufferedReader(new
2237InputStreamReader(System.in));
2238ia = InetAddress.getLocalHost();
2239System.out.println("Client is Running... Type \'STOP\'
2240to Quit");
2241while(true)
2242{
2243String str = new String(dis.readLine());
2244buf = str.getBytes();
2245if(str.equals("STOP"))
2246{
2247System.out.println("Terminated...");
2248clientsocket.send(new
2249DatagramPacket(buf,str.length(), ia,
2250sport));
2251break;
2252}
2253clientsocket.send(new DatagramPacket(buf,
2254str.length(), ia, sport));
2255clientsocket.receive(dp);
2256String str2 = new String(dp.getData(), 0,
2257dp.getLength());
2258System.out.println("Server: " + str2);
2259}
2260}
2261}
2262
2263
2264
2265
2266
2267
2268
2269
22704-> Write a java program to develop a simple chat application?
2271
2272import java.io.*;
2273import java.net.*;
2274public class EchoServer
2275{
2276public static void main(String args[]) throws Exception
2277{
2278try
2279{
2280int Port;
2281BufferedReader Buf =new BufferedReader(new
2282InputStreamReader(System.in));
2283System.out.print(" Enter the Port Address : " );
2284Port=Integer.parseInt(Buf.readLine());
2285ServerSocket sok =new ServerSocket(Port);
2286System.out.println(" Server is Ready To Receive a Message. ");
2287System.out.println(" Waiting ..... ");
2288Socket so=sok.accept();
2289if(so.isConnected()==true)
2290System.out.println(" Client Socket is Connected Succecfully. ");
2291InputStream in=so.getInputStream();
2292OutputStream ou=so.getOutputStream();
2293PrintWriter pr=new PrintWriter(ou);
2294BufferedReader buf=new BufferedReader(new
2295InputStreamReader(in));
2296String str=buf.readLine();
2297System.out.println(" Message Received From Client : " + str);
2298System.out.println(" This Message is Forwarded To Client. ");
2299pr.println(str);
2300pr.flush();
2301}
2302catch(Exception e)
2303{
2304System.out.println(" Error : " + e.getMessage());
2305}
2306}
2307}
2308
2309
2310
2311import java.io.*;
2312import java.net.*;
2313public class EchoClient
2314{
2315public static void main(String args[]) throws Exception
2316{
2317try {
2318int Port;
2319BufferedReader Buf =new BufferedReader(new
2320InputStreamReader(System.in));
2321System.out.print(" Enter the Port Address : " );
2322Port=Integer.parseInt(Buf.readLine());
2323Socket sok=new Socket("localhost",Port);
2324if(sok.isConnected()==true)
2325System.out.println(" Server Socket is Connected Succecfully. ");
2326InputStream in=sok.getInputStream();
2327OutputStream ou=sok.getOutputStream();
2328PrintWriter pr=new PrintWriter(ou);
2329BufferedReader buf1=new BufferedReader(new
2330InputStreamReader(System.in));
2331BufferedReader buf2=new BufferedReader(new
2332InputStreamReader(in));
2333String str1,str2;
2334System.out.print(" Enter the Message : ");
2335str1=buf1.readLine();
2336pr.println(str1);
2337pr.flush();
2338System.out.println(" Message Send Successfully. ");
2339str2=buf2.readLine();
2340System.out.println(" Message From Server : " + str2);
2341}
2342catch(Exception e)
2343{
2344System.out.println(" Error : " + e.getMessage());
2345}
2346}
2347}
2348
2349
23505-> The message entered in the client is sent to the server and the server encodes the message and returns it to the client. Encoding is done by replacing a character by the character next to it i.e. a as b, b as c …z as a.
2351This process is done using the TCP/IP protocol. Write a Java program for the above?
2352
2353
2354
2355
2356
23576-> The message entered in the client is sent to the server and the server encodes the message and returns it to the client.
2358Encoding is done by replacing a character by the character next to it i.e. a as b, b as c …z as a. This process is done using UDP. Write a Java program for the above?
2359
2360
2361
2362
23637-> Write a Java program to display the name and address of the computer that we are currently working on?
2364
2365import java.net.*;
2366import java.util.*;
2367import java.lang.*;
2368public class ip
2369{
2370public static void main(String args[])throws UnknownHostException
2371{
2372InetAddress Address=InetAddress.getLocalHost();
2373System.out.println(Address);
2374System.out.println(Address.getHostAddress());
2375System.out.println(Address.getHostName());
2376}
2377}
2378
2379
2380
2381
2382
23838-> The client accepts IP header information in hexadecimal and sends to the server. The server receives those details and examines its checksum field.
2384Write a Java program for this scenario?
2385
2386
2387
2388
23899-> Using threading concepts, write a Java program to create a daemon process?
2390
2391import java.util.*;
2392import java.net.*;
2393public class TestDaemonThread1 extends Thread{
2394 public void run(){
2395 if(Thread.currentThread().isDaemon()){//checking for daemon thread
2396 System.out.println("daemon thread work");
2397 }
2398 else{
2399 System.out.println("user thread work");
2400 }
2401 }
2402 public static void main(String[] args){
2403 TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
2404 TestDaemonThread1 t2=new TestDaemonThread1();
2405 TestDaemonThread1 t3=new TestDaemonThread1();
2406
2407 t1.setDaemon(true);//now t1 is daemon thread
2408
2409 t1.start();//starting threads
2410 t2.start();
2411 t3.start();
2412 }
2413}
2414
2415
2416
2417
241810-> A server should run for 10 secs and generate numbers continuously. The client connecting to it
2419should read data and find out the sum of the data thus read. Write a Java program to implement this scenario.?
2420
2421
2422
2423
2424
2425
2426
242711-> Java Program to Send a Message from Client to Server and Receive a Response Back Using Socket Programming?
2428
2429
2430import java.io.BufferedReader;
2431import java.io.BufferedWriter;
2432import java.io.InputStream;
2433import java.io.InputStreamReader;
2434import java.io.OutputStream;
2435import java.io.OutputStreamWriter;
2436import java.net.ServerSocket;
2437import java.net.Socket;
2438
2439public class Server
2440{
2441
2442 private static Socket socket;
2443
2444 public static void main(String[] args)
2445 {
2446 try
2447 {
2448
2449 int port = 25000;
2450 ServerSocket serverSocket = new ServerSocket(port);
2451 System.out.println("Server Started and listening to the port 25000");
2452
2453 //Server is running always. This is done using this while(true) loop
2454 while(true)
2455 {
2456 //Reading the message from the client
2457 socket = serverSocket.accept();
2458 InputStream is = socket.getInputStream();
2459 InputStreamReader isr = new InputStreamReader(is);
2460 BufferedReader br = new BufferedReader(isr);
2461 String number = br.readLine();
2462 System.out.println("Message received from client is "+number);
2463
2464 //Multiplying the number by 2 and forming the return message
2465 String returnMessage;
2466 try
2467 {
2468 int numberInIntFormat = Integer.parseInt(number);
2469 int returnValue = numberInIntFormat*2;
2470 returnMessage = String.valueOf(returnValue) + "\n";
2471 }
2472 catch(NumberFormatException e)
2473 {
2474 //Input was not a number. Sending proper message back to client.
2475 returnMessage = "Please send a proper number\n";
2476 }
2477
2478 //Sending the response back to the client.
2479 OutputStream os = socket.getOutputStream();
2480 OutputStreamWriter osw = new OutputStreamWriter(os);
2481 BufferedWriter bw = new BufferedWriter(osw);
2482 bw.write(returnMessage);
2483 System.out.println("Message sent to the client is "+returnMessage);
2484 bw.flush();
2485 }
2486 }
2487 catch (Exception e)
2488 {
2489 e.printStackTrace();
2490 }
2491 finally
2492 {
2493 try
2494 {
2495 socket.close();
2496 }
2497 catch(Exception e){}
2498 }
2499 }
2500}
2501
2502
2503
2504import java.io.BufferedReader;
2505import java.io.BufferedWriter;
2506import java.io.InputStream;
2507import java.io.InputStreamReader;
2508import java.io.OutputStream;
2509import java.io.OutputStreamWriter;
2510import java.net.InetAddress;
2511import java.net.Socket;
2512
2513public class Client
2514{
2515
2516 private static Socket socket;
2517
2518 public static void main(String args[])
2519 {
2520 try
2521 {
2522 String host = "localhost";
2523 int port = 25000;
2524 InetAddress address = InetAddress.getByName(host);
2525 socket = new Socket(address, port);
2526
2527 //Send the message to the server
2528 OutputStream os = socket.getOutputStream();
2529 OutputStreamWriter osw = new OutputStreamWriter(os);
2530 BufferedWriter bw = new BufferedWriter(osw);
2531
2532 String number = "2";
2533
2534 String sendMessage = number + "\n";
2535 bw.write(sendMessage);
2536 bw.flush();
2537 System.out.println("Message sent to the server : "+sendMessage);
2538
2539 //Get the return message from the server
2540 InputStream is = socket.getInputStream();
2541 InputStreamReader isr = new InputStreamReader(is);
2542 BufferedReader br = new BufferedReader(isr);
2543 String message = br.readLine();
2544 System.out.println("Message received from the server : " +message);
2545 }
2546 catch (Exception exception)
2547 {
2548 exception.printStackTrace();
2549 }
2550 finally
2551 {
2552 //Closing the socket
2553 try
2554 {
2555 socket.close();
2556 }
2557 catch(Exception e)
2558 {
2559 e.printStackTrace();
2560 }
2561 }
2562 }
2563}
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
258211-> A java program to implement an echo UDP server?
2583
2584
2585
2586import java.net.*;
2587import java.util.*;
2588
2589public class ClientEcho
2590{
2591 public static void main( String args[] ) throws Exception
2592 {
2593 InetAddress add = InetAddress.getByName("snrao");
2594
2595 DatagramSocket dsock = new DatagramSocket( );
2596 String message1 = "This is client calling";
2597 byte arr[] = message1.getBytes( );
2598 DatagramPacket dpack = new DatagramPacket(arr, arr.length, add, 7);
2599 dsock.send(dpack); // send the packet
2600 Date sendTime = new Date(); // note the time of sending the message
2601
2602 dsock.receive(dpack); // receive the packet
2603 String message2 = new String(dpack.getData( ));
2604 Date receiveTime = new Date( ); // note the time of receiving the message
2605 System.out.println((receiveTime.getTime( ) - sendTime.getTime( )) + " milliseconds echo time for " + message2);
2606 }
2607}
2608
2609
2610import java.net.*;
2611import java.util.*;
2612public class ServerEcho
2613{
2614 public static void main( String args[]) throws Exception
2615 {
2616 DatagramSocket dsock = new DatagramSocket(7);
2617 byte arr1[] = new byte[150];
2618 DatagramPacket dpack = new DatagramPacket(arr1, arr1.length );
2619
2620 while(true)
2621 {
2622 dsock.receive(dpack);
2623
2624 byte arr2[] = dpack.getData();
2625 int packSize = dpack.getLength();
2626 String s2 = new String(arr2, 0, packSize);
2627
2628 System.out.println( new Date( ) + " " + dpack.getAddress( ) + " : " + dpack.getPort( ) + " "+ s2);
2629 dsock.send(dpack);
2630 }
2631 } }
2632
2633
2634
2635
263612-> Random number generation in java?
2637
2638import java.util.*;
2639
2640class RandomNumbers {
2641 public static void main(String[] args) {
2642 int c;
2643 Random t = new Random();
2644
2645 // random integers in [0, 100]
2646
2647 for (c = 1; c <= 10; c++) {
2648 System.out.println(t.nextInt(100));
2649 }
2650 }
2651}
2652
2653
2654
2655
2656
2657Question-Client which sends a text and server recieves it??
2658
2659
2660File: MyServer.java
2661
2662import java.io.*;
2663import java.net.*;
2664public class MyServer {
2665public static void main(String[] args){
2666try{
2667ServerSocket ss=new ServerSocket(6666);
2668Socket s=ss.accept();//establishes connection
2669DataInputStream dis=new DataInputStream(s.getInputStream());
2670String str=(String)dis.readUTF();
2671System.out.println("message= "+str);
2672ss.close();
2673}catch(Exception e){System.out.println(e);}
2674}
2675}
2676File: MyClient.java
2677
2678import java.io.*;
2679import java.net.*;
2680public class MyClient {
2681public static void main(String[] args) {
2682try{
2683Socket s=new Socket("localhost",6666);
2684DataOutputStream dout=new DataOutputStream(s.getOutputStream());
2685dout.writeUTF("Hello Server");
2686dout.flush();
2687dout.close();
2688s.close();
2689}catch(Exception e){System.out.println(e);}
2690}
2691}
2692
2693
2694Question-URL listing
2695
2696
2697//URLDemo.java
2698import java.io.*;
2699import java.net.*;
2700public class URLDemo{
2701public static void main(String[] args){
2702try{
2703URL url=new URL("http://www.javatpoint.com/java-tutorial");
2704
2705System.out.println("Protocol: "+url.getProtocol());
2706System.out.println("Host Name: "+url.getHost());
2707System.out.println("Port Number: "+url.getPort());
2708System.out.println("File Name: "+url.getFile());
2709
2710}catch(Exception e){System.out.println(e);}
2711}
2712}
2713
2714
2715
2716Question-Displaying all the contents of the web page???
2717
2718
2719import java.io.*;
2720import java.net.*;
2721public class URLConnectionExample {
2722public static void main(String[] args){
2723try{
2724URL url=new URL("http://www.javatpoint.com/java-tutorial");
2725URLConnection urlcon=url.openConnection();
2726InputStream stream=urlcon.getInputStream();
2727int i;
2728while((i=stream.read())!=-1){
2729System.out.print((char)i);
2730}
2731}catch(Exception e){System.out.println(e);}
2732}
2733}
2734
2735
2736
27374.Getting header of the URL?
2738
2739
2740import java.io.*;
2741import java.net.*;
2742public class HttpURLConnectionDemo{
2743public static void main(String[] args){
2744try{
2745URL url=new URL("http://www.javatpoint.com/java-tutorial");
2746HttpURLConnection huc=(HttpURLConnection)url.openConnection();
2747for(int i=1;i<=8;i++){
2748System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));
2749}
2750huc.disconnect();
2751}catch(Exception e){System.out.println(e);}
2752}
2753}
2754
2755
2756
2757
2758Question-InetAddress class ?
2759
2760
2761import java.io.*;
2762import java.net.*;
2763public class InetDemo{
2764public static void main(String[] args){
2765try{
2766InetAddress ip=InetAddress.getByName("www.javatpoint.com");
2767
2768System.out.println("Host Name: "+ip.getHostName());
2769System.out.println("IP Address: "+ip.getHostAddress());
2770}catch(Exception e){System.out.println(e);}
2771}
2772}
2773
2774
2775
2776Question-Datagram socket class?
2777
2778
2779import java.net.*;
2780public class DSender{
2781 public static void main(String[] args) throws Exception {
2782 DatagramSocket ds = new DatagramSocket();
2783 String str = "Welcome java";
2784 InetAddress ip = InetAddress.getByName("127.0.0.1");
2785
2786 DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
2787 ds.send(dp);
2788 ds.close();
2789 }
2790}
2791
2792Example of Receiving DatagramPacket by DatagramSocket
2793
2794//DReceiver.java
2795import java.net.*;
2796public class DReceiver{
2797 public static void main(String[] args) throws Exception {
2798 DatagramSocket ds = new DatagramSocket(3000);
2799 byte[] buf = new byte[1024];
2800 DatagramPacket dp = new DatagramPacket(buf, 1024);
2801 ds.receive(dp);
2802 String str = new String(dp.getData(), 0, dp.getLength());
2803 System.out.println(str);
2804 ds.close();
2805 }
2806
2807
2808Question-The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting, and then waits for a response.
2809
2810
2811
2812
2813// File Name GreetingClient.java
2814
2815import java.net.*;
2816import java.io.*;
2817
2818public class GreetingClient
2819{
2820 public static void main(String [] args)
2821 {
2822 String serverName = args[0];
2823 int port = Integer.parseInt(args[1]);
2824 try
2825 {
2826 System.out.println("Connecting to " + serverName +
2827 " on port " + port);
2828 Socket client = new Socket(serverName, port);
2829 System.out.println("Just connected to "
2830 + client.getRemoteSocketAddress());
2831 OutputStream outToServer = client.getOutputStream();
2832 DataOutputStream out = new DataOutputStream(outToServer);
2833 out.writeUTF("Hello from "
2834 + client.getLocalSocketAddress());
2835 InputStream inFromServer = client.getInputStream();
2836 DataInputStream in =
2837 new DataInputStream(inFromServer);
2838 System.out.println("Server says " + in.readUTF());
2839 client.close();
2840 }catch(IOException e)
2841 {
2842 e.printStackTrace();
2843 }
2844 }
2845}
2846Socket Server Example:
2847The following GreetingServer program is an example of a server application that uses the Socket class to listen for clients on a port number specified by a command-line argument:
2848
2849// File Name GreetingServer.java
2850
2851import java.net.*;
2852import java.io.*;
2853
2854public class GreetingServer extends Thread
2855{
2856 private ServerSocket serverSocket;
2857
2858 public GreetingServer(int port) throws IOException
2859 {
2860 serverSocket = new ServerSocket(port);
2861 serverSocket.setSoTimeout(10000);
2862 }
2863
2864 public void run()
2865 {
2866 while(true)
2867 {
2868 try
2869 {
2870 System.out.println("Waiting for client on port " +
2871 serverSocket.getLocalPort() + "...");
2872 Socket server = serverSocket.accept();
2873 System.out.println("Just connected to "
2874 + server.getRemoteSocketAddress());
2875 DataInputStream in =
2876 new DataInputStream(server.getInputStream());
2877 System.out.println(in.readUTF());
2878 DataOutputStream out =
2879 new DataOutputStream(server.getOutputStream());
2880 out.writeUTF("Thank you for connecting to "
2881 + server.getLocalSocketAddress() + "\nGoodbye!");
2882 server.close();
2883 }catch(SocketTimeoutException s)
2884 {
2885 System.out.println("Socket timed out!");
2886 break;
2887 }catch(IOException e)
2888 {
2889 e.printStackTrace();
2890 break;
2891 }
2892 }
2893 }
2894 public static void main(String [] args)
2895 {
2896 int port = Integer.parseInt(args[0]);
2897 try
2898 {
2899 Thread t = new GreetingServer(port);
2900 t.start();
2901 }catch(IOException e)
2902 {
2903 e.printStackTrace();
2904 }
2905 }
2906}
2907Compile client and server and then start server as follows:
2908
2909
2910
2911
2912Question- Wap to check whether Ipv4 or Ipv6 address?
2913
2914
2915import java.net.*;
2916import java.util.*;
2917import java.lang.*;
2918public class ipvi
2919{
2920public static void main(String args[])throws UnknownHostException
2921{
2922InetAddress Address=InetAddress.getLocalHost();
2923System.out.println(Address.getHostAddress());
2924if(Address instanceof InetAddress)
2925{
2926System.out.println("......IPV4ADDRESS");
2927}
2928else
2929{
2930System.out.println(".....IPV6ADDRESS");
2931}
2932}
2933}
2934
2935
2936
2937Question-WAP to display parts of URL.
2938
2939import java.io.*;
2940import java.net.*;
2941import java.util.*;
2942
2943class UrlParts
2944{
2945 public static void main(String args[])
2946 {
2947 try
2948 {
2949 URL u = new URL("http://academics.vit.ac.in");
2950 System.out.println("Protocol="+u.getProtocol());
2951 System.out.println("Port="+u.getPort());
2952 System.out.println("Default port="+u.getDefaultPort());
2953 System.out.println("File="+u.getFile());
2954 System.out.println("Path="+u.getPath());
2955 System.out.println("Refference="+u.getRef());
2956 }
2957 catch(Exception e)
2958 {
2959 System.out.println("Error");
2960 }
2961 }
2962}
2963
2964
2965
2966Question- Write a program to list all ports hosting a TCP server in a specified host and identify
2967available servers in well-known ports?
2968
2969import java.net.*;
2970import java.io.*;
2971public class ports{
2972public static void main(String args[])
2973{
2974for(int i=1; i++)
2975{
2976try{
2977Socket s=new Socket("127.0.0.1",i);
2978System.out.println("There is server on port"+i+"of 127.0.0.1");
2979}
2980catch(UnknownHostException e){
2981System.err.println(e);
2982break;
2983}
2984catch(IOException e){
2985}}}}
2986
2987
2988Question- Find which out of the first 1024 ports seems to be hosted tcp srevers on a specified host?
2989(Local host can be default)
2990
2991
2992import java.net.*;
2993import java.io.*;
2994public class portsB{
2995public static void main(String args[])
2996{
2997for(int i=1; i<1024; i++)
2998{
2999try{
3000Socket s=new Socket("127.0.0.1",i);
3001System.out.println("There is server on port"+i+"of 127.0.0.1");
3002}
3003catch(UnknownHostException e){
3004System.err.println(e);
3005break;
3006}
3007catch(IOException e){
3008}}}}
3009
3010
3011
3012Question- Find out which of the ports are above 1024 that seems to be hosted tcp
3013servers on a specified host?
3014
3015import java.net.*;
3016import java.io.*;
3017public class portsB{
3018public static void main(String args[])
3019{
3020for(int i=1024; ; i++)
3021{
3022try{
3023Socket s=new Socket("127.0.0.1",i);
3024System.out.println("There is server on port"+i+"of 127.0.0.1");
3025}
3026catch(UnknownHostException e){
3027System.err.println(e);
3028break;
3029}
3030catch(IOException e){
3031}}}}
3032
3033
3034
3035Question- How to check whether a port is being used or not ?
3036
3037Solution
3038Following example shows how to check whether any port is being used as a server or not by creating a socket object.
3039
3040import java.net.*;
3041import java.io.*;
3042
3043public class Main {
3044 public static void main(String[] args) {
3045 Socket Skt;
3046 String host = "localhost";
3047
3048 if (args.length > 0) {
3049 host = args[0];
3050 }
3051 for (int i = 0; i < 1024; i++) {
3052 try {
3053 System.out.println("Looking for "+ i);
3054 Skt = new Socket(host, i);
3055 System.out.println("There is a server on port " + i + " of " + host);
3056 } catch (UnknownHostException e) {
3057 System.out.println("Exception occured"+ e);
3058 break;
3059 } catch (IOException e) {}
3060 }
3061 }
3062}
3063
3064
3065Implement echo server and client in java using UDP sockets.
3066Code:
3067Server:
3068import java.io.*;
3069import java.net.*;
3070class UDPServer {
3071public static void main(String args[]) throws Exception
3072{
3073DatagramSocket serverSocket = new DatagramSocket(9876);
3074byte[] receiveData = new byte[1024];
3075byte[] sendData = new byte[1024];
3076while(true)
3077{
3078DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
3079serverSocket.receive(receivePacket);
3080String sentence = new String(receivePacket.getData());
3081InetAddress IPAddress = receivePacket.getAddress();
3082int port = receivePacket.getPort();
3083String capitalizedSentence = sentence.toUpperCase();
3084sendData = capitalizedSentence.getBytes();
3085DatagramPacket sendPacket =new DatagramPacket(sendData, sendData.length, IPAddress,port);
3086serverSocket.send(sendPacket);
3087}
3088}
3089}
3090
3091Client
3092import java.io.*;
3093import java.net.*;
3094
3095class UDPClient {
3096public static void main(String args[]) throws Exception
3097{
3098BufferedReader inFromUser =
3099new BufferedReader(new InputStreamReader(System.in));
3100DatagramSocket clientSocket = new DatagramSocket();
3101InetAddress IPAddress = InetAddress.getByName("");
3102byte[] sendData = new byte[1024];
3103byte[] receiveData = new byte[1024];
3104String sentence = inFromUser.readLine();
3105sendData = sentence.getBytes();
3106DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
3107clientSocket.send(sendPacket);
3108DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
3109clientSocket.receive(receivePacket);
3110String modifiedSentence = new String(receivePacket.getData());
3111System.out.println("FROM SERVER:" + modifiedSentence);
3112clientSocket.close();
3113}
3114}
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140Q. Write a program to implement a text based message transfer from client to server process using UDP.
3141
3142Code:
3143Server:
3144import java.net.DatagramPacket;
3145import java.net.DatagramSocket;
3146public class UDPaServer
3147{
3148 public static void main(String args[])
3149 {
3150 int server_port = 1111;
3151 System.out.println("UDP Server Listening in " + server_port);
3152 try
3153 {
3154 // DatagramSocket created and listening in Port 1111
3155 DatagramSocket socket = new DatagramSocket(server_port);
3156 byte[] msgBuffer = new byte[1024];
3157
3158 // DatagramPacket for receiving the incoming data from UDP Client
3159 DatagramPacket packet = new DatagramPacket(msgBuffer, msgBuffer.length);
3160
3161 while (true)
3162 {
3163 socket.receive(packet);
3164 String message = new String(msgBuffer, 0, packet.getLength());
3165 System.out.println("UDPServer: Message received = " + message);
3166 packet.setLength(msgBuffer.length);
3167 }
3168 }
3169 catch (Exception e)
3170 {
3171 e.printStackTrace();
3172 System.out.println("Error in getting the Data from UDP Client");
3173 }
3174 }
3175}
3176
3177Client:
3178import java.net.DatagramPacket;
3179import java.net.DatagramSocket;
3180import java.net.InetAddress;
3181import java.io.*;
3182import java.net.*;
3183
3184public class UDPaClient
3185{
3186 public static void main(String args[])
3187 {
3188 try
3189 {
3190 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
3191 String server_address = "localhost";
3192 int server_port = 1111;
3193 String message = inFromUser.readLine();
3194 InetAddress address = InetAddress.getByName(server_address);
3195 DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, address, server_port);
3196 DatagramSocket socket = new DatagramSocket();
3197 socket.send(packet);
3198
3199 System.out.println("UDPClient: Sent data to Server ; Message = " + message);
3200 socket.close();
3201 }
3202 catch (Exception e)
3203 {
3204 e.printStackTrace();
3205 System.out.println("Error in sending the Data to UDP Server");
3206 }
3207 }
3208}
3209
3210
3211
3212
3213Q. Implement a chat server and client in java using UDP sockets.
3214
3215Code:
3216Server:
3217import java.net.DatagramPacket;
3218import java.net.DatagramSocket;
3219import java.net.InetAddress;
3220public class Server {
3221private static DatagramSocket serverSocket;
3222public static void main(String[] args) throws Exception {
3223serverSocket = new DatagramSocket(1111);
3224byte[] receiveData = new byte[1024];
3225byte[] sendData = new byte[1024];
3226 while(true)
3227 {
3228 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
3229 serverSocket.receive(receivePacket);
3230 String s = new String( receivePacket.getData());
3231 System.out.println("Client : " + s);
3232 InetAddress IPAddress = receivePacket.getAddress();
3233 boolean found = false;
3234 int port = receivePacket.getPort();
3235 sendData = s.getBytes();
3236 }
3237 }
3238}
3239Client
3240import java.io.BufferedReader;
3241import java.io.InputStreamReader;
3242import java.net.DatagramPacket;
3243import java.net.DatagramSocket;
3244import java.net.InetAddress;
3245public class ClientX
3246 {
3247public static void main(String[] args) throws Exception {
3248 BufferedReader inFromUser =
3249 new BufferedReader(new InputStreamReader(System.in));
3250 DatagramSocket clientSocket = new DatagramSocket();
3251 InetAddress IPAddress = InetAddress.getByName("localhost");
3252 System.out.println("Connect to Server");
3253 byte[] sendData = new byte[1024];
3254 byte[] receiveData = new byte[1024];
3255 System.out.print("Enter The message: ");
3256 String s = inFromUser.readLine();
3257 sendData = s.getBytes();
3258 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 1111);
3259 clientSocket.send(sendPacket);
3260 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
3261 clientSocket.receive(receivePacket);
3262 String message = new String(receivePacket.getData());
3263 System.out.println(message);
3264 clientSocket.close();
3265}
3266}
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276Q. Implement a DNS server and client in java using UDP sockets.
3277Code:
3278Server
3279import java.io.*;
3280import java.net.*;
3281import java.util.*;
3282class Serverdns12
3283{
3284 public static void main(String args[])
3285 {
3286 try
3287 {
3288 DatagramSocket server=new DatagramSocket(1309);
3289 while(true)
3290 {
3291 byte[] sendbyte=new byte[1024];
3292 byte[] receivebyte=new byte[1024];
3293 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
3294 server.receive(receiver);
3295 String str=new String(receiver.getData());
3296 String s=str.trim();
3297 //System.out.println(s);
3298 InetAddress addr=receiver.getAddress();
3299 int port=receiver.getPort();
3300 String ip[]={"165.165.80.80","165.165.79.1"};
3301 String name[]={"www.google.com","www.yahoo.com"};
3302 for(int i=0;i<ip.length;i++)
3303 {
3304 if(s.equals(ip[i]))
3305 {
3306 sendbyte=name[i].getBytes();
3307 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
3308 server.send(sender);
3309 break;
3310 }
3311 else if(s.equals(name[i]))
3312 {
3313 sendbyte=ip[i].getBytes();
3314 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
3315 server.send(sender);
3316 break;
3317 }
3318
3319 }
3320 break;
3321}
3322 }
3323 catch(Exception e)
3324 {
3325 System.out.println(e);
3326 }
3327 }
3328}
3329
3330
3331
3332
3333
3334
3335Client:
3336import java.io.*;
3337import java.net.*;
3338import java.util.*;
3339class Clientdns12
3340{
3341 public static void main(String args[])
3342 {
3343 try
3344 {
3345 DatagramSocket client=new DatagramSocket();
3346 InetAddress addr=InetAddress.getByName("127.0.0.1");
3347
3348 byte[] sendbyte=new byte[1024];
3349 byte[] receivebyte=new byte[1024];
3350 BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
3351 System.out.println("Enter the DOMAIN NAME or IP adress:");
3352 String str=in.readLine();
3353 sendbyte=str.getBytes();
3354 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,1309);
3355 client.send(sender);
3356 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
3357 client.receive(receiver);
3358 String s=new String(receiver.getData());
3359 System.out.println("IP address or DOMAIN NAME: "+s.trim());
3360 client.close();
3361 }
3362 catch(Exception e)
3363 {
3364 System.out.println(e);
3365 }
3366 }
3367}
3368
3369
3370
3371
3372Q.Find the logical address of a host when its physical address is known (RARP protocol) using UDP.
3373
3374Code:
3375Server:
3376import java.io.*;
3377import java.net.*;
3378import java.util.*;
3379class Serverarp12
3380{
3381 public static void main(String args[])
3382 {
3383 try
3384 {
3385 DatagramSocket server=new DatagramSocket(1309);
3386 while(true)
3387 {
3388 byte[] sendbyte=new byte[1024];
3389 byte[] receivebyte=new byte[1024];
3390 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
3391 server.receive(receiver);
3392 String str=new String(receiver.getData());
3393 String s=str.trim();
3394 //System.out.println(s);
3395 InetAddress addr=receiver.getAddress();
3396 int port=receiver.getPort();
3397 String ip[]={"165.165.80.80","165.165.79.1"};
3398 String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
3399 for(int i=0;i<mac.length;i++)
3400 {
3401 if(s.equals(mac[i]))
3402 {
3403 sendbyte=ip[i].getBytes();
3404 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
3405 server.send(sender);
3406 break;
3407 }
3408 }
3409 break;
3410
3411
3412 }
3413 }
3414 catch(Exception e)
3415 {
3416 System.out.println(e);
3417 }
3418 }
3419}
3420
3421Client
3422import java.io.*;
3423import java.net.*;
3424import java.util.*;
3425class Clientarp12
3426{
3427 public static void main(String args[])
3428 {
3429 try
3430 {
3431 DatagramSocket client=new DatagramSocket();
3432 InetAddress addr=InetAddress.getByName("127.0.0.1");
3433
3434 byte[] sendbyte=new byte[1024];
3435 byte[] receivebyte=new byte[1024];
3436 BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
3437 System.out.println("Enter the Physical Address:");
3438 String str=in.readLine();
3439 sendbyte=str.getBytes();
3440 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,1309);
3441 client.send(sender);
3442 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
3443 client.receive(receiver);
3444 String s=new String(receiver.getData());
3445 System.out.println("The Logical Address is(IP): "+s.trim());
3446 client.close();
3447 }
3448 catch(Exception e)
3449 {
3450 System.out.println(e);
3451 }
3452 }
3453}
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472Q. Find the physical address of a host when its logical address is known (ARP protocol) using UDP.
3473Code:
3474Server:
3475
3476import java.io.*;
3477import java.net.*;
3478import java.util.*;
3479class Serverarp12
3480{
3481 public static void main(String args[])
3482 {
3483 try
3484 {
3485 DatagramSocket server=new DatagramSocket(1309);
3486 while(true)
3487 {
3488 byte[] sendbyte=new byte[1024];
3489 byte[] receivebyte=new byte[1024];
3490 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
3491 server.receive(receiver);
3492 String str=new String(receiver.getData());
3493 String s=str.trim();
3494 //System.out.println(s);
3495 InetAddress addr=receiver.getAddress();
3496 int port=receiver.getPort();
3497 String ip[]={"165.165.80.80","165.165.79.1"};
3498 String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
3499 for(int i=0;i<ip.length;i++)
3500 {
3501 if(s.equals(ip[i]))
3502 {
3503 sendbyte=mac[i].getBytes();
3504 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
3505 server.send(sender);
3506 break;
3507 }
3508 }
3509 break;
3510
3511
3512 }
3513 }
3514 catch(Exception e)
3515 {
3516 System.out.println(e);
3517 }
3518 }
3519}
3520
3521Client
3522import java.io.*;
3523import java.net.*;
3524import java.util.*;
3525class Clientarp12
3526{
3527 public static void main(String args[])
3528 {
3529 try
3530 {
3531 DatagramSocket client=new DatagramSocket();
3532 InetAddress addr=InetAddress.getByName("127.0.0.1");
3533
3534 byte[] sendbyte=new byte[1024];
3535 byte[] receivebyte=new byte[1024];
3536 BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
3537 System.out.println("Enter the logical address (IP):");
3538 String str=in.readLine();
3539 sendbyte=str.getBytes();
3540 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,1309);
3541 client.send(sender);
3542 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
3543 client.receive(receiver);
3544 String s=new String(receiver.getData());
3545 System.out.println("The Physical Address is(MAC): "+s.trim());
3546 client.close();
3547 }
3548 catch(Exception e)
3549 {
3550 System.out.println(e);
3551 }
3552 }
3553}
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569Q.Implement Client - Server communication to access Date using UDP in Java.
3570
3571Server:
3572import java.net.*;
3573import java.io.*;
3574import java.util.*;
3575
3576class DateServer
3577{
3578 public static void main(String args[]) throws Exception
3579 {
3580 ServerSocket s=new ServerSocket(5217);
3581
3582 while(true)
3583 {
3584 System.out.println("Waiting For Connection ...");
3585 Socket soc=s.accept();
3586 DataOutputStream out=new DataOutputStream(soc.getOutputStream());
3587 out.writeBytes("Server Date" + (new Date()).toString() + "\n");
3588 out.close();
3589 soc.close();
3590 }
3591
3592 }
3593}
3594
3595Client
3596import java.io.*;
3597import java.net.*;
3598
3599class DateClient
3600{
3601 public static void main(String args[]) throws Exception
3602 {
3603 Socket soc=new Socket(InetAddress.getLocalHost(),5217);
3604 BufferedReader in=new BufferedReader(
3605 new InputStreamReader(
3606 soc.getInputStream()
3607 )
3608 );
3609
3610 System.out.println(in.readLine());
3611 }
3612}
3613
3614cycle sheet 2)
3615
3616QUESTION 6)
3617Implement a chat server and client in java using TCP sockets
3618
3619
3620import java.io.*;
3621
3622import java.net.*;
3623
3624public class GossipServer
3625
3626{
3627
3628 public static void main(String[] args) throws Exception
3629
3630 {
3631
3632 ServerSocket sersock = new ServerSocket(3000);
3633
3634 System.out.println("Server ready for chatting");
3635
3636 Socket sock = sersock.accept( );
3637
3638 // reading from keyboard (keyRead object)
3639
3640 BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
3641
3642 // sending to client (pwrite object)
3643
3644 OutputStream ostream = sock.getOutputStream();
3645
3646 PrintWriter pwrite = new PrintWriter(ostream, true);
3647
3648
3649
3650 // receiving from server ( receiveRead object)
3651
3652 InputStream istream = sock.getInputStream();
3653
3654 BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
3655
3656
3657
3658 String receiveMessage, sendMessage;
3659
3660 while(true)
3661
3662 {
3663
3664 if((receiveMessage = receiveRead.readLine()) != null)
3665
3666 {
3667
3668 System.out.println(receiveMessage);
3669
3670 }
3671
3672 sendMessage = keyRead.readLine();
3673
3674 pwrite.println(sendMessage);
3675
3676 pwrite.flush();
3677
3678 }
3679
3680 }
3681
3682}
3683
3684
3685
3686
3687
3688/Client
3689
3690import java.io.*;
3691
3692import java.net.*;
3693
3694public class GossipClient
3695
3696{
3697
3698 public static void main(String[] args) throws Exception
3699
3700 {
3701
3702 Socket sock = new Socket("127.0.0.1", 3000);
3703
3704 // reading from keyboard (keyRead object)
3705
3706 BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
3707
3708 // sending to client (pwrite object)
3709
3710 OutputStream ostream = sock.getOutputStream();
3711
3712 PrintWriter pwrite = new PrintWriter(ostream, true);
3713
3714
3715
3716 // receiving from server ( receiveRead object)
3717
3718 InputStream istream = sock.getInputStream();
3719
3720 BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
3721
3722
3723
3724 System.out.println("Start the chitchat, type and press Enter key");
3725
3726
3727
3728 String receiveMessage, sendMessage;
3729
3730 while(true)
3731
3732 {
3733
3734 sendMessage = keyRead.readLine(); // keyboard reading
3735
3736 pwrite.println(sendMessage); // sending to server
3737
3738 pwrite.flush(); // flush the data
3739
3740 if((receiveMessage = receiveRead.readLine()) != null) //receive from server
3741
3742 {
3743
3744 System.out.println(receiveMessage); // displaying at DOS prompt
3745
3746 }
3747
3748 }
3749
3750 }
3751
3752}
3753
3754
3755QUESTION 8)
3756
3757Find the physical address of a host when its logical address is known (ARP protocol) using TCP/IP.
3758
3759 server.java
3760import java.io.*;
3761import java.util.*;
3762import java.net.*;
3763
3764public class server
3765{
3766public static void main(String[] args)
3767{
3768try
3769{
3770ServerSocket ss = new ServerSocket(5555);
3771Socket s = ss.accept();
3772BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
3773DataOutputStream dout = new DataOutputStream(s.getOutputStream());
3774DataInputStream din = new DataInputStream(s.getInputStream());
3775String str = din.readLine();
3776String logical[] = {"172.16.27.34","195.24.54.204"};
3777String physical[] = {"8E:AE:08:AA","0A:78:6C:AD"};
3778for(int i=0;i<logical.length;i++)
3779{
3780if (str.equals(logical[i]))
3781{
3782dout.writeBytes(physical[i] + "\n");
3783break;
3784}
3785}
3786s.close();
3787}
3788catch (Exception e)
3789{
3790}
3791}
3792}
3793 client.java
3794import java.io.*;
3795import java.util.*;
3796import java.net.*;
3797
3798public class client
3799{
3800public static void main(String[] args)
3801{
3802try
3803{
3804Socket s = new Socket("localhost",5555);
3805BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
3806DataOutputStream dout = new DataOutputStream(s.getOutputStream());
3807DataInputStream din = new DataInputStream(s.getInputStream());
3808System.out.println("Enter the logical address: ");
3809String str = b.readLine();
3810dout.writeBytes(str + "\n");
3811String str1 = din.readLine();
3812System.out.println("Physical Address of str: " + str1);
3813s.close();
3814}
3815catch (Exception e)
3816{
3817}
3818}
3819}
3820
3821
3822
3823QUESTION 9)
3824Find the logical address of a host when its physical address is known (RARP protocol) using TCP/IP.
3825
3826
3827 //TCPLogServer.java
3828import java.io.*;
3829import java.net.*;
3830
3831class TCPLogServer {
3832
3833 public static void main(String argv[]) throws Exception
3834 {
3835 String phyAdd;
3836
3837
3838 ServerSocket welcomeSocket = new ServerSocket(6789);
3839
3840 while(true) {
3841
3842 Socket connectionSocket = welcomeSocket.accept();
3843
3844 BufferedReader inFromClient =
3845 new BufferedReader(new
3846 InputStreamReader(connectionSocket.getInputStream()));
3847
3848
3849 String logical[] = {"172.16.27.34","195.24.54.204", "10.10.137.1"};
3850 String physical[] = {"8E:AE:08:AA","0A:78:6C:AD", "d4:6d:50:84:db:c8"};
3851
3852 DataOutputStream outToClient =
3853 new DataOutputStream(connectionSocket.getOutputStream());
3854
3855 phyAdd = inFromClient.readLine();
3856 for(int i = 0; i < physical.length; i++)
3857 {
3858 if (phyAdd.equals(physical[i]))
3859 {
3860 outToClient.writeBytes(logical[i] + "\n");
3861 connectionSocket.close();
3862 }
3863 }
3864
3865
3866 }
3867 }
3868}
3869
3870 TCPLogClient.java
3871
3872import java.io.*;
3873import java.net.*;
3874class TCPLogClient {
3875
3876 public static void main(String argv[]) throws Exception
3877 {
3878 String logicAdd;
3879 String phyAdd;
3880
3881 BufferedReader inFromUser =
3882 new BufferedReader(new InputStreamReader(System.in));
3883
3884 Socket clientSocket = new Socket("localhost", 6789);
3885
3886 DataOutputStream outToServer =
3887 new DataOutputStream(clientSocket.getOutputStream());
3888
3889 BufferedReader inFromServer =
3890 new BufferedReader(new
3891 InputStreamReader(clientSocket.getInputStream()));
3892
3893 System.out.println("Enter Physical address of host");
3894 phyAdd = inFromUser.readLine();
3895
3896 outToServer.writeBytes(phyAdd + '\n');
3897
3898 logicAdd = inFromServer.readLine();
3899
3900 System.out.println("FROM SERVER: Logical Address " + logicAdd);
3901
3902 clientSocket.close();
3903
3904 }
3905}
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928QUESTION 10)
3929
3930Implement Domain Name System (DNS) using TCP/IP
3931
3932
3933import java.io.*;
3934import java.util.*;
3935import java.net.InetAddress;
3936import java.net.UnknownHostException;
3937public class dns
3938{
3939public static void main(String args[])throws Exception
3940{
3941try
3942{
3943System.out.println("Enter IP address: ");
3944BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
3945String ip=br.readLine();
3946InetAddress host=InetAddress.getByName(ip);
3947System.out.println("Host name is: ");
3948System.out.println(host.getHostName());
3949}
3950catch(Exception e)
3951{
3952//e.printStackTrace();
3953System.out.println(e);
3954}
3955}
3956
3957
3958Question 11)
3959
3960
396111.Implement a TCP/IP based Server program in Java to compute the factorial of a number (can contain arbitrary number of digits). Write a client program to test the working of the same
3962
3963import java.io.*;
3964import java.net.*;
3965class serv{
3966 public static void main(String argv[]) throws Exception
3967 {
3968 String clientSentence;
3969 String capitalizedSentence;
3970 ServerSocket welcomeSocket = new ServerSocket(6788);
3971 Socket connectionSocket = welcomeSocket.accept();
3972 BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
3973 DataOutputStream outToClient = new DataOutputStream (connectionSocket.getOutputStream());
3974 clientSentence = inFromClient.readLine();
3975 int num = Integer.parseInt(clientSentence);
3976 int fact=1;
3977 for(int i=1;i<=num;i++)
3978 fact=fact*i;
3979 System.out.println("Factorial : "+fact);
3980 capitalizedSentence = String.valueOf(fact);
3981 //capitalizedSentence = clientSentence.toUpperCase() + '\n';
3982 outToClient.writeBytes(capitalizedSentence);
3983 }
3984
3985
3986}
3987
3988
3989
3990
3991client
3992import java.io.*;
3993import java.net.*;
3994class Clientt {
3995 public static void main(String argv[]) throws Exception
3996 {
3997 String sentence;
3998 String modifiedSentence;
3999 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
4000 Socket clientSocket = new Socket("localhost", 6788);
4001 DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
4002 BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
4003 System.out.println("Enter a number - ");
4004 sentence = inFromUser.readLine();
4005 outToServer.writeBytes(sentence + '\n');
4006 modifiedSentence = inFromServer.readLine();
4007 System.out.println ("Factorial: " + modifiedSentence );
4008 clientSocket.close();
4009 }
4010}
4011
4012
4013
4014
4015.
4016
401712.Find the class of the IP address using TCP/IP.
4018import java.io.*;
4019import java.net.*;
4020
4021class TCPIpclassServer {
4022
4023 public static void main(String argv[]) throws Exception
4024 {
4025 String ip;
4026 int fbyte;
4027 String ipclass = "Invalid";
4028
4029
4030 ServerSocket welcomeSocket = new ServerSocket(6789);
4031
4032 while(true) {
4033
4034 Socket connectionSocket = welcomeSocket.accept();
4035
4036 BufferedReader inFromClient =
4037 new BufferedReader(new
4038 InputStreamReader(connectionSocket.getInputStream()));
4039
4040
4041 DataOutputStream outToClient =
4042 new DataOutputStream(connectionSocket.getOutputStream());
4043
4044 ip = inFromClient.readLine();
4045 int index;
4046 index = ip.indexOf(".");
4047 ip = ip.substring(0, index);
4048
4049
4050 fbyte = Integer.parseInt(ip);
4051 if (fbyte >= 0 && fbyte <= 127)
4052 ipclass = "Class A";
4053 else if (fbyte >= 128 && fbyte <= 191)
4054 ipclass = "Class B";
4055 else if (fbyte >= 192 && fbyte <= 223)
4056 ipclass = "Class C";
4057 else if (fbyte >= 224 && fbyte <= 239)
4058 ipclass = "Class D";
4059 else if (fbyte >= 240 && fbyte <= 255)
4060 ipclass = "Class E";
4061
4062 outToClient.writeBytes(ipclass + "\n");
4063 connectionSocket.close();
4064
4065 }
4066 }
4067}
4068//client
4069import java.io.*;
4070import java.net.*;
4071
4072class TCPIpclassClient {
4073
4074 public static void main(String argv[]) throws Exception
4075 {
4076 String ip;
4077 int fbyte;
4078 String ipclass = "Invalid";
4079
4080
4081 ServerSocket welcomeSocket = new ServerSocket(6789);
4082
4083 while(true) {
4084
4085 Socket connectionSocket = welcomeSocket.accept();
4086
4087 BufferedReader inFromClient =
4088 new BufferedReader(new
4089 InputStreamReader(connectionSocket.getInputStream()));
4090
4091
4092 DataOutputStream outToClient =
4093 new DataOutputStream(connectionSocket.getOutputStream());
4094
4095 ip = inFromClient.readLine();
4096 int index;
4097 index = ip.indexOf(".");
4098 ip = ip.substring(0, index);
4099
4100
4101 fbyte = Integer.parseInt(ip);
4102 if (fbyte >= 0 && fbyte <= 127)
4103 ipclass = "Class A";
4104 else if (fbyte >= 128 && fbyte <= 191)
4105 ipclass = "Class B";
4106 else if (fbyte >= 192 && fbyte <= 223)
4107 ipclass = "Class C";
4108 else if (fbyte >= 224 && fbyte <= 239)
4109 ipclass = "Class D";
4110 else if (fbyte >= 240 && fbyte <= 255)
4111 ipclass = "Class E";
4112
4113 outToClient.writeBytes(ipclass + "\n");
4114 connectionSocket.close();
4115
4116 }
4117 }
4118}
4119
41201.WAJP to display server date and time in client
4121
4122Server:
4123
4124import java.io.*;
4125import java.net.*;
4126import java.util.Date;
4127class server1 {
4128 public static void main(String argv[]) throws Exception
4129 {
4130 String capitalizedSentence;
4131 ServerSocket welcomeSocket = new ServerSocket(6789);
4132 while(true) {
4133 Socket connectionSocket = welcomeSocket.accept();
4134DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
4135 capitalizedSentence = new Date().toString() + '\n';
4136 outToClient.writeBytes(capitalizedSentence);
4137 }
4138 }
4139}
4140
4141
4142Client:
4143
4144import java.io.*;
4145import java.net.*;
4146class client1 {
4147 public static void main(String argv[]) throws Exception
4148 {
4149 String modifiedSentence;
4150 Socket clientSocket = new Socket("localhost", 6789);
4151BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
4152 modifiedSentence = inFromServer.readLine();
4153 System.out.println("FROM SERVER: " + modifiedSentence);
4154 clientSocket.close();
4155 }
4156}
4157
4158
4159
4160
41612.WAJP to display client address in server
4162Server:
4163
4164import java.io.*;
4165import java.net.*;
4166
4167class server1 {
4168 public static void main(String argv[]) throws Exception
4169 {
4170 ServerSocket welcomeSocket = new ServerSocket(6789);
4171 while(true) {
4172 Socket connectionSocket = welcomeSocket.accept();
4173 BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
4174System.out.println("Address Received from client : "+ inFromClient.readLine());
4175 }
4176 }
4177}
4178
4179
4180Client:
4181
4182import java.io.*;
4183import java.net.*;
4184class client1 {
4185 public static void main(String argv[]) throws Exception
4186 {
4187 Socket clientSocket = new Socket("localhost", 6789);
4188DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
4189 outToServer.writeBytes(InetAddress.getLocalHost().getHostAddress() + '\n');
4190 clientSocket.close();
4191
4192 }
4193}
4194
4195
4196
41974.WAJP for chat
4198SERVER
4199import java.io.*;
4200import java.net.*;
4201import java.util.*;
4202class Server
4203{
4204public static void main(String[] args)throws IOException
4205{
4206ServerSocket sr=new ServerSocket(6789);
4207while(true)
4208{
4209Socket cons=sr.accept();
4210BufferedReader incl=new BufferedReader(new InputStreamReader(cons.getInputStream()));
4211OutputStream outcl=cons.getOutputStream();
4212PrintWriter pw=new PrintWriter(outcl,true);
4213BufferedReader serin=new BufferedReader(new InputStreamReader(System.in));
4214String str=" ",str1=" ";
4215try
4216{
4217while( (str=incl.readLine())!=null)
4218{
4219System.out.println("Client:"+str);
4220str1=serin.readLine();
4221System.out.println("You:"+str1);
4222pw.println(str1);
4223}
4224}
4225catch(SocketException e)
4226{
4227System.out.println(e);
4228}
4229}
4230}
4231}
4232
4233CLIENT
4234import java.io.*;
4235import java.net.*;
4236
4237class Client
4238{
4239public static void main(String[] args)throws IOException
4240{
4241String str=" ",str1=" ";
4242int i=0;
4243Socket cls=new Socket("localhost",6789);
4244BufferedReader inser=new BufferedReader(new InputStreamReader(cls.getInputStream()));
4245OutputStream outser=cls.getOutputStream();
4246PrintWriter pw=new PrintWriter(outser,true);
4247BufferedReader clin=new BufferedReader(new InputStreamReader(System.in));
4248System.out.println("Begin chat");
4249str1=clin.readLine();
4250System.out.println("You:"+str1);
4251pw.println(str1);
4252try
4253{
4254while( (str=inser.readLine())!=null)
4255{
4256System.out.println("Server:"+str);
4257str1=clin.readLine();
4258System.out.println("You:"+str1);
4259pw.println(str1);
4260}
4261}
4262catch(SocketException e)
4263{
4264System.out.println(e);
4265}//catch
4266
4267}
4268}
4269
4270
42715.TCP/IP
4272server:
4273
4274import java.io.*;
4275import java.net.*;
4276
4277class server1 {
4278
4279 public static void main(String argv[]) throws Exception {
4280 String clientSentence;
4281 ServerSocket welcomeSocket = new ServerSocket(6789);
4282 while (true) {
4283 Socket connectionSocket = welcomeSocket.accept();
4284 BufferedReader inFromClient
4285 = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
4286 DataOutputStream outToClient
4287 = new DataOutputStream(connectionSocket.getOutputStream());
4288 clientSentence = inFromClient.readLine();
4289 System.out.println("Received from client : " + clientSentence);
4290 String a = clientSentence.toLowerCase();
4291 String b = "";//abc
4292 String x = "abcdefghijklmnopqrstuvwxyz";
4293//code to encode
4294 for (int i = 0; i < a.length(); i++) {
4295 if (a.charAt(i) == 'z') {
4296 b += 'a';
4297 } else {
4298 for (int j = 0; j < x.length(); j++) {
4299 if (x.charAt(j) == a.charAt(i)) {
4300 b += x.charAt(j + 1);
4301 break;
4302 }
4303 }
4304 }
4305 }
4306 outToClient.writeBytes(b+"\n");
4307 }
4308 }
4309}
4310
4311client:
4312
4313import java.io.*;
4314import java.net.*;
4315class client1 {
4316 public static void main(String argv[]) throws Exception {
4317 String sentence;
4318 String modifiedSentence;
4319 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
4320 Socket clientSocket = new Socket("localhost", 6789);
4321 DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
4322 BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
4323 sentence = inFromUser.readLine();
4324 outToServer.writeBytes(sentence + '\n');
4325
4326 modifiedSentence = inFromServer.readLine();
4327
4328 System.out.println("FROM SERVER: " + modifiedSentence);
4329
4330 clientSocket.close();
4331
4332 }
4333}
4334
43357.WAJP to display name and address of computer currently working on
4336import java.net.InetAddress;
4337public class pro1 {
4338 public static void main(String []args) throws Exception{
4339 InetAddress a=InetAddress.getLocalHost();
4340 System.out.println(a);
4341 }
4342}
4343
43448.IPv4 header
4345
4346
43479.Threads
4348import java.util.*;
4349/**
4350 *
4351 * @author mock3
4352 */
4353class waste extends Thread {
4354
4355 int a;
4356
4357 public void run() {
4358 try {
4359 Random r = new Random();
4360 int r1= r.nextInt(1000);
4361 if(Thread.currentThread().isDaemon()){
4362 for (a = 0; a < 4; a++) {
4363 System.out.println(a + " daemon");
4364 Thread.sleep(r1);
4365 }
4366 }
4367 else{
4368 for (a = 0; a < 4; a++) {
4369 System.out.println(a + " haha");
4370 Thread.sleep(r1);
4371 }
4372 }
4373 } catch (Exception e) {
4374
4375 }
4376 }
4377}
4378
4379public class JavaApplication2 {
4380
4381 /**
4382 * @param args the command line arguments
4383 */
4384 public static void main(String[] args) throws Exception {
4385 // TODO code application logic here
4386 waste w1 = new waste();
4387 w1.setDaemon(true);
4388 waste w2 = new waste();
4389 waste w3 = new waste();
4390 w1.start();
4391 w2.start();
4392 w3.start();
4393 }
4394
4395}
4396
439710.WAJP to run basic network commands
4398import java.net.*;
4399import java.util.*;
4400import java.io.*;
4401public class command
4402{
4403 public static void main(String args[])
4404 throws Exception
4405 {
4406 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
4407 System.out.println("enter command:");
4408 String s=br.readLine();
4409 Process p=Runtime.getRuntime().exec(s);
4410 p.waitFor();
4411 BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
4412 String line=reader.readLine();
4413 while(line!=null)
4414 {
4415 System.out.println(line);
4416 line=reader.readLine();0
4417 }
4418 System.out.println("done!");
4419
4420}
4421}
4422
4423
4424
4425
44261- Wap to display server's date and time details at the client end.
4427
4428DateClient.java
4429import java.io.*;
4430import java.net.Socket;
4431public class dateClient {
4432public static void main(String[] args) throws IOException {
4433Socket s = new Socket("127.0.0.1",9090);
4434BufferedReader input = new BufferedReader(new
4435InputStreamReader(s.getInputStream()));
4436String answer = input.readLine();
4437System.out.println("The date and time details are"+answer);
4438System.exit(0);
4439}
4440
4441
4442
4443DATESERVER.java
4444
4445import java.io.IOException;
4446import java.io.PrintWriter;
4447import java.net.ServerSocket;
4448import java.net.Socket;
4449import java.util.Date;
4450public class dateserver {
4451public static void main(String[] args) throws IOException {
4452ServerSocket listener = new ServerSocket(9090);
4453try {
4454while(true) {
4455Socket socket = listener.accept();
4456try {
4457PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
4458out.println(new Date().toString());
4459}finally {
4460socket.close();
4461}
4462}
4463}
4464finally {
4465listener.close();
4466}
4467}
4468}
4469
4470
4471
44722-> Wap to display the client's address at the server end?
4473
4474import java.io.*;
4475import java.net.*;
4476public class ServerAddr {
4477public static void main(String[] args) throws IOException {
4478try {
4479ServerSocket ss = new ServerSocket(6666);
4480System.out.println("Waiting for client....");
4481Socket s = ss.accept();
4482System.out.println("Connected to client....");
4483DataInputStream in = new DataInputStream(s.getInputStream());
4484String line = null;
4485line = in.readUTF();
4486System.out.println("Client's IP address:" + line);
4487}
4488catch(Exception e) {
4489e.printStackTrace();
4490}}}
4491
4492
4493import java.io.*;
4494import java.net.*;
4495public class ClientAddr {
4496public static void main(String[] args) throws IOException {
4497try {
4498InetAddress ipaddress = InetAddress.getByName("");
4499Socket s = new Socket(ipaddress, 6666);
4500System.out.println("Connected to the server...");
4501DataOutputStream out = new DataOutputStream(s.getOutputStream());
4502String line = null;
4503System.out.println("Sending IP Adrress to server...");
4504line = ipaddress.getHostAddress();
4505out.writeUTF(line);
4506out.flush(); }
4507catch(Exception e) {
4508e.printStackTrace();
4509}}}
4510
4511
4512
45133-> A java program to make a chat application using UDP?
4514
4515
4516import java.io.*;
4517import java.net.*;
4518class UDPServer
4519{
4520public static DatagramSocket serversocket;
4521public static DatagramPacket dp;
4522public static BufferedReader dis;
4523public static InetAddress ia;
4524public static byte buf[] = new byte[1024];
4525public static int cport = 789,sport=790;
4526public static void main(String[] a) throws IOException
4527{
4528serversocket = new DatagramSocket(sport);
4529dp = new DatagramPacket(buf,buf.length);
4530dis = new BufferedReader
4531(new InputStreamReader(System.in));
4532ia = InetAddress.getLocalHost();
4533System.out.println("Server is Running...");
4534while(true)
4535{
4536serversocket.receive(dp);
4537String str = new String(dp.getData(), 0,
4538dp.getLength());
4539if(str.equals("STOP"))
4540{
4541System.out.println("Terminated...");
4542break;
4543}
4544System.out.println("Client: " + str);
4545String str1 = new String(dis.readLine());
4546buf = str1.getBytes();
4547serversocket.send(new
4548DatagramPacket(buf,str1.length(), ia, cport));
4549}
4550}
4551}
4552
4553
4554
4555import java.io.*;
4556import java.net.*;
4557class UDPClient
4558{
4559public static DatagramSocket clientsocket;
4560public static DatagramPacket dp;
4561public static BufferedReader dis;
4562public static InetAddress ia;
4563public static byte buf[] = new byte[1024];
4564public static int cport = 789, sport = 790;
4565public static void main(String[] a) throws IOException
4566{
4567clientsocket = new DatagramSocket(cport);
4568dp = new DatagramPacket(buf, buf.length);
4569dis = new BufferedReader(new
4570InputStreamReader(System.in));
4571ia = InetAddress.getLocalHost();
4572System.out.println("Client is Running... Type \'STOP\'
4573to Quit");
4574while(true)
4575{
4576String str = new String(dis.readLine());
4577buf = str.getBytes();
4578if(str.equals("STOP"))
4579{
4580System.out.println("Terminated...");
4581clientsocket.send(new
4582DatagramPacket(buf,str.length(), ia,
4583sport));
4584break;
4585}
4586clientsocket.send(new DatagramPacket(buf,
4587str.length(), ia, sport));
4588clientsocket.receive(dp);
4589String str2 = new String(dp.getData(), 0,
4590dp.getLength());
4591System.out.println("Server: " + str2);
4592}
4593}
4594}
4595
4596
4597
4598
4599
4600
4601
4602
46034-> Write a java program to develop a simple chat application?
4604
4605import java.io.*;
4606import java.net.*;
4607public class EchoServer
4608{
4609public static void main(String args[]) throws Exception
4610{
4611try
4612{
4613int Port;
4614BufferedReader Buf =new BufferedReader(new
4615InputStreamReader(System.in));
4616System.out.print(" Enter the Port Address : " );
4617Port=Integer.parseInt(Buf.readLine());
4618ServerSocket sok =new ServerSocket(Port);
4619System.out.println(" Server is Ready To Receive a Message. ");
4620System.out.println(" Waiting ..... ");
4621Socket so=sok.accept();
4622if(so.isConnected()==true)
4623System.out.println(" Client Socket is Connected Succecfully. ");
4624InputStream in=so.getInputStream();
4625OutputStream ou=so.getOutputStream();
4626PrintWriter pr=new PrintWriter(ou);
4627BufferedReader buf=new BufferedReader(new
4628InputStreamReader(in));
4629String str=buf.readLine();
4630System.out.println(" Message Received From Client : " + str);
4631System.out.println(" This Message is Forwarded To Client. ");
4632pr.println(str);
4633pr.flush();
4634}
4635catch(Exception e)
4636{
4637System.out.println(" Error : " + e.getMessage());
4638}
4639}
4640}
4641
4642
4643
4644import java.io.*;
4645import java.net.*;
4646public class EchoClient
4647{
4648public static void main(String args[]) throws Exception
4649{
4650try {
4651int Port;
4652BufferedReader Buf =new BufferedReader(new
4653InputStreamReader(System.in));
4654System.out.print(" Enter the Port Address : " );
4655Port=Integer.parseInt(Buf.readLine());
4656Socket sok=new Socket("localhost",Port);
4657if(sok.isConnected()==true)
4658System.out.println(" Server Socket is Connected Succecfully. ");
4659InputStream in=sok.getInputStream();
4660OutputStream ou=sok.getOutputStream();
4661PrintWriter pr=new PrintWriter(ou);
4662BufferedReader buf1=new BufferedReader(new
4663InputStreamReader(System.in));
4664BufferedReader buf2=new BufferedReader(new
4665InputStreamReader(in));
4666String str1,str2;
4667System.out.print(" Enter the Message : ");
4668str1=buf1.readLine();
4669pr.println(str1);
4670pr.flush();
4671System.out.println(" Message Send Successfully. ");
4672str2=buf2.readLine();
4673System.out.println(" Message From Server : " + str2);
4674}
4675catch(Exception e)
4676{
4677System.out.println(" Error : " + e.getMessage());
4678}
4679}
4680}
4681
4682
46835-> The message entered in the client is sent to the server and the server encodes the message and returns it to the client. Encoding is done by replacing a character by the character next to it i.e. a as b, b as c …z as a.
4684This process is done using the TCP/IP protocol. Write a Java program for the above?
4685
4686
4687
4688
4689
46906-> The message entered in the client is sent to the server and the server encodes the message and returns it to the client.
4691Encoding is done by replacing a character by the character next to it i.e. a as b, b as c …z as a. This process is done using UDP. Write a Java program for the above?
4692
4693
4694
4695
46967-> Write a Java program to display the name and address of the computer that we are currently working on?
4697
4698import java.net.*;
4699import java.util.*;
4700import java.lang.*;
4701public class ip
4702{
4703public static void main(String args[])throws UnknownHostException
4704{
4705InetAddress Address=InetAddress.getLocalHost();
4706System.out.println(Address);
4707System.out.println(Address.getHostAddress());
4708System.out.println(Address.getHostName());
4709}
4710}
4711
4712
4713
4714
4715
47168-> The client accepts IP header information in hexadecimal and sends to the server. The server receives those details and examines its checksum field.
4717Write a Java program for this scenario?
4718
4719
4720
4721
47229-> Using threading concepts, write a Java program to create a daemon process?
4723
4724import java.util.*;
4725import java.net.*;
4726public class TestDaemonThread1 extends Thread{
4727 public void run(){
4728 if(Thread.currentThread().isDaemon()){//checking for daemon thread
4729 System.out.println("daemon thread work");
4730 }
4731 else{
4732 System.out.println("user thread work");
4733 }
4734 }
4735 public static void main(String[] args){
4736 TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
4737 TestDaemonThread1 t2=new TestDaemonThread1();
4738 TestDaemonThread1 t3=new TestDaemonThread1();
4739
4740 t1.setDaemon(true);//now t1 is daemon thread
4741
4742 t1.start();//starting threads
4743 t2.start();
4744 t3.start();
4745 }
4746}
4747
4748
4749
4750
475110-> A server should run for 10 secs and generate numbers continuously. The client connecting to it
4752should read data and find out the sum of the data thus read. Write a Java program to implement this scenario.?
4753
4754
4755
4756
4757
4758
4759
476011-> Java Program to Send a Message from Client to Server and Receive a Response Back Using Socket Programming?
4761
4762
4763import java.io.BufferedReader;
4764import java.io.BufferedWriter;
4765import java.io.InputStream;
4766import java.io.InputStreamReader;
4767import java.io.OutputStream;
4768import java.io.OutputStreamWriter;
4769import java.net.ServerSocket;
4770import java.net.Socket;
4771
4772public class Server
4773{
4774
4775 private static Socket socket;
4776
4777 public static void main(String[] args)
4778 {
4779 try
4780 {
4781
4782 int port = 25000;
4783 ServerSocket serverSocket = new ServerSocket(port);
4784 System.out.println("Server Started and listening to the port 25000");
4785
4786 //Server is running always. This is done using this while(true) loop
4787 while(true)
4788 {
4789 //Reading the message from the client
4790 socket = serverSocket.accept();
4791 InputStream is = socket.getInputStream();
4792 InputStreamReader isr = new InputStreamReader(is);
4793 BufferedReader br = new BufferedReader(isr);
4794 String number = br.readLine();
4795 System.out.println("Message received from client is "+number);
4796
4797 //Multiplying the number by 2 and forming the return message
4798 String returnMessage;
4799 try
4800 {
4801 int numberInIntFormat = Integer.parseInt(number);
4802 int returnValue = numberInIntFormat*2;
4803 returnMessage = String.valueOf(returnValue) + "\n";
4804 }
4805 catch(NumberFormatException e)
4806 {
4807 //Input was not a number. Sending proper message back to client.
4808 returnMessage = "Please send a proper number\n";
4809 }
4810
4811 //Sending the response back to the client.
4812 OutputStream os = socket.getOutputStream();
4813 OutputStreamWriter osw = new OutputStreamWriter(os);
4814 BufferedWriter bw = new BufferedWriter(osw);
4815 bw.write(returnMessage);
4816 System.out.println("Message sent to the client is "+returnMessage);
4817 bw.flush();
4818 }
4819 }
4820 catch (Exception e)
4821 {
4822 e.printStackTrace();
4823 }
4824 finally
4825 {
4826 try
4827 {
4828 socket.close();
4829 }
4830 catch(Exception e){}
4831 }
4832 }
4833}
4834
4835
4836
4837import java.io.BufferedReader;
4838import java.io.BufferedWriter;
4839import java.io.InputStream;
4840import java.io.InputStreamReader;
4841import java.io.OutputStream;
4842import java.io.OutputStreamWriter;
4843import java.net.InetAddress;
4844import java.net.Socket;
4845
4846public class Client
4847{
4848
4849 private static Socket socket;
4850
4851 public static void main(String args[])
4852 {
4853 try
4854 {
4855 String host = "localhost";
4856 int port = 25000;
4857 InetAddress address = InetAddress.getByName(host);
4858 socket = new Socket(address, port);
4859
4860 //Send the message to the server
4861 OutputStream os = socket.getOutputStream();
4862 OutputStreamWriter osw = new OutputStreamWriter(os);
4863 BufferedWriter bw = new BufferedWriter(osw);
4864
4865 String number = "2";
4866
4867 String sendMessage = number + "\n";
4868 bw.write(sendMessage);
4869 bw.flush();
4870 System.out.println("Message sent to the server : "+sendMessage);
4871
4872 //Get the return message from the server
4873 InputStream is = socket.getInputStream();
4874 InputStreamReader isr = new InputStreamReader(is);
4875 BufferedReader br = new BufferedReader(isr);
4876 String message = br.readLine();
4877 System.out.println("Message received from the server : " +message);
4878 }
4879 catch (Exception exception)
4880 {
4881 exception.printStackTrace();
4882 }
4883 finally
4884 {
4885 //Closing the socket
4886 try
4887 {
4888 socket.close();
4889 }
4890 catch(Exception e)
4891 {
4892 e.printStackTrace();
4893 }
4894 }
4895 }
4896}
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
491511-> A java program to implement an echo UDP server?
4916
4917
4918
4919import java.net.*;
4920import java.util.*;
4921
4922public class ClientEcho
4923{
4924 public static void main( String args[] ) throws Exception
4925 {
4926 InetAddress add = InetAddress.getByName("snrao");
4927
4928 DatagramSocket dsock = new DatagramSocket( );
4929 String message1 = "This is client calling";
4930 byte arr[] = message1.getBytes( );
4931 DatagramPacket dpack = new DatagramPacket(arr, arr.length, add, 7);
4932 dsock.send(dpack); // send the packet
4933 Date sendTime = new Date(); // note the time of sending the message
4934
4935 dsock.receive(dpack); // receive the packet
4936 String message2 = new String(dpack.getData( ));
4937 Date receiveTime = new Date( ); // note the time of receiving the message
4938 System.out.println((receiveTime.getTime( ) - sendTime.getTime( )) + " milliseconds echo time for " + message2);
4939 }
4940}
4941
4942
4943import java.net.*;
4944import java.util.*;
4945public class ServerEcho
4946{
4947 public static void main( String args[]) throws Exception
4948 {
4949 DatagramSocket dsock = new DatagramSocket(7);
4950 byte arr1[] = new byte[150];
4951 DatagramPacket dpack = new DatagramPacket(arr1, arr1.length );
4952
4953 while(true)
4954 {
4955 dsock.receive(dpack);
4956
4957 byte arr2[] = dpack.getData();
4958 int packSize = dpack.getLength();
4959 String s2 = new String(arr2, 0, packSize);
4960
4961 System.out.println( new Date( ) + " " + dpack.getAddress( ) + " : " + dpack.getPort( ) + " "+ s2);
4962 dsock.send(dpack);
4963 }
4964 } }
4965
4966
4967
4968
496912-> Random number generation in java?
4970
4971import java.util.*;
4972
4973class RandomNumbers {
4974 public static void main(String[] args) {
4975 int c;
4976 Random t = new Random();
4977
4978 // random integers in [0, 100]
4979
4980 for (c = 1; c <= 10; c++) {
4981 System.out.println(t.nextInt(100));
4982 }
4983 }
4984}
4985
4986
4987
4988
4989
4990Question-Client which sends a text and server recieves it??
4991
4992
4993File: MyServer.java
4994
4995import java.io.*;
4996import java.net.*;
4997public class MyServer {
4998public static void main(String[] args){
4999try{
5000ServerSocket ss=new ServerSocket(6666);
5001Socket s=ss.accept();//establishes connection
5002DataInputStream dis=new DataInputStream(s.getInputStream());
5003String str=(String)dis.readUTF();
5004System.out.println("message= "+str);
5005ss.close();
5006}catch(Exception e){System.out.println(e);}
5007}
5008}
5009File: MyClient.java
5010
5011import java.io.*;
5012import java.net.*;
5013public class MyClient {
5014public static void main(String[] args) {
5015try{
5016Socket s=new Socket("localhost",6666);
5017DataOutputStream dout=new DataOutputStream(s.getOutputStream());
5018dout.writeUTF("Hello Server");
5019dout.flush();
5020dout.close();
5021s.close();
5022}catch(Exception e){System.out.println(e);}
5023}
5024}
5025
5026
5027Question-URL listing
5028
5029
5030//URLDemo.java
5031import java.io.*;
5032import java.net.*;
5033public class URLDemo{
5034public static void main(String[] args){
5035try{
5036URL url=new URL("http://www.javatpoint.com/java-tutorial");
5037
5038System.out.println("Protocol: "+url.getProtocol());
5039System.out.println("Host Name: "+url.getHost());
5040System.out.println("Port Number: "+url.getPort());
5041System.out.println("File Name: "+url.getFile());
5042
5043}catch(Exception e){System.out.println(e);}
5044}
5045}
5046
5047
5048
5049Question-Displaying all the contents of the web page???
5050
5051
5052import java.io.*;
5053import java.net.*;
5054public class URLConnectionExample {
5055public static void main(String[] args){
5056try{
5057URL url=new URL("http://www.javatpoint.com/java-tutorial");
5058URLConnection urlcon=url.openConnection();
5059InputStream stream=urlcon.getInputStream();
5060int i;
5061while((i=stream.read())!=-1){
5062System.out.print((char)i);
5063}
5064}catch(Exception e){System.out.println(e);}
5065}
5066}
5067
5068
5069
50704.Getting header of the URL?
5071
5072
5073import java.io.*;
5074import java.net.*;
5075public class HttpURLConnectionDemo{
5076public static void main(String[] args){
5077try{
5078URL url=new URL("http://www.javatpoint.com/java-tutorial");
5079HttpURLConnection huc=(HttpURLConnection)url.openConnection();
5080for(int i=1;i<=8;i++){
5081System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));
5082}
5083huc.disconnect();
5084}catch(Exception e){System.out.println(e);}
5085}
5086}
5087
5088
5089
5090
5091Question-InetAddress class ?
5092
5093
5094import java.io.*;
5095import java.net.*;
5096public class InetDemo{
5097public static void main(String[] args){
5098try{
5099InetAddress ip=InetAddress.getByName("www.javatpoint.com");
5100
5101System.out.println("Host Name: "+ip.getHostName());
5102System.out.println("IP Address: "+ip.getHostAddress());
5103}catch(Exception e){System.out.println(e);}
5104}
5105}
5106
5107
5108
5109Question-Datagram socket class?
5110
5111
5112import java.net.*;
5113public class DSender{
5114 public static void main(String[] args) throws Exception {
5115 DatagramSocket ds = new DatagramSocket();
5116 String str = "Welcome java";
5117 InetAddress ip = InetAddress.getByName("127.0.0.1");
5118
5119 DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
5120 ds.send(dp);
5121 ds.close();
5122 }
5123}
5124
5125Example of Receiving DatagramPacket by DatagramSocket
5126
5127//DReceiver.java
5128import java.net.*;
5129public class DReceiver{
5130 public static void main(String[] args) throws Exception {
5131 DatagramSocket ds = new DatagramSocket(3000);
5132 byte[] buf = new byte[1024];
5133 DatagramPacket dp = new DatagramPacket(buf, 1024);
5134 ds.receive(dp);
5135 String str = new String(dp.getData(), 0, dp.getLength());
5136 System.out.println(str);
5137 ds.close();
5138 }
5139
5140
5141Question-The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting, and then waits for a response.
5142
5143
5144
5145
5146// File Name GreetingClient.java
5147
5148import java.net.*;
5149import java.io.*;
5150
5151public class GreetingClient
5152{
5153 public static void main(String [] args)
5154 {
5155 String serverName = args[0];
5156 int port = Integer.parseInt(args[1]);
5157 try
5158 {
5159 System.out.println("Connecting to " + serverName +
5160 " on port " + port);
5161 Socket client = new Socket(serverName, port);
5162 System.out.println("Just connected to "
5163 + client.getRemoteSocketAddress());
5164 OutputStream outToServer = client.getOutputStream();
5165 DataOutputStream out = new DataOutputStream(outToServer);
5166 out.writeUTF("Hello from "
5167 + client.getLocalSocketAddress());
5168 InputStream inFromServer = client.getInputStream();
5169 DataInputStream in =
5170 new DataInputStream(inFromServer);
5171 System.out.println("Server says " + in.readUTF());
5172 client.close();
5173 }catch(IOException e)
5174 {
5175 e.printStackTrace();
5176 }
5177 }
5178}
5179Socket Server Example:
5180The following GreetingServer program is an example of a server application that uses the Socket class to listen for clients on a port number specified by a command-line argument:
5181
5182// File Name GreetingServer.java
5183
5184import java.net.*;
5185import java.io.*;
5186
5187public class GreetingServer extends Thread
5188{
5189 private ServerSocket serverSocket;
5190
5191 public GreetingServer(int port) throws IOException
5192 {
5193 serverSocket = new ServerSocket(port);
5194 serverSocket.setSoTimeout(10000);
5195 }
5196
5197 public void run()
5198 {
5199 while(true)
5200 {
5201 try
5202 {
5203 System.out.println("Waiting for client on port " +
5204 serverSocket.getLocalPort() + "...");
5205 Socket server = serverSocket.accept();
5206 System.out.println("Just connected to "
5207 + server.getRemoteSocketAddress());
5208 DataInputStream in =
5209 new DataInputStream(server.getInputStream());
5210 System.out.println(in.readUTF());
5211 DataOutputStream out =
5212 new DataOutputStream(server.getOutputStream());
5213 out.writeUTF("Thank you for connecting to "
5214 + server.getLocalSocketAddress() + "\nGoodbye!");
5215 server.close();
5216 }catch(SocketTimeoutException s)
5217 {
5218 System.out.println("Socket timed out!");
5219 break;
5220 }catch(IOException e)
5221 {
5222 e.printStackTrace();
5223 break;
5224 }
5225 }
5226 }
5227 public static void main(String [] args)
5228 {
5229 int port = Integer.parseInt(args[0]);
5230 try
5231 {
5232 Thread t = new GreetingServer(port);
5233 t.start();
5234 }catch(IOException e)
5235 {
5236 e.printStackTrace();
5237 }
5238 }
5239}
5240Compile client and server and then start server as follows:
5241
5242
5243
5244
5245Question- Wap to check whether Ipv4 or Ipv6 address?
5246
5247
5248import java.net.*;
5249import java.util.*;
5250import java.lang.*;
5251public class ipvi
5252{
5253public static void main(String args[])throws UnknownHostException
5254{
5255InetAddress Address=InetAddress.getLocalHost();
5256System.out.println(Address.getHostAddress());
5257if(Address instanceof InetAddress)
5258{
5259System.out.println("......IPV4ADDRESS");
5260}
5261else
5262{
5263System.out.println(".....IPV6ADDRESS");
5264}
5265}
5266}
5267
5268
5269
5270Question-WAP to display parts of URL.
5271
5272import java.io.*;
5273import java.net.*;
5274import java.util.*;
5275
5276class UrlParts
5277{
5278 public static void main(String args[])
5279 {
5280 try
5281 {
5282 URL u = new URL("http://academics.vit.ac.in");
5283 System.out.println("Protocol="+u.getProtocol());
5284 System.out.println("Port="+u.getPort());
5285 System.out.println("Default port="+u.getDefaultPort());
5286 System.out.println("File="+u.getFile());
5287 System.out.println("Path="+u.getPath());
5288 System.out.println("Refference="+u.getRef());
5289 }
5290 catch(Exception e)
5291 {
5292 System.out.println("Error");
5293 }
5294 }
5295}
5296
5297
5298
5299Question- Write a program to list all ports hosting a TCP server in a specified host and identify
5300available servers in well-known ports?
5301
5302import java.net.*;
5303import java.io.*;
5304public class ports{
5305public static void main(String args[])
5306{
5307for(int i=1; i++)
5308{
5309try{
5310Socket s=new Socket("127.0.0.1",i);
5311System.out.println("There is server on port"+i+"of 127.0.0.1");
5312}
5313catch(UnknownHostException e){
5314System.err.println(e);
5315break;
5316}
5317catch(IOException e){
5318}}}}
5319
5320
5321Question- Find which out of the first 1024 ports seems to be hosted tcp srevers on a specified host?
5322(Local host can be default)
5323
5324
5325import java.net.*;
5326import java.io.*;
5327public class portsB{
5328public static void main(String args[])
5329{
5330for(int i=1; i<1024; i++)
5331{
5332try{
5333Socket s=new Socket("127.0.0.1",i);
5334System.out.println("There is server on port"+i+"of 127.0.0.1");
5335}
5336catch(UnknownHostException e){
5337System.err.println(e);
5338break;
5339}
5340catch(IOException e){
5341}}}}
5342
5343
5344
5345Question- Find out which of the ports are above 1024 that seems to be hosted tcp
5346servers on a specified host?
5347
5348import java.net.*;
5349import java.io.*;
5350public class portsB{
5351public static void main(String args[])
5352{
5353for(int i=1024; ; i++)
5354{
5355try{
5356Socket s=new Socket("127.0.0.1",i);
5357System.out.println("There is server on port"+i+"of 127.0.0.1");
5358}
5359catch(UnknownHostException e){
5360System.err.println(e);
5361break;
5362}
5363catch(IOException e){
5364}}}}
5365
5366
5367
5368Question- How to check whether a port is being used or not ?
5369
5370Solution
5371Following example shows how to check whether any port is being used as a server or not by creating a socket object.
5372
5373import java.net.*;
5374import java.io.*;
5375
5376public class Main {
5377 public static void main(String[] args) {
5378 Socket Skt;
5379 String host = "localhost";
5380
5381 if (args.length > 0) {
5382 host = args[0];
5383 }
5384 for (int i = 0; i < 1024; i++) {
5385 try {
5386 System.out.println("Looking for "+ i);
5387 Skt = new Socket(host, i);
5388 System.out.println("There is a server on port " + i + " of " + host);
5389 } catch (UnknownHostException e) {
5390 System.out.println("Exception occured"+ e);
5391 break;
5392 } catch (IOException e) {}
5393 }
5394 }
5395}
5396
5397
5398Cyclesheet 1
5399
5400
54012) Write a Java program to run the basic networking commands
5402
5403import java.net.*;
5404import java.util.*;
5405import java.io.*;
5406public class command
5407{
5408 public static void main(String args[])
5409 throws Exception
5410 {
5411 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
5412 System.out.println("enter command:");
5413 String s=br.readLine();
5414 Process p=Runtime.getRuntime().exec(s);
5415 p.waitFor();
5416 BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
5417 String line=reader.readLine();
5418 while(line!=null)
5419 {
5420 System.out.println(line);
5421 line=reader.readLine();0
5422 }
5423 System.out.println("done!");
5424
5425}
5426}
5427
54283) Write a program to display the name of the computer and its IP address that you are currently working on.
5429
5430import java.net.*;
5431import java.io.*;
5432public class cm
5433{
5434public static void main(String args[])
5435{
5436try
5437{
5438BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
5439System.out.println("Enter the url which you want to find ip address and host name");
5440String str=br.readLine();
5441InetAddress add=InetAddress.getByName(str);
5442System.out.println("Local Host Information");
5443System.out.println("Host Name:"+add.getHostName());
5444System.out.println("IP address:"+add.getHostAddress());
5445}
5446catch(Exception e)
5447{
5448System.out.println(e);
5449}
5450}
5451
5452
54534) Write a program to print the IP address of “www.google.com†all IP addresses of “www.microsoft.comâ€.
5454import java.net.*;
5455import java.io.*;
5456public class ip
5457{
5458public static void main(String args[])
5459throws UnknownHostException {
5460 System.out.println(InetAddress.getByName("www.google.com"));
5461 InetAddress[] inetAddresses=InetAddress.getAllByName("www.microsoft.com");
5462 for(InetAddress ipAddress:inetAddresses)
5463 {
5464 System.out.println(ipAddress);
5465 }
5466}
5467}
5468
54695) Write a program to print all Network Interfaces of “localhostâ€.
5470
5471import java.net.*;
5472import java.util.*;
5473import java.io.*;
5474public class ni
5475{
5476public static void main(String args[]) throws UnknownHostException,SocketException
5477{
5478
5479 Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
5480if(interfaces==null)
5481{
5482System.out.println("No network interfaces found");
5483}
5484else
5485{
5486for(NetworkInterface netIf:Collections.list(interfaces))
5487{
5488System.out.println("Display Name:" + netIf.getDisplayName());
5489System.out.println("Name : " + netIf.getName());
5490System.out.println();
5491}
5492}
5493}
5494}
5495
5496
54976) Implement the simple version of “nslookup†utility.
5498
5499import java.net.*;
5500import java.io.*;
5501import java.util.*;
5502public class nslook
5503{
5504public static void main(String args[]) throws Exception
5505{
5506 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
5507 System.out.println("Enter the hostname");
5508 String cmd=br.readLine();
5509 Process p=Runtime.getRuntime().exec("nslookup "+cmd);
5510 p.waitFor();
5511 BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
5512 String line=reader.readLine();
5513 while(line!=null)
5514 {
5515 System.out.println(line);
5516 line=reader.readLine();
5517 }
5518 System.out.println("Done");
5519}
5520}
5521
55227) Write a program to download the contents associated with a HTTP URL and save it in a file.
5523
5524import java.io.*;
5525 import java.net.*;
5526 public class GetJavaUrl
5527 {
5528 public static void main(String[] args)
5529 {
5530 URL u;
5531 InputStream is=null;
5532 DataInputStream dis;
5533 String s;
5534 try
5535 {
5536 u=new URL("ftp://10.30.2.53");
5537 is=u.openStream();
5538 dis = new DataInputStream(new BufferedInputStream(is));
5539 while((s=dis.readLine())!=null)
5540 {
5541 System.out.println(s);
5542 }
5543 }
5544 catch(MalformedURLException mue)
5545 {
5546 System.out.println("404: Error NOT FOUND");
5547 mue.printStackTrace();
5548 System.exit(1);
5549 }
5550 catch(IOException ioe)
5551 {
5552 System.out.println("404: Error NOT FOUND");
5553 ioe.printStackTrace();
5554 System.exit(1);
5555 }
5556 finally
5557 {
5558 try
5559 {
5560 is.close();
5561 }
5562 catch(IOException ioe)
5563 {
5564 }
5565 }
5566 }
5567
5568}
5569
5570ITE 304 Computer Networks Lab
5571
5572Cycle sheet-2
5573
5574
5575
55761. Write a program to list all ports hosting a TCP server in a specified host and identify available servers in well-known ports?
5577
55782. Implement echo server and client in java using TCP sockets.
5579
55803. Implement date server and client in java using TCP sockets.
5581
55824. Write a program to implement a simple message transfer from client to server process using TCP/IP.
5583
55845. Develop a TCP client/server application for transferring a text file from client to server?
5585
55866. Implement a chat server and client in java using TCP sockets.
5587
55887. Implement a TCP based server program to authenticate the client’s User Name and Password. The validity of the client must be sent as the reply message to the client and display it on the standard output.
5589
55908. Find the physical address of a host when its logical address is known (ARP protocol) using TCP/IP.
5591
55929. Find the logical address of a host when its physical address is known (RARP protocol) using TCP/IP.
5593
559410. Implement Domain Name System (DNS) using TCP/IP
5595
559611. Implement a TCP/IP based Server program in Java to compute the factorial of a number (can contain arbitrary number of digits). Write a client program to test the working of the same.
5597
559812. Find the class of the IP address using TCP/IP.
5599
5600
5601Solutions
5602
5603Q1 Write a program to list all ports hosting a TCP server in a specified host and identify available servers in well-known ports?
5604
5605import java.net.Socket;
5606import java.net.*;
5607
5608public class A {
5609public static void main(String[] args) throws Exception{
5610 try {
5611 for(int i=0;i<1024;i++)
5612 {
5613 Socket s=new Socket("localhost",i);
5614 System.out.println(i);
5615 }
5616 }
5617 catch(Exception e)
5618 {
5619 System.out.println(e);
5620 }
5621}
5622}
5623
5624Q2 Implement echo server and client in java using TCP sockets.
5625
5626
5627server
5628
5629import java.io.*;
5630
5631import java.net.*;
5632
5633
5634
5635public class EchoServer
5636
5637{
5638
5639public static void main(String args[]) throws Exception
5640
5641{
5642
5643try
5644
5645{
5646
5647int Port;
5648
5649BufferedReader Buf =new BufferedReader(new
5650
5651InputStreamReader(System.in));
5652
5653System.out.print(" Enter the Port Address : " );
5654
5655Port=Integer.parseInt(Buf.readLine());
5656
5657ServerSocket sok =new ServerSocket(Port);
5658
5659System.out.println(" Server is Ready To Receive a Message. ");
5660
5661System.out.println(" Waiting ..... ");
5662
5663Socket so=sok.accept();
5664
5665if(so.isConnected()==true)
5666
5667 System.out.println(" Client Socket is Connected Succecfully. ");
5668
5669InputStream in=so.getInputStream();
5670
5671OutputStream ou=so.getOutputStream();
5672
5673PrintWriter pr=new PrintWriter(ou);
5674
5675BufferedReader buf=new BufferedReader(new
5676
5677InputStreamReader(in));
5678
5679String str=buf.readLine();
5680
5681System.out.println(" Message Received From Client : " + str);
5682
5683System.out.println(" This Message is Forwarded To Client. ");
5684
5685pr.println(str);
5686
5687pr.flush();
5688
5689}
5690
5691 catch(Exception e)
5692
5693 {
5694
5695 System.out.println(" Error : " + e.getMessage());
5696
5697 }
5698
5699}
5700
5701}
5702
5703
5704
5705client
5706
5707import java.io.*;
5708
5709import java.net.*;
5710
5711
5712
5713public class EchoClient
5714
5715{
5716
5717public static void main(String args[]) throws Exception
5718
5719{
5720
5721try {
5722
5723int Port;
5724
5725BufferedReader Buf =new BufferedReader(new
5726
5727InputStreamReader(System.in));
5728
5729System.out.print(" Enter the Port Address : " );
5730
5731Port=Integer.parseInt(Buf.readLine());
5732
5733Socket sok=new Socket("localhost",Port);
5734
5735if(sok.isConnected()==true)
5736
5737 System.out.println(" Server Socket is Connected Succecfully. ");
5738
5739InputStream in=sok.getInputStream();
5740
5741OutputStream ou=sok.getOutputStream();
5742
5743PrintWriter pr=new PrintWriter(ou);
5744
5745BufferedReader buf1=new BufferedReader(new
5746
5747InputStreamReader(System.in));
5748
5749
5750BufferedReader buf2=new BufferedReader(new
5751
5752InputStreamReader(in));
5753
5754String str1,str2;
5755
5756System.out.print(" Enter the Message : ");
5757
5758str1=buf1.readLine();
5759
5760pr.println(str1);
5761
5762pr.flush();
5763
5764System.out.println(" Message Send Successfully. ");
5765
5766str2=buf2.readLine();
5767
5768System.out.println(" Message From Server : " + str2);
5769
5770 }
5771
5772 catch(Exception e)
5773
5774 {
5775
5776 System.out.println(" Error : " + e.getMessage());
5777
5778 }
5779
5780}
5781
5782}
5783Q3 Implement date server and client in java using TCP sockets.
5784
5785client
5786
5787import java.io.*;
5788
5789import java.net.*;
5790
5791
5792
5793class DateClient
5794
5795{
5796
5797 public static void main(String args[]) throws Exception
5798
5799 {
5800
5801 Socket soc=new Socket(InetAddress.getLocalHost(),5217);
5802
5803 BufferedReader in=new BufferedReader(new InputStreamReader( soc.getInputStream() ) );
5804
5805 System.out.println(in.readLine());
5806
5807 }
5808
5809}
5810
5811
5812
5813server
5814
5815import java.net.*;
5816
5817import java.io.*;
5818
5819import java.util.*;
5820
5821
5822
5823class DateServer
5824
5825{
5826
5827 public static void main(String args[]) throws Exception
5828
5829 {
5830
5831 ServerSocket s=new ServerSocket(5217);
5832 while(true)
5833
5834 {
5835
5836 System.out.println("Waiting For Connection ...");
5837
5838 Socket soc=s.accept();
5839
5840 DataOutputStream out=new DataOutputStream(soc.getOutputStream());
5841
5842 out.writeBytes("Server Date" + (new Date()).toString() + "\n");
5843
5844 out.close();
5845
5846 soc.close();
5847
5848 }
5849
5850
5851
5852 }
5853
5854}
5855
5856
5857Q4 , Q6 Write a program to implement a simple message transfer from client to server process using TCP/IP.
5858SERVER
5859
5860import java.io.*;
5861import java.io.BufferedReader;
5862import java.io.InputStream;
5863import java.io.InputStreamReader;
5864import java.io.OutputStream;
5865import java.io.PrintWriter;
5866import java.net.*;
5867public class GossipServer
5868{
5869 public static void main(String[] args) throws Exception
5870 {
5871 ServerSocket sersock = new ServerSocket(3000);
5872 System.out.println("Server ready for chatting");
5873 Socket sock = sersock.accept( );
5874 // reading from keyboard (keyRead object)
5875 BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
5876 // sending to client (pwrite object)
5877 OutputStream ostream = sock.getOutputStream();
5878 PrintWriter pwrite = new PrintWriter(ostream, true);
5879
5880 // receiving from server ( receiveRead object)
5881 InputStream istream = sock.getInputStream();
5882 BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
5883
5884 String receiveMessage, sendMessage;
5885 while(true)
5886 {
5887 if((receiveMessage = receiveRead.readLine()) != null)
5888 {
5889 System.out.println(receiveMessage);
5890 }
5891 sendMessage = keyRead.readLine();
5892 pwrite.println(sendMessage);
5893 pwrite.flush();
5894 }
5895 }
5896}
5897
5898
58995 Develop a TCP client/server application for transferring a text file from client to server?
5900Server:
5901import java.io.BufferedInputStream;
5902import java.io.File;
5903import java.io.FileInputStream;
5904import java.io.OutputStream;
5905import java.net.InetAddress;
5906import java.net.ServerSocket;
5907import java.net.Socket;
5908
5909public class FileTransferServer {
5910
5911 public static void main(String[] args) throws Exception {
5912 //Initialize Sockets
5913 ServerSocket ssock = new ServerSocket(5000);
5914 Socket socket = ssock.accept();
5915
5916 //The InetAddress specification
5917 InetAddress IA = InetAddress.getByName("localhost");
5918
5919 //Specify the file
5920 File file = new File("/home/likewise-open/VITUNIVERSITY/14bit0297/DateServer.java");
5921 FileInputStream fis = new FileInputStream(file);
5922 BufferedInputStream bis = new BufferedInputStream(fis);
5923
5924 //Get socket's output stream
5925 OutputStream os = socket.getOutputStream();
5926
5927 //Read File Contents into contents array
5928 byte[] contents;
5929 long fileLength = file.length();
5930 long current = 0;
5931
5932 long start = System.nanoTime();
5933 while(current!=fileLength){
5934 int size = 10000;
5935 if(fileLength - current >= size)
5936 current += size;
5937 else{
5938 size = (int)(fileLength - current);
5939 current = fileLength;
5940 }
5941 contents = new byte[size];
5942 bis.read(contents, 0, size);
5943 os.write(contents);
5944 System.out.print("Sending file ... "+(current*100)/fileLength+"% complete!");
5945 }
5946
5947 os.flush();
5948 //File transfer done. Close the socket connection!
5949 socket.close();
5950 ssock.close();
5951 System.out.println("File sent succesfully!");
5952 }
5953}
5954
5955Client:
5956import java.io.BufferedOutputStream;
5957import java.io.FileOutputStream;
5958import java.io.InputStream;
5959import java.net.InetAddress;
5960import java.net.Socket;
5961
5962
5963public class FileTransferClient {
5964
5965 public static void main(String[] args) throws Exception{
5966
5967 //Initialize socket
5968 Socket socket = new Socket(InetAddress.getByName("localhost"), 5000);
5969 byte[] contents = new byte[10000];
5970
5971 //Initialize the FileOutputStream to the output file's full path.
5972 FileOutputStream fos = new FileOutputStream("e:\\data2.bin");
5973 BufferedOutputStream bos = new BufferedOutputStream(fos);
5974 InputStream is = socket.getInputStream();
5975
5976 //No of bytes read in one read() call
5977 int bytesRead = 0;
5978
5979 while((bytesRead=is.read(contents))!=-1)
5980 bos.write(contents, 0, bytesRead);
5981
5982 bos.flush();
5983 socket.close();
5984
5985 System.out.println("File saved successfully!");
5986 }
5987}
5988OUTPUT
5989
5990
5991CLINET
5992
5993import java.io.*;
5994import java.net.*;
5995public class GossipClient
5996{
5997 public static void main(String[] args) throws Exception
5998 {
5999 Socket sock = new Socket("127.0.0.1", 3000);
6000 // reading from keyboard (keyRead object)
6001 BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
6002 // sending to client (pwrite object)
6003 OutputStream ostream = sock.getOutputStream();
6004 PrintWriter pwrite = new PrintWriter(ostream, true);
6005
6006 // receiving from server ( receiveRead object)
6007 InputStream istream = sock.getInputStream();
6008 BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
6009
6010 System.out.println("Start the chitchat, type and press Enter key");
6011
6012 String receiveMessage, sendMessage;
6013 while(true)
6014 {
6015 sendMessage = keyRead.readLine(); // keyboard reading
6016 pwrite.println(sendMessage); // sending to server
6017 pwrite.flush(); // flush the data
6018 if((receiveMessage = receiveRead.readLine()) != null) //receive from server
6019 {
6020 System.out.println(receiveMessage); // displaying at DOS prompt
6021 }
6022 }
6023 }
6024}
6025Q7 Implement a TCP based server program to authenticate the client’s User Name and Password. The validity of the client must be sent as the reply message to the client and display it on the standard output.
6026
6027
6028CLIENT
6029
6030import java.io.*;
6031import java.net.*;
6032class TCPClientAuth {
6033
6034 public static void main(String argv[]) throws Exception
6035 {
6036 String username;
6037 String password;
6038 String auth;
6039
6040 BufferedReader inFromUser =
6041 new BufferedReader(new InputStreamReader(System.in));
6042
6043 Socket clientSocket = new Socket("localhost", 6789);
6044
6045 DataOutputStream outToServer =
6046 new DataOutputStream(clientSocket.getOutputStream());
6047
6048 BufferedReader inFromServer =
6049 new BufferedReader(new
6050 InputStreamReader(clientSocket.getInputStream()));
6051
6052 System.out.print("Username :");
6053 username = inFromUser.readLine();
6054
6055 System.out.print("Password :");
6056 password = inFromUser.readLine();
6057
6058
6059 outToServer.writeBytes(username + '\n' + password + '\n' );
6060
6061 auth = inFromServer.readLine();
6062
6063 System.out.println("FROM SERVER: " + auth);
6064
6065 clientSocket.close();
6066
6067 }
6068}
6069
6070SERVER
6071
6072
6073import java.io.*;
6074import java.net.*;
6075
6076class TCPServerAuth {
6077
6078 public static void main(String argv[]) throws Exception
6079 {
6080 String username;
6081 String password;
6082 String auth;
6083
6084 ServerSocket welcomeSocket = new ServerSocket(6789);
6085
6086 while(true) {
6087
6088 Socket connectionSocket = welcomeSocket.accept();
6089
6090 BufferedReader inFromClient =
6091 new BufferedReader(new
6092 InputStreamReader(connectionSocket.getInputStream()));
6093
6094
6095
6096 DataOutputStream outToClient =
6097 new DataOutputStream(connectionSocket.getOutputStream());
6098
6099 username = inFromClient.readLine();
6100 password = inFromClient.readLine();
6101
6102
6103 if (username.equals("Admin")){
6104 if (password.equals("root")){
6105 auth = "Login Successful!";
6106 }else{
6107 auth = "Wrong Password";
6108 }
6109 }else{
6110 auth = "Wrong Username";
6111 }
6112
6113 outToClient.writeBytes(auth);
6114 connectionSocket.close();
6115 }
6116 }
6117}
6118
6119Q8.Find the physical address of a host when its logical address is known (ARP protocol) using TCP/IP.
6120
6121CLIENT:
6122import java.io.*;
6123import java.util.*;
6124import java.net.*;
6125
6126public class q8client
6127{
6128public static void main(String[] args)
6129{
6130try
6131{
6132Socket s = new Socket("localhost",5555);
6133BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
6134DataOutputStream dout = new DataOutputStream(s.getOutputStream());
6135DataInputStream din = new DataInputStream(s.getInputStream());
6136System.out.println("Enter the logical address: ");
6137String str = b.readLine();
6138dout.writeBytes(str + "\n");
6139String str1 = din.readLine();
6140System.out.println("Physical Address of str: " + str1);
6141s.close();
6142}
6143catch (Exception e)
6144{
6145}
6146}}
6147
6148SERVER:
6149
6150import java.io.*;
6151import java.util.*;
6152import java.net.*;
6153
6154public class q8server
6155{
6156public static void main(String[] args)
6157{
6158try
6159{
6160ServerSocket ss = new ServerSocket(5555);
6161Socket s = ss.accept();
6162BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
6163DataOutputStream dout = new DataOutputStream(s.getOutputStream());
6164DataInputStream din = new DataInputStream(s.getInputStream());
6165String str = din.readLine();
6166String logical[] = {"172.16.27.34","195.24.54.204"};
6167String physical[] = {"8E:AE:08:AA","0A:78:6C:AD"};
6168for(int i=0;i<logical.length;i++)
6169{
6170if (str.equals(logical[i]))
6171{
6172dout.writeBytes(physical[i] + "\n");
6173break;
6174}
6175}
6176s.close();
6177}
6178catch (Exception e)
6179{
6180}
6181}
6182}
6183
6184
6185OUTPUT:
6186
6187
6188=====================================================
6189
6190
6191
6192
6193Q9.Find the logical address of a host when its physical address is known (RARP protocol) using TCP/IP.
6194
6195CLIENT:
6196import java.io.*;
6197import java.net.*;
6198class TCPLogClient {
6199
6200 public static void main(String argv[]) throws Exception
6201 {
6202 String logicAdd;
6203 String phyAdd;
6204
6205 BufferedReader inFromUser =
6206 new BufferedReader(new InputStreamReader(System.in));
6207
6208 Socket clientSocket = new Socket("localhost", 6789);
6209
6210 DataOutputStream outToServer =
6211 new DataOutputStream(clientSocket.getOutputStream());
6212
6213 BufferedReader inFromServer =
6214 new BufferedReader(new
6215 InputStreamReader(clientSocket.getInputStream()));
6216
6217 System.out.println("Enter Physical address of host");
6218 phyAdd = inFromUser.readLine();
6219
6220 outToServer.writeBytes(phyAdd + '\n');
6221
6222 logicAdd = inFromServer.readLine();
6223
6224 System.out.println("FROM SERVER: Logical Address " + logicAdd);
6225
6226 clientSocket.close();
6227
6228 }
6229}
6230
6231SERVER:
6232import java.io.*;
6233import java.net.*;
6234
6235class TCPLogServer {
6236
6237 public static void main(String argv[]) throws Exception
6238 {
6239 String phyAdd;
6240
6241
6242 ServerSocket welcomeSocket = new ServerSocket(6789);
6243
6244 while(true) {
6245
6246 Socket connectionSocket = welcomeSocket.accept();
6247
6248 BufferedReader inFromClient =
6249 new BufferedReader(new
6250 InputStreamReader(connectionSocket.getInputStream()));
6251
6252
6253 String logical[] = {"172.16.27.34","195.24.54.204", "10.10.137.1"};
6254 String physical[] = {"8E:AE:08:AA","0A:78:6C:AD", "d4:6d:50:84:db:c8"};
6255
6256 DataOutputStream outToClient =
6257 new DataOutputStream(connectionSocket.getOutputStream());
6258
6259 phyAdd = inFromClient.readLine();
6260 for(int i = 0; i < physical.length; i++)
6261 {
6262 if (phyAdd.equals(physical[i]))
6263 {
6264 outToClient.writeBytes(logical[i] + "\n");
6265 connectionSocket.close();
6266 }
6267 }
6268
6269
6270 }
6271 }
6272}
6273
6274=======================================
6275
6276
627710.Implement Domain Name System (DNS) using TCP/IP
6278
6279SERVER:
6280import java.io.*;
6281import java.net.*;
6282class TCPLoServer {
6283 public static void main(String argv[]) throws Exception
6284 {
6285 String D;
6286 ServerSocket welcomeSocket = new ServerSocket(6789);
6287 while(true) {
6288 Socket connectionSocket = welcomeSocket.accept();
6289BufferedReader inFromClient =
6290 new BufferedReader(new
6291 InputStreamReader(connectionSocket.getInputStream()));
6292String hostaddr[] = {"172.16.27.34","195.24.54.204", "10.10.137.1"};
6293 String DNS[] = {"www.google.com","www.facebook.com", "www.vit.ac.in"};
6294 DataOutputStream outToClient =
6295 new DataOutputStream(connectionSocket.getOutputStream());
6296 D = inFromClient.readLine();
6297for(int i = 0; i < hostaddr.length; i++)
6298 {
6299 if (D.equals(hostaddr[i]))
6300 {
6301 outToClient.writeBytes(DNS[i] + "\n");
6302 connectionSocket.close();
6303 }
6304 }
6305
6306
6307 }
6308 }
6309}
6310
6311
6312
6313CLIENT:
6314import java.io.*;
6315import java.net.*;
6316class TCPLoClient {
6317
6318 public static void main(String argv[]) throws Exception
6319 {
6320 String hostaddr;
6321 String DNS;
6322
6323 BufferedReader inFromUser =
6324 new BufferedReader(new InputStreamReader(System.in));
6325
6326 Socket clientSocket = new Socket("localhost", 6789);
6327
6328 DataOutputStream outToServer =
6329 new DataOutputStream(clientSocket.getOutputStream());
6330
6331 BufferedReader inFromServer =
6332 new BufferedReader(new
6333 InputStreamReader(clientSocket.getInputStream()));
6334
6335 System.out.println("Enter IP address of host");
6336 DNS = inFromUser.readLine();
6337
6338 outToServer.writeBytes(DNS + '\n');
6339
6340 hostaddr = inFromServer.readLine();
6341
6342 System.out.println("FROM SERVER: Logical Address " + hostaddr);
6343
6344 clientSocket.close();
6345
6346 }
6347}
6348
6349
6350
6351*************************************************
6352
635311.Implement a TCP/IP based Server program in Java to compute the factorial of a number (can contain arbitrary number of digits). Write a client program to test the working of the same.
6354
6355CLIENT:
6356import java.io.*;
6357import java.net.*;
6358class client {
6359 public static void main(String argv[]) throws Exception
6360 {
6361 String sentence;
6362 String modifiedSentence;
6363 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
6364 Socket clientSocket = new Socket("localhost", 2222);
6365 DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
6366 BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
6367 System.out.println("Enter a number - ");
6368 sentence = inFromUser.readLine();
6369 outToServer.writeBytes(sentence + '\n');
6370 modifiedSentence = inFromServer.readLine();
6371 System.out.println ("Factorial: " + modifiedSentence );
6372 clientSocket.close();
6373 }
6374}
6375SREVER:
6376
6377import java.io.*;
6378import java.net.*;
6379class serv {
6380 public static void main(String argv[]) throws Exception
6381 {
6382 String clientSentence;
6383 String capitalizedSentence;
6384 ServerSocket welcomeSocket = new ServerSocket(2222);
6385 Socket connectionSocket = welcomeSocket.accept();
6386 BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
6387 DataOutputStream outToClient = new DataOutputStream (connectionSocket.getOutputStream());
6388 clientSentence = inFromClient.readLine();
6389 int num = Integer.parseInt(clientSentence);
6390 int fact=1;
6391 for(int i=1;i<=num;i++)
6392 fact=fact*i;
6393 System.out.println("Factorial : "+fact);
6394 capitalizedSentence = String.valueOf(fact);
6395 //capitalizedSentence = clientSentence.toUpperCase() + '\n';
6396 outToClient.writeBytes(capitalizedSentence);
6397 }
6398}
6399
6400******************************************************
6401
6402Ques12.Find the class of the IP address using TCP/IP.
6403import java.io.*;
6404import java.net.*;
6405
6406class TCPIpclassServer {
6407
6408 public static void main(String argv[]) throws Exception
6409 {
6410 String ip;
6411 int fbyte;
6412 String ipclass = "Invalid";
6413
6414
6415 ServerSocket welcomeSocket = new ServerSocket(6789);
6416
6417 while(true) {
6418
6419 Socket connectionSocket = welcomeSocket.accept();
6420
6421 BufferedReader inFromClient =
6422 new BufferedReader(new
6423 InputStreamReader(connectionSocket.getInputStream()));
6424
6425
6426 DataOutputStream outToClient =
6427 new DataOutputStream(connectionSocket.getOutputStream());
6428
6429 ip = inFromClient.readLine();
6430 int index;
6431 index = ip.indexOf(".");
6432 ip = ip.substring(0, index);
6433
6434
6435 fbyte = Integer.parseInt(ip);
6436 if (fbyte >= 0 && fbyte <= 127)
6437 ipclass = "Class A";
6438 else if (fbyte >= 128 && fbyte <= 191)
6439 ipclass = "Class B";
6440 else if (fbyte >= 192 && fbyte <= 223)
6441 ipclass = "Class C";
6442 else if (fbyte >= 224 && fbyte <= 239)
6443 ipclass = "Class D";
6444 else if (fbyte >= 240 && fbyte <= 255)
6445 ipclass = "Class E";
6446
6447 outToClient.writeBytes(ipclass + "\n");
6448 connectionSocket.close();
6449
6450 }
6451 }
6452}
6453
6454//client
6455
6456import java.io.*;
6457import java.net.*;
6458class TCPIpclassClient {
6459
6460 public static void main(String argv[]) throws Exception
6461 {
6462 String ip;
6463 String ipclass;
6464
6465 BufferedReader inFromUser =
6466 new BufferedReader(new InputStreamReader(System.in));
6467
6468 Socket clientSocket = new Socket("localhost", 6789);
6469
6470 DataOutputStream outToServer =
6471 new DataOutputStream(clientSocket.getOutputStream());
6472
6473 BufferedReader inFromServer =
6474 new BufferedReader(new
6475 InputStreamReader(clientSocket.getInputStream()));
6476
6477 System.out.println("Enter an IP address: ");
6478 ip = inFromUser.readLine();
6479
6480 outToServer.writeBytes(ip + '\n');
6481
6482 ipclass = inFromServer.readLine();
6483
6484 System.out.println("FROM SERVER: Class for IP: "+ ip + " is : " + ipclass);
6485
6486 clientSocket.close();
6487
6488 }
6489}
6490
6491CYCLESHEET 3
6492
64931. Implement echo server and client in java using UDP sockets.
6494
64952. Write a program to implement a text based message transfer from client to server process using UDP.
6496
64973. Implement a chat server and client in java using UDP sockets.
6498
64994. Implement a DNS server and client in java using UDP sockets.
6500
65015. Find the logical address of a host when its physical address is known (RARP protocol) using UDP.
6502
65036. Find the physical address of a host when its logical address is known (ARP protocol) using UDP.
6504
65057. Implement Client - Server communication to access Date using UDP in Java.
6506
6507Solutions :
6508
65091. Implement echo server and client in java using UDP sockets.
6510Code:
6511Server:
6512import java.io.*;
6513import java.net.*;
6514class UDPServer {
6515public static void main(String args[]) throws Exception
6516{
6517DatagramSocket serverSocket = new DatagramSocket(9876);
6518byte[] receiveData = new byte[1024];
6519byte[] sendData = new byte[1024];
6520while(true)
6521{
6522DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
6523serverSocket.receive(receivePacket);
6524String sentence = new String(receivePacket.getData());
6525InetAddress IPAddress = receivePacket.getAddress();
6526int port = receivePacket.getPort();
6527String capitalizedSentence = sentence.toUpperCase();
6528sendData = capitalizedSentence.getBytes();
6529DatagramPacket sendPacket =new DatagramPacket(sendData, sendData.length, IPAddress,port);
6530serverSocket.send(sendPacket);
6531}
6532}
6533}
6534
6535Client
6536import java.io.*;
6537import java.net.*;
6538
6539class UDPClient {
6540public static void main(String args[]) throws Exception
6541{
6542BufferedReader inFromUser =
6543new BufferedReader(new InputStreamReader(System.in));
6544DatagramSocket clientSocket = new DatagramSocket();
6545InetAddress IPAddress = InetAddress.getByName("");
6546byte[] sendData = new byte[1024];
6547byte[] receiveData = new byte[1024];
6548String sentence = inFromUser.readLine();
6549sendData = sentence.getBytes();
6550DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
6551clientSocket.send(sendPacket);
6552DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
6553clientSocket.receive(receivePacket);
6554String modifiedSentence = new String(receivePacket.getData());
6555System.out.println("FROM SERVER:" + modifiedSentence);
6556clientSocket.close();
6557}
6558}
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584Q. Write a program to implement a text based message transfer from client to server process using UDP.
6585
6586Code:
6587Server:
6588import java.net.DatagramPacket;
6589import java.net.DatagramSocket;
6590public class UDPaServer
6591{
6592 public static void main(String args[])
6593 {
6594 int server_port = 1111;
6595 System.out.println("UDP Server Listening in " + server_port);
6596 try
6597 {
6598 // DatagramSocket created and listening in Port 1111
6599 DatagramSocket socket = new DatagramSocket(server_port);
6600 byte[] msgBuffer = new byte[1024];
6601
6602 // DatagramPacket for receiving the incoming data from UDP Client
6603 DatagramPacket packet = new DatagramPacket(msgBuffer, msgBuffer.length);
6604
6605 while (true)
6606 {
6607 socket.receive(packet);
6608 String message = new String(msgBuffer, 0, packet.getLength());
6609 System.out.println("UDPServer: Message received = " + message);
6610 packet.setLength(msgBuffer.length);
6611 }
6612 }
6613 catch (Exception e)
6614 {
6615 e.printStackTrace();
6616 System.out.println("Error in getting the Data from UDP Client");
6617 }
6618 }
6619}
6620
6621Client:
6622import java.net.DatagramPacket;
6623import java.net.DatagramSocket;
6624import java.net.InetAddress;
6625import java.io.*;
6626import java.net.*;
6627
6628public class UDPaClient
6629{
6630 public static void main(String args[])
6631 {
6632 try
6633 {
6634 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
6635 String server_address = "localhost";
6636 int server_port = 1111;
6637 String message = inFromUser.readLine();
6638 InetAddress address = InetAddress.getByName(server_address);
6639 DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, address, server_port);
6640 DatagramSocket socket = new DatagramSocket();
6641 socket.send(packet);
6642
6643 System.out.println("UDPClient: Sent data to Server ; Message = " + message);
6644 socket.close();
6645 }
6646 catch (Exception e)
6647 {
6648 e.printStackTrace();
6649 System.out.println("Error in sending the Data to UDP Server");
6650 }
6651 }
6652}
6653
6654
6655**********************************************
6656
66573.Implement a chat server and client in java using UDP sockets.
6658
6659//server
6660import java.io.*;
6661import java.net.*;
6662
6663public class UDPChatServer {
6664 public static void main(String args[]) throws Exception
6665 {
6666 DatagramSocket serverSocket = new DatagramSocket(6789);
6667
6668 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
6669 String reply;
6670 while(true)
6671 {
6672 byte[] receiveData = new byte[1024];
6673 byte[] sendData = new byte[1024];
6674 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
6675 serverSocket.receive(receivePacket);
6676
6677 String msg = new String(receivePacket.getData());
6678 System.out.println("Message Received: " + msg);
6679
6680 InetAddress IPAddress = receivePacket.getAddress();
6681 int port = receivePacket.getPort();
6682
6683 System.out.printf("Enter reply: ");
6684 reply = inFromUser.readLine();
6685 if (reply.equals("bye"))
6686 {
6687 System.out.printf("Exiting Chat!");
6688 serverSocket.close();
6689 break;
6690 }
6691 sendData = reply.getBytes();
6692 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
6693 serverSocket.send(sendPacket);
6694 }
6695
6696 }
6697}
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708//client
6709import java.io.*;
6710import java.net.*;
6711
6712public class UDPChatClient {
6713 public static void main(String args[]) throws Exception
6714 {
6715 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
6716
6717 InetAddress IPAddress = InetAddress.getByName("localhost");
6718
6719 String msg = "";
6720 while(true)
6721 {
6722 byte[] sendData = new byte[1024];
6723 byte[] receiveData = new byte[1024];
6724 DatagramSocket clientSocket = new DatagramSocket();
6725 System.out.printf("Send a Message: ");
6726 msg = inFromUser.readLine();
6727 if (msg.equals("bye"))
6728 {
6729 System.out.printf("Exiting Chat!");
6730 clientSocket.close();
6731 break;
6732 }
6733 sendData = msg.getBytes();
6734
6735 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 6789);
6736 clientSocket.send(sendPacket);
6737
6738 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
6739 clientSocket.receive(receivePacket);
6740
6741 String reply = new String(receivePacket.getData());
6742 System.out.println("Reply: " + reply);
6743 clientSocket.close();
6744 }
6745 }
6746}
6747
6748
6749****************************************
6750
6751
6752
67534. Implement a DNS server and client in java using UDP sockets.
6754
6755//server
6756import java.io.*;
6757import java.net.*;
6758import java.util.*;
6759class Serverdns12
6760{
6761
6762 public static void main(String args[])
6763 {
6764 try
6765 {
6766 DatagramSocket server=new DatagramSocket(1309);
6767 while(true)
6768 {
6769 byte[] sendbyte=new byte[1024];
6770 byte[] receivebyte=new byte[1024];
6771 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
6772 server.receive(receiver);
6773 String str=new String(receiver.getData());
6774 String s=str.trim();
6775 //System.out.println(s);
6776 InetAddress addr=receiver.getAddress();
6777 int port=receiver.getPort();
6778 String ip[]={"165.165.80.80","165.165.79.1"};
6779 String name[]={"www.aptitudeguru.com","www.downloadcyclone.blogspot.com"};
6780 for(int i=0;i<ip.length;i++)
6781 {
6782 if(s.equals(ip[i]))
6783 {
6784 sendbyte=name[i].getBytes();
6785 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
6786 server.send(sender);
6787 break;
6788 }
6789 else if(s.equals(name[i]))
6790 {
6791 sendbyte=ip[i].getBytes();
6792 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
6793 server.send(sender);
6794 break;
6795 }
6796 }
6797 break;
6798 }
6799 }
6800 catch(Exception e)
6801 {
6802 System.out.println(e);
6803 }
6804 }
6805}
6806
6807
6808
6809
6810//client
6811
6812import java.io.*;
6813import java.net.*;
6814import java.util.*;
6815class Clientdns12
6816{
6817 public static void main(String args[])
6818 {
6819 try
6820 {
6821 DatagramSocket client=new DatagramSocket();
6822 InetAddress addr=InetAddress.getByName("127.0.0.1");
6823
6824 byte[] sendbyte=new byte[1024];
6825 byte[] receivebyte=new byte[1024];
6826
6827 BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
6828 System.out.println("Enter the DOMAIN NAME or IP adress:");
6829 String str=in.readLine();
6830 sendbyte=str.getBytes();
6831 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,1309);
6832 client.send(sender);
6833 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
6834 client.receive(receiver);
6835 String s=new String(receiver.getData());
6836 System.out.println("IP address or DOMAIN NAME: "+s.trim());
6837 client.close();
6838 }
6839 catch(Exception e)
6840 {
6841 System.out.println(e);
6842 }
6843 }
6844}
6845
6846***************************
6847
6848
6849
6850
6851
68525. Find the logical address of a host when its physical address is known (RARP protocol) using UDP.
6853
6854//SERVER
6855import java.io.*;
6856import java.net.*;
6857
6858public class UDPRARPServer {
6859 public static void main(String args[]) throws Exception
6860 {
6861 DatagramSocket serverSocket = new DatagramSocket(6789);
6862 byte[] receiveData = new byte[1024];
6863 byte[] sendData = new byte[1024];
6864
6865 String logical[] = {"172.16.27.34","195.24.54.204", "10.10.137.1"};
6866 String physical[] = {"8E:AE:08:AA","0A:78:6C:AD", "d4:6d:50:84:db:c8"};
6867 String reply = "";
6868
6869 while(true)
6870 {
6871 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
6872 serverSocket.receive(receivePacket);
6873
6874 String phyaddr = new String(receivePacket.getData());
6875 System.out.println("Physical Address received: " + phyaddr);
6876 phyaddr = phyaddr.trim();
6877 InetAddress IPAddress = receivePacket.getAddress();
6878 int port = receivePacket.getPort();
6879
6880 for(int i = 0; i < physical.length; i++)
6881 {
6882 if (phyaddr.equals(physical[i]))
6883 {
6884 reply = logical[i];
6885 sendData = reply.getBytes();
6886 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
6887 serverSocket.send(sendPacket);
6888 }
6889 }
6890
6891 }
6892 }
6893}
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904//CLIENT
6905import java.io.*;
6906import java.net.*;
6907
6908public class UDPRARPClient {
6909 public static void main(String args[]) throws Exception
6910 {
6911 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
6912 DatagramSocket clientSocket = new DatagramSocket();
6913 InetAddress IPAddress = InetAddress.getByName("localhost");
6914 byte[] sendData = new byte[1024];
6915 byte[] receiveData = new byte[1024];
6916
6917 System.out.printf("Enter Physical address: ");
6918 String phyaddr = inFromUser.readLine();
6919 sendData = phyaddr.getBytes();
6920
6921 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 6789);
6922 clientSocket.send(sendPacket);
6923
6924 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
6925 clientSocket.receive(receivePacket);
6926
6927 String logaddr = new String(receivePacket.getData());
6928 System.out.println("Logical Address:" + logaddr);
6929 clientSocket.close();
6930 }
6931}
6932
6933
6934********************************
6935
6936
69376.Find the physical address of a host when its logical address is known (ARP protocol) using UDP.
6938
6939//server
6940import java.io.*;
6941import java.net.*;
6942import java.util.*;
6943class Serverarp12
6944{
6945 public static void main(String args[])
6946 {
6947 try
6948 {
6949 DatagramSocket server=new DatagramSocket(1309);
6950 while(true)
6951 {
6952 byte[] sendbyte=new byte[1024];
6953 byte[] receivebyte=new byte[1024];
6954 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
6955 server.receive(receiver);
6956 String str=new String(receiver.getData());
6957 String s=str.trim();
6958 //System.out.println(s);
6959 InetAddress addr=receiver.getAddress();
6960 int port=receiver.getPort();
6961 String ip[]={"165.165.80.80","165.165.79.1"};
6962 String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
6963 for(int i=0;i<ip.length;i++)
6964 {
6965 if(s.equals(ip[i]))
6966 {
6967 sendbyte=mac[i].getBytes();
6968 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
6969 server.send(sender);
6970 break;
6971 }
6972 }
6973 break;
6974
6975
6976 }
6977 }
6978 catch(Exception e)
6979 {
6980 System.out.println(e);
6981 }
6982 }
6983}
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997//client
6998import java.io.*;
6999import java.net.*;
7000import java.util.*;
7001class Clientarp12
7002{
7003 public static void main(String args[])
7004 {
7005 try
7006 {
7007 DatagramSocket client=new DatagramSocket();
7008 InetAddress addr=InetAddress.getByName("127.0.0.1");
7009
7010 byte[] sendbyte=new byte[1024];
7011 byte[] receivebyte=new byte[1024];
7012 BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
7013 System.out.println("Enter the logical address (IP):");
7014 String str=in.readLine();
7015 sendbyte=str.getBytes();
7016 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,1309);
7017 client.send(sender);
7018 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
7019 client.receive(receiver);
7020 String s=new String(receiver.getData());
7021 System.out.println("The Physical Address is(MAC): "+s.trim());
7022 client.close();
7023 }
7024 catch(Exception e)
7025 {
7026 System.out.println(e);
7027 }
7028 }
7029}
7030
7031
7032
7033*********************************
7034
7035
70367.Implement Client - Server communication to access Date using UDP in Java.
7037
7038
7039//server
7040import java.io.*;
7041import java.net.*;
7042import java.util.*;
7043
7044public class UDPDateServer {
7045 public static void main(String args[]) throws Exception
7046 {
7047 DatagramSocket serverSocket = new DatagramSocket(6789);
7048 byte[] receiveData = new byte[1024];
7049 byte[] sendData = new byte[1024];
7050 String GetDate = "";
7051 while(true)
7052 {
7053 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
7054 serverSocket.receive(receivePacket);
7055
7056 String msg = new String(receivePacket.getData());
7057 System.out.println("Message: " + msg);
7058
7059 InetAddress IPAddress = receivePacket.getAddress();
7060 int port = receivePacket.getPort();
7061 msg = msg.trim();
7062 if (msg.equals("date"))
7063 {
7064 Date d = new Date();
7065 GetDate = d.toString();
7066 }
7067
7068 sendData = GetDate.getBytes();
7069 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
7070 serverSocket.send(sendPacket);
7071 }
7072 }
7073}
7074
7075
7076
7077
7078
7079//client
7080
7081import java.io.*;
7082import java.net.*;
7083
7084
7085public class UDPDateClient {
7086 public static void main(String args[]) throws Exception
7087 {
7088 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
7089 DatagramSocket clientSocket = new DatagramSocket();
7090 InetAddress IPAddress = InetAddress.getByName("localhost");
7091 byte[] sendData = new byte[1024];
7092 byte[] receiveData = new byte[1024];
7093
7094 System.out.printf("Enter Request: ");
7095 String msg = inFromUser.readLine();
7096 sendData = msg.getBytes();
7097
7098 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 6789);
7099 clientSocket.send(sendPacket);
7100
7101 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
7102 clientSocket.receive(receivePacket);
7103
7104 String reply = new String(receivePacket.getData());
7105 System.out.println("FROM SERVER:" + reply);
7106 clientSocket.close();
7107 }
7108}
7109
7110
7111==========================================
7112
7113This class of java in "java.net" represents an Internet Protocol (IP) address. InetAddress class is used to create and manipulate IP objects. It does not have a public constructor. The object of this class can be obtained using its static methods getLocalHost(), getByName(), and getAllByName(). It has several useful methods for obtaining host names and IP addresses
7114Methods in java.net that return InetAddress
7115
7116 InetAddress
7117InterfaceAddress.getAddress()
7118 Returns an InetAddress for this address.
7119 InetAddress
7120InetSocketAddress.getAddress()
7121 Gets the InetAddress.
7122 InetAddress
7123DatagramPacket.getAddress()
7124 Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.
7125static InetAddress[]
7126InetAddress.getAllByName(String host)
7127 Given the name of a host, returns an array of its IP addresses, based on the configured name service on the system.
7128 InetAddress
7129InterfaceAddress.getBroadcast()
7130 Returns an InetAddress for the brodcast address for this InterfaceAddress.
7131static InetAddress
7132InetAddress.getByAddress(byte[] addr)
7133 Returns an InetAddress object given the raw IP address .
7134static InetAddress
7135InetAddress.getByAddress(String host, byte[] addr)
7136 Create an InetAddress based on the provided host name and IP address No name service is checked for the validity of the address.
7137static InetAddress
7138InetAddress.getByName(String host)
7139 Determines the IP address of a host, given the host's name.
7140protected InetAddress
7141URLStreamHandler.getHostAddress(URL u)
7142 Get the IP address of our host.
7143protected InetAddress
7144SocketImpl.getInetAddress()
7145 Returns the value of this socket's address field.
7146 InetAddress
7147Socket.getInetAddress()
7148 Returns the address to which the socket is connected.
7149 InetAddress
7150ServerSocket.getInetAddress()
7151 Returns the local address of this server socket.
7152 InetAddress
7153DatagramSocket.getInetAddress()
7154 Returns the address to which this socket is connected.
7155 InetAddress
7156MulticastSocket.getInterface()
7157 Retrieve the address of the network interface used for multicast packets.
7158 InetAddress
7159Socket.getLocalAddress()
7160 Gets the local address to which the socket is bound.
7161 InetAddress
7162DatagramSocket.getLocalAddress()
7163 Gets the local address to which the socket is bound.
7164static InetAddress
7165InetAddress.getLocalHost()
7166 Returns the local host.
7167protected InetAddress
7168Authenticator.getRequestingSite()
7169 Gets the InetAddress of the site requesting authorization, or null if not available.
7170
7171
7172\A Program That Prints the Address of 192.168.64.3\\
7173
7174import java.net.*;
7175public class Address {
7176public static void main (String[] args) {
7177try {
7178InetAddress address = inetAddress.getByName("192.168.64.3");
7179System.out.println(address);
7180}
7181catch (UnknownHostException e) {
7182System.out.println("Could not find 192.168.64.3 ");
7183}
7184}
7185}
7186
7187\\program find the all address of google\\
7188
7189import java.net.*;
7190public class AllAddressesOfgoogle {
7191public static void main (String[] args) {
7192try {
7193InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
7194for (int i = 0; i < addresses.length; i++) {
7195System.out.println(addresses[i]);
7196}
7197}
7198catch (UnknownHostException e) {
7199System.out.println("Could not find www.microsoft.com");
7200}
7201}
7202}
7203
7204
7205
7206\\prints the address of the machine it's run on.
7207
7208import java.net.*;
7209public class MyAddress {
7210public static void main (String[] args) {
7211try {
7212InetAddress address = InetAddress.getLocalHost( );
7213System.out.println(address);
7214}
7215catch (UnknownHostException e) {
7216System.out.println("Could not find this computer's address.");
7217}
7218}
7219}
7220
7221Given the Address, Find the Hostname
7222import java.net.*;
7223public class ReverseTest {
7224public static void main (String[] args) {
7225try {
7226InetAddress ia = InetAddress.getByName("192.168.64.3");
7227System.out.println(ia.getHostName( ));
7228}
7229catch (Exception e) {
7230System.err.println(e);
7231}
7232}
7233}
7234. Are www.oreilly.com and helio.ora.com the Same?
7235import java.net.*;
7236public class OReillyAliases {
7237public static void main (String args[]) {
7238try {
7239InetAddress oreilly = InetAddress.getByName("www.oreilly.com");
7240InetAddress helio = InetAddress.getByName("helio.ora.com");
7241if (oreilly.equals(helio)) {
7242System.out.println("www.oreilly.com is the same as helio.ora.com");
7243}
7244else {
7245System.out.println("www.oreilly.com is not the same as helio.ora.com");
7246}
7247}
7248catch (UnknownHostException e) {
7249System.out.println("Host lookup failed.");
7250}
7251}
7252}
7253
7254import java.net.*;
7255import java.io.*;
7256public class prog7
7257{
7258public static void main(String args[])
7259{
7260try
7261{
7262
7263BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
7264File f=new File("test.txt");
7265FileWriter fw=new FileWriter(f);
7266System.out.println("Enter the URL which u want to download");
7267String str=br.readLine();
7268URL u=new URL(str);
7269InputStream in=u.openStream();
7270BufferedReader br1=new BufferedReader(new InputStreamReader(in));
7271String str1;
7272while((str1=br1.readLine())!=null){
7273fw.write(str1+"\r\n");
7274}
7275System.out.println("the content of the url:"+str+" is download and saved in text .txt");
7276fw.close();
7277}
7278catch(Exception e)
7279{
7280System.out.println(e);
7281}
7282}
7283}
7284
7285
7286+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++11111111111111111111111111111111111111111111111111111111111111111111111111144444444444444444444444444444444444444444444444444444444444444444444444444444444444444bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiittttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111133333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333
7287
7288
7289
7290
7291question one
7292Implement echo server and client in java using UDP sockets.
7293
7294Client program – ServerEcho.java
7295
7296import java.net.*;
7297import java.util.*;
7298
7299public class ServerEcho
7300{
7301 public static void main( String args[]) throws Exception
7302 {
7303 DatagramSocket dsock = new DatagramSocket(7);
7304 byte arr1[] = new byte[150];
7305 DatagramPacket dpack = new DatagramPacket(arr1, arr1.length );
7306
7307 while(true)
7308 {
7309 dsock.receive(dpack);
7310
7311 byte arr2[] = dpack.getData();
7312 int packSize = dpack.getLength();
7313 String s2 = new String(arr2, 0, packSize);
7314
7315 System.out.println( new Date( ) + " " + dpack.getAddress( ) + " : " + dpack.getPort( ) + " "+ s2);
7316 dsock.send(dpack);
7317 }
7318 }
7319}
7320
7321Client program – ClientEcho.java
7322import java.net.*;
7323import java.util.*;
7324
7325public class ClientEcho
7326{
7327 public static void main( String args[] ) throws Exception
7328 {
7329 InetAddress add = InetAddress.getByName("snrao");
7330
7331 DatagramSocket dsock = new DatagramSocket( );
7332 String message1 = "This is client calling";
7333 byte arr[] = message1.getBytes( );
7334 DatagramPacket dpack = new DatagramPacket(arr, arr.length, add, 7);
7335 dsock.send(dpack); // send the packet
7336 Date sendTime = new Date(); // note the time of sending the message
7337
7338 dsock.receive(dpack); // receive the packet
7339 String message2 = new String(dpack.getData( ));
7340 Date receiveTime = new Date( ); // note the time of receiving the message
7341 System.out.println((receiveTime.getTime( ) - sendTime.getTime( )) + " milliseconds echo time for " + message2);
7342 }
7343}
7344
7345
7346 OR
7347
7348import java.net.*;
7349 import java.util.*;
7350 public class EchoServer
7351{
7352 public static void main( String args[]) throws Exception
7353 {
7354 DatagramSocket dsock = new DatagramSocket(7);
7355byte arr1[] = new byte[150];
7356DatagramPacket dpack = new DatagramPacket(arr1, arr1.length );
7357while(true)
7358{ dsock.receive(dpack);
7359byte arr2[] = dpack.getData();
7360 int packSize = dpack.getLength();
7361String s2 = new String(arr2, 0, packSize);
7362System.out.println( new Date( ) + " " + dpack.getAddress( ) + " : " + dpack.getPort( ) + " "+ s2);
7363dsock.send(dpack);
7364}
7365}
7366}----------------------------------
7367import java.net.*;
7368import java.util.*;
7369 public class EchoClient
7370{ public static void main( String args[] ) throws Exception {
7371InetAddress add = InetAddress.getByName("127.0.0.1");
7372DatagramSocket dsock = new DatagramSocket( );
7373 String message1 = "This is client calling";
7374 byte arr[] = message1.getBytes( );
7375 DatagramPacket dpack = new DatagramPacket(arr, arr.length, add, 7);
7376 dsock.send(dpack); // send the packet
7377Date sendTime = new Date( ); // note the time of sending the message
7378dsock.receive(dpack); // receive the packet
7379String message2 = new String(dpack.getData( ));
7380 Date receiveTime = new Date( ); // note the time of receiving the message
7381 System.out.println((receiveTime.getTime( ) - sendTime.getTime( )) + " milliseconds echo time for " + message2);
7382 }
7383 }
7384
7385
7386
7387
7388
7389
7390
7391
7392question 2
7393Implement a simple message transfer from client to server process using UDP.
7394import java.io.*;
7395import java.net.*;
7396class UDPServerss {
7397public static void main(String args[]) throws Exception {
7398 DatagramSocket serverSocket = new DatagramSocket(9876);
7399
7400 byte[] receiveData = new byte[1024];
7401 byte[] sendData = new byte[1024];
7402 while(true) {
7403
7404 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
7405 serverSocket.receive(receivePacket);
7406 String sentence = new String( receivePacket.getData());
7407 System.out.println("RECEIVED: " + sentence);
7408 InetAddress IPAddress = receivePacket.getAddress();
7409 int port = receivePacket.getPort();
7410 String capitalizedSentence = sentence.toUpperCase();
7411 sendData = capitalizedSentence.getBytes();
7412 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
7413 serverSocket.send(sendPacket);
7414 }
7415}
7416}
7417import java.io.*;
7418import java.net.*;
7419 class UDPClientssss {
7420 public static void main(String args[]) throws Exception {
7421 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
7422 DatagramSocket clientSocket = new DatagramSocket();
7423 InetAddress IPAddress = InetAddress.getByName("localhost");
7424 byte[] sendData = new byte[1024];
7425 byte[] receiveData = new byte[1024];
7426 String sentence = inFromUser.readLine();
7427 sendData = sentence.getBytes();
7428 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
7429 clientSocket.send(sendPacket);
7430 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
7431 clientSocket.receive(receivePacket);
7432 String modifiedSentence = new String(receivePacket.getData());
7433 System.out.println("FROM SERVER:" + modifiedSentence);
7434 clientSocket.close();
7435 }
7436 }
7437
7438
7439
7440
7441
7442
7443question 3
7444 Simple chat application in java using datagram socket and datagram packet
7445Algorithm
7446Start the UDP chat program
7447Import the package java.net.*;
7448Declare the datagramsocket,datagrampacket,BufferedReader,InetAddress.
7449Start the main function
7450In the main function using while loop it perform the loop until str.equals is STOP
7451There important while loop function are
7452clientsocket = new DatagramSocket(cport);
7453dp = new DatagramPacket(buf, buf.length);
7454dis = new BufferedReader(new
7455InputStreamReader(System.in));
7456ia = InetAddress.getLocalHost(); f it is stop then break the while loop
7457Terminate the UDP client program
7458source code java programming UDP Chat server
7459import java.io.*;
7460import java.net.*;
7461class UDPServer
7462{
7463public static DatagramSocket serversocket;
7464public static DatagramPacket dp;
7465public static BufferedReader dis;
7466public static InetAddress ia;
7467public static byte buf[] = new byte[1024];
7468public static int cport = 789,sport=790;
7469public static void main(String[] a) throws IOException
7470{
7471serversocket = new DatagramSocket(sport);
7472dp = new DatagramPacket(buf,buf.length);
7473dis = new BufferedReader
7474(new InputStreamReader(System.in));
7475ia = InetAddress.getLocalHost();
7476System.out.println("Server is Running...");
7477while(true)
7478{
7479serversocket.receive(dp);
7480String str = new String(dp.getData(), 0,
7481dp.getLength());
7482if(str.equals("STOP"))
7483{
7484System.out.println("Terminated...");
7485break;
7486}
7487System.out.println("Client: " + str);
7488String str1 = new String(dis.readLine());
7489buf = str1.getBytes();
7490serversocket.send(new
7491DatagramPacket(buf,str1.length(), ia, cport));
7492}
7493}
7494}
7495
7496Output:-
7497C:\IPLAB>javac UDPServer.java
7498C:\IPLAB>java UDPServer
7499Server is Running...
7500Client: Hello
7501Welcome
7502Terminated...
7503
7504source code java programming UDP Chat Client
7505import java.io.*;
7506import java.net.*;
7507class UDPClient
7508{
7509public static DatagramSocket clientsocket;
7510public static DatagramPacket dp;
7511public static BufferedReader dis;
7512public static InetAddress ia;
7513public static byte buf[] = new byte[1024];
7514public static int cport = 789, sport = 790;
7515public static void main(String[] a) throws IOException
7516{
7517clientsocket = new DatagramSocket(cport);
7518dp = new DatagramPacket(buf, buf.length);
7519dis = new BufferedReader(new
7520InputStreamReader(System.in));
7521ia = InetAddress.getLocalHost();
7522System.out.println("Client is Running... Type 'STOP'
7523to Quit");
7524while(true)
7525{
7526String str = new String(dis.readLine());
7527buf = str.getBytes();
7528if(str.equals("STOP"))
7529{
7530System.out.println("Terminated...");
7531clientsocket.send(new
7532DatagramPacket(buf,str.length(), ia,
7533sport));
7534break;
7535}
7536clientsocket.send(new DatagramPacket(buf,
7537str.length(), ia, sport));
7538clientsocket.receive(dp);
7539String str2 = new String(dp.getData(), 0,
7540dp.getLength());
7541System.out.println("Server: " + str2);
7542}
7543}
7544}
7545
7546Output UDP Chat Client
7547C:\IPLAB>javac UDPClient.java
7548C:\IPLAB>java UDPClient
7549Client is Running... Type ‘STOP’ to Quit
7550Hello
7551Server: Welcome
7552STOP
7553Terminated...
7554BB / REC - 41
7555
7556
7557
7558 or
7559
7560
7561 Client interface:
7562
7563 import java.awt.*;
7564 import javax.swing.*;
7565 public class UDPClient extends JFrame
7566 {
7567 // Variables
7568 private JFrame frame;
7569 private JPanel panel;
7570 private JLabel label;
7571 private JButton sendbutton;
7572 private JTextField textfield;
7573 private JTextArea textarea;
7574 private JScrollPane scrollpane;
7575
7576 public static void main (String args[]) {
7577
7578 new UDPClient();
7579 }
7580
7581 // Constructor
7582 public UDPClient() {
7583
7584 frame = this;
7585 panel = new JPanel(new GridBagLayout());
7586 panel.setBackground(Color.cyan);
7587 frame.setTitle("Chat Applet Client");
7588 frame.getContentPane().add(panel, BorderLayout.NORTH);
7589 frame.setVisible(true);
7590 frame.setSize(430, 364);
7591 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
7592 //frame.setResizable(false);
7593 GridBagConstraints c = new GridBagConstraints();
7594 c.insets = new Insets(5, 5, 5, 5);
7595
7596 // Server address label
7597 label = new JLabel("Server:");
7598 c.fill = GridBagConstraints.HORIZONTAL;
7599 c.gridx = 0;
7600 c.gridy = 0;
7601 panel.add(label, c);
7602
7603 // Server address textfield
7604 textfield = new JTextField(20);
7605 c.fill = GridBagConstraints.HORIZONTAL;
7606 c.gridx = 1;
7607 c.gridy = 0;
7608 panel.add(textfield, c);
7609
7610 // 'Port#:' label
7611 label = new JLabel("Port# :");
7612 c.fill = GridBagConstraints.HORIZONTAL;
7613 c.gridx = 2;
7614 c.gridy = 0;
7615 panel.add(label, c);
7616
7617 // Port# textfield
7618 textfield = new JTextField(6);
7619 c.fill = GridBagConstraints.HORIZONTAL;
7620 c.gridx = 3;
7621 c.gridy = 0;
7622 panel.add(textfield, c);
7623
7624 // 'Conversation:' label
7625 label = new JLabel("Conversation:");
7626 c.fill = GridBagConstraints.HORIZONTAL;
7627 c.gridx = 0;
7628 c.gridy = 1;
7629 c.gridwidth = 4;
7630 panel.add(label, c);
7631
7632 // Conversation Window
7633 textarea = new JTextArea(10, 2);
7634 scrollpane = new JScrollPane(textarea);
7635 textarea.setLineWrap(true);
7636 textarea.setWrapStyleWord(true);
7637 textarea.setEditable(false);
7638 c.fill = GridBagConstraints.HORIZONTAL;
7639 c.gridx = 0;
7640 c.gridy = 2;
7641 c.gridwidth = 4;
7642 panel.add(scrollpane, c);
7643
7644 // 'Message:' label
7645 label = new JLabel("Message to Send:");
7646 c.fill = GridBagConstraints.HORIZONTAL;
7647 c.gridx = 0;
7648 c.gridy = 3;
7649 panel.add(label, c);
7650
7651 // Message Window
7652 textarea = new JTextArea(2, 2);
7653 scrollpane = new JScrollPane(textarea);
7654 textarea.setLineWrap(true);
7655 textarea.setWrapStyleWord(true);
7656 c.fill = GridBagConstraints.HORIZONTAL;
7657 c.gridx = 0;
7658 c.gridy = 4;
7659 c.gridwidth = 4;
7660 panel.add(scrollpane, c);
7661
7662 // 'Send' button
7663 sendbutton = new JButton("Send");
7664 c.fill = GridBagConstraints.HORIZONTAL;
7665 c.gridx = 0;
7666 c.gridy = 5;
7667 c.gridwidth = 4;
7668 panel.add(sendbutton, c);
7669 }
7670 }
7671
7672
7673
7674
7675
7676Server interface:
7677
7678 import java.awt.*;
7679 import javax.swing.*;
7680 public class UDPServer extends JFrame {
7681 // Variables
7682 private JFrame frame;
7683 private JPanel panel;
7684 private JLabel label;
7685 private JButton startbutton;
7686 private JButton stopbutton;
7687 private JButton sendbutton;
7688 private JTextField textfield;
7689 private JTextArea textarea;
7690 private JScrollPane scrollpane;
7691
7692 //http://www.youtube.com/watch?v=IkEz5tW5bok
7693 public static void main (String args[]) {
7694
7695 new UDPServer();
7696 }
7697
7698 // Constructor
7699 public UDPServer() {
7700
7701 frame = this;
7702 panel = new JPanel(new GridBagLayout());
7703 panel.setBackground(Color.darkGray);
7704 frame.setTitle("Chat Applet Server");
7705 frame.getContentPane().add(panel, BorderLayout.NORTH);
7706 frame.setVisible(true);
7707 //frame.pack();
7708
7709 frame.setSize(430, 364);
7710 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
7711 frame.setResizable(true);
7712 GridBagConstraints c = new GridBagConstraints();
7713 c.insets = new Insets(5, 5, 5, 5);
7714
7715 // 'Start Server' button
7716 startbutton = new JButton("Start Server");
7717 startbutton.setPreferredSize(new Dimension(130,20));
7718 c.fill = GridBagConstraints.HORIZONTAL;
7719 c.gridx = 0;
7720 c.gridy = 0;
7721 c.gridwidth = 1;
7722 panel.add(startbutton, c);
7723
7724 // 'Stop Server' button
7725 stopbutton = new JButton("Stop Server");
7726 stopbutton.setPreferredSize(new Dimension(130,20));
7727 c.fill = GridBagConstraints.HORIZONTAL;
7728 c.gridx = 1;
7729 c.gridy = 0;
7730 c.gridwidth = 1;
7731 panel.add(stopbutton, c);
7732
7733 // 'Port#:' label
7734 label = new JLabel("Port# :");
7735 label.setForeground(Color.white);
7736 c.fill = GridBagConstraints.HORIZONTAL;
7737 c.gridx = 2;
7738 c.gridy = 0;
7739 panel.add(label, c);
7740
7741 // Port# textfield
7742 textfield = new JTextField(6);
7743 c.fill = GridBagConstraints.HORIZONTAL;
7744 c.gridx = 3;
7745 c.gridy = 0;
7746 panel.add(textfield, c);
7747
7748 // 'Conversation:' label
7749 label = new JLabel("Conversation:");
7750 label.setForeground(Color.white);
7751 c.fill = GridBagConstraints.HORIZONTAL;
7752 c.gridx = 0;
7753 c.gridy = 1;
7754 c.gridwidth = 4;
7755 panel.add(label, c);
7756
7757 // Conversation Window
7758 textarea = new JTextArea("<Server not yet started!>", 10, 2);
7759 scrollpane = new JScrollPane(textarea);
7760 textarea.setLineWrap(true);
7761 textarea.setWrapStyleWord(true);
7762 textarea.setEditable(false);
7763 c.fill = GridBagConstraints.HORIZONTAL;
7764 c.gridx = 0;
7765 c.gridy = 2;
7766 c.gridwidth = 4;
7767 panel.add(scrollpane, c);
7768
7769 // 'Message:' label
7770 label = new JLabel("Message to Send:");
7771 label.setForeground(Color.white);
7772 c.fill = GridBagConstraints.HORIZONTAL;
7773 c.gridx = 0;
7774 c.gridy = 3;
7775 panel.add(label, c);
7776
7777 // Message Window
7778 textarea = new JTextArea(2, 2);
7779 scrollpane = new JScrollPane(textarea);
7780 textarea.setLineWrap(true);
7781 textarea.setWrapStyleWord(true);
7782 c.fill = GridBagConstraints.HORIZONTAL;
7783 c.gridx = 0;
7784 c.gridy = 4;
7785 c.gridwidth = 4;
7786 panel.add(scrollpane, c);
7787
7788 // 'Send' button
7789 sendbutton = new JButton("Send");
7790 c.fill = GridBagConstraints.HORIZONTAL;
7791 c.gridx = 0;
7792 c.gridy = 5;
7793 c.gridwidth = 4;
7794 panel.add(sendbutton, c);
7795 }
7796 }
7797
7798
7799
7800
7801
7802
7803question 4-----------------------------
7804UDP Program – DNS CLIENT-SERVER
7805
7806UDP Program (DNS CLIENT-SERVER)
7807
7808AIM : To create a client server program to Domain Name System using the UDP protocol client server.
7809
7810ALGORITHM
7811
7812Server
7813
7814 Declare the necessary arrays and variables.
7815 Set server port address using socket().
7816 Get the current message.
7817 Connect to the client.
7818 Stop the process.
7819
7820Client
7821
7822 Set the client machine address.
7823 Connect to the server.
7824 Read from the server the current message.
7825 Display the current message.
7826 Close the connection.
7827
7828PROGRAM:
7829
7830UDPclient
7831
7832import java .io.*;
7833
7834import java.net.*;
7835
7836classUDPclient
7837
7838{
7839
7840public static DatagramSocket ds;
7841
7842public static intclientport=789,serverport=790;
7843
7844public static void main(String args[])throws Exception
7845
7846{
7847
7848byte buffer[]=new byte[1024];
7849
7850ds=new DatagramSocket(serverport);
7851
7852BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
7853
7854System.out.println(“server waitingâ€);
7855
7856InetAddressia=InetAddress.getLocalHost();
7857
7858while(true)
7859
7860{
7861
7862System.out.println(“Client:â€);
7863
7864String str=dis.readLine();
7865
7866if(str.equals(“endâ€))
7867
7868break;
7869
7870buffer=str.getBytes();
7871
7872ds.send(new DatagramPacket(buffer,str.length(),ia,clientport));
7873
7874DatagramPacket p=new DatagramPacket(buffer,buffer.length);
7875
7876ds.receive(p);
7877
7878String psx=new String(p.getData(),0,p.getLength());
7879
7880System.out.println(“Server:†+ psx);
7881
7882}
7883
7884}
7885
7886}
7887
7888UDP server
7889
7890import java.io.*;
7891
7892import java.net.*;
7893
7894classUDPserver
7895
7896{
7897
7898public static DatagramSocket ds;
7899
7900public static byte buffer[]=new byte[1024];
7901
7902public static intclientport=789,serverport=790;
7903
7904public static void main(String args[])throws Exception
7905
7906{
7907
7908ds=new DatagramSocket(clientport);
7909
7910System.out.println(“press ctrl+c to quit the programâ€);
7911
7912BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
7913
7914InetAddressia=InetAddress.getLocalHost();
7915
7916while(true)
7917
7918{
7919
7920DatagramPacket p=new DatagramPacket(buffer,buffer.length);
7921
7922ds.receive(p);
7923
7924String psx=new String(p.getData(),0,p.getLength());
7925
7926System.out.println(“Client:†+ psx);
7927
7928InetAddressib=InetAddress.getByName(psx);
7929
7930System.out.println(“Server output:â€+ib);
7931
7932String str=dis.readLine();
7933
7934if(str.equals(“endâ€))
7935
7936break;
7937
7938buffer=str.getBytes();
7939
7940ds.send(new DatagramPacket(buffer,str.length(),ia,serverport));
7941
7942}
7943
7944}
7945
7946}
7947
7948OUTPUT:
7949
7950UDPclient
7951
7952C:\Program Files\Java\jdk1.6.0\bin>javac UDPclient.java
7953
7954C:\Program Files\Java\jdk1.6.0\bin>java UDPclient
7955
7956Server waiting
7957
7958Client:www.yahoo.com
7959
7960UDPserver
7961
7962C:\Program Files\Java\jdk1.6.0\bin>javac UDPserver.java
7963
7964C:\Program Files\Java\jdk1.6.0\bin>java UDPserver
7965
7966Press ctrl+c to quit the program
7967
7968Client:www.yahoo.com
7969
7970Server output:www.yahoo.com/106.10.170.115
7971
7972RESULT:
7973
7974Thus client server program to Domain Name System using the UDP protocol client server has been executed and verified successfully.
7975
7976
7977
7978
7979
7980QUESTION 5------------------------------------------------
7981UDP DATE SERVER
7982
7983Server Program >>>>> Server.java
7984
7985
7986import java.net.*;
7987import java.io.*;
7988import java.util.*;
7989
7990public class Server {
7991
7992public static void main(String[] args) throws Exception{
7993
7994DatagramSocket ss=new DatagramSocket(1234);
7995
7996while(true){
7997
7998System.out.println("Server is up....");
7999
8000byte[] rd=new byte[100];
8001byte[] sd=new byte[100];
8002
8003DatagramPacket rp=new DatagramPacket(rd,rd.length);
8004
8005ss.receive(rp);
8006
8007InetAddress ip= rp.getAddress();
8008
8009int port=rp.getPort();
8010
8011Date d=new Date(); // getting system time
8012
8013String time= d + ""; // converting it to String
8014
8015sd=time.getBytes(); // converting that String to byte
8016
8017DatagramPacket sp=new DatagramPacket(sd,sd.length,ip,port);
8018
8019ss.send(sp);
8020
8021rp=null;
8022
8023System.out.println("Done !! ");
8024
8025}
8026
8027}
8028
8029}
8030
8031
8032Client program >>>>>>>>> Clientnew.java
8033import java.net.*;
8034import java.io.*;
8035
8036public class Clientnew {
8037
8038public static void main(String[] args) throws Exception{
8039
8040 System.out.println("Server Time >>>>");
8041
8042 DatagramSocket cs=new DatagramSocket();
8043
8044 InetAddress ip=InetAddress.getByName("localhost");
8045
8046 byte[] rd=new byte[100];
8047 byte[] sd=new byte[100];
8048
8049 DatagramPacket sp=new DatagramPacket(sd,sd.length,ip,1234);
8050
8051 DatagramPacket rp=new DatagramPacket(rd,rd.length);
8052
8053 cs.send(sp);
8054
8055 cs.receive(rp);
8056
8057 String time=new String(rp.getData());
8058
8059 System.out.println(time);
8060
8061 cs.close();
8062
8063}
8064
8065}
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
8076SIR UPLOADED MATERIAL
8077
8078
80791)Write a program to list all ports hosting a TCP server in a specified host.
8080
8081import java.net.*;
8082import java.io.*;
8083public class ports{
8084public static void main(String args[])
8085{
8086for(int i=1;i<1024;i++)
8087{
8088try{
8089Socket s=new Socket("127.0.0.1",i);
8090System.out.println("There is server on port"+i+"of 127.0.0.1");
8091}
8092catch(UnknownHostException e){
8093System.err.println(e);
8094break;
8095}
8096catch(IOException e){
8097//must not be server on this port
8098}
8099}
8100}
8101}
8102
81032)Write a program to display the server’s date and time details at the client end.
8104
8105import java.io.IOException;
8106import java.io.PrintWriter;
8107import java.net.ServerSocket;
8108import java.net.Socket;
8109import java.util.Date;
8110
8111public class dateserver {
8112
8113 public static void main(String[] args) throws IOException {
8114 ServerSocket listener = new ServerSocket(9090);
8115 try {
8116 while (true) {
8117 Socket socket = listener.accept();
8118 try {
8119 PrintWriter out =
8120 new PrintWriter(socket.getOutputStream(), true);
8121 out.println(new Date().toString());
8122 } finally {
8123 socket.close();
8124 }
8125 }
8126 }
8127 finally {
8128 listener.close();
8129 }
8130 }
8131}
8132
8133------------------------------
8134import java.io.*;
8135import java.net.Socket;
8136
8137public class dateClient {
8138
8139 public static void main(String[] args) throws IOException {
8140 Socket s = new Socket("127.0.0.1", 9090);
8141 BufferedReader input =
8142 new BufferedReader(new InputStreamReader(s.getInputStream()));
8143 String answer = input.readLine();
8144 System.out.println("The date and time details are "+answer );
8145
8146 System.exit(0);
8147 }
8148}
8149
8150
81513)Write a program to display the client’s address at the server end.
8152
8153
8154import java.io.*;
8155import java.net.*;
8156
8157public class ServerAddr
8158{
8159public static void main(String args[]) throws IOException
8160{
8161try
8162{
8163ServerSocket ss = new ServerSocket(6666);
8164System.out.println("Waiting for client.....");
8165
8166Socket s = ss.accept();
8167System.out.println("Connected to client....");
8168
8169DataInputStream in = new DataInputStream (s.getInputStream());
8170String line = null;
8171line = in.readUTF();
8172System.out.println("Client's IP adress: " + line);
8173}
8174catch (Exception e)
8175{
8176e.printStackTrace();
8177}
8178}
8179}
8180
8181--------------------------------
8182
8183import java.io.*;
8184import java.net.*;
8185
8186public class ClientAddr
8187{
8188public static void main(String args[]) throws IOException
8189{
8190try
8191{
8192InetAddress ipaddress = InetAddress.getByName("");
8193Socket s = new Socket(ipaddress,6666);
8194
8195System.out.println("Connected to the server...");
8196DataOutputStream out = new DataOutputStream(s.getOutputStream());
8197
8198String line = null;
8199System.out.println("Sending my IP Address to server...");
8200
8201line=ipaddress.getHostAddress();
8202
8203out.writeUTF(line);
8204out.flush();}
8205catch (Exception e)
8206{
8207e.printStackTrace();
8208}
8209}
8210}
8211
82124)Implement a simple message transfer from client to server process using TCP/IP.
8213
8214import java.io.*;
8215import java.net.*;
8216
8217public class Tcpserver
8218{
8219public static void main(String args[]) throws IOException
8220{
8221try
8222{
8223ServerSocket ss = new ServerSocket(6666);
8224System.out.println("Waiting for client.....");
8225
8226Socket s = ss.accept();
8227System.out.println("Connected to client....");
8228
8229DataInputStream in = new DataInputStream (s.getInputStream());
8230String line = null;
8231line = in.readUTF();
8232System.out.println("Mesage from Client:" + line);
8233}
8234catch (Exception e)
8235{
8236e.printStackTrace();
8237}
8238}
8239}
8240
8241--------------------------------------
8242import java.io.*;
8243import java.net.*;
8244
8245public class TCPClient
8246{
8247public static void main(String args[]) throws IOException
8248{
8249try
8250{
8251InetAddress ipaddress = InetAddress.getByName("");
8252Socket s = new Socket(ipaddress,6666);
8253DataInputStream read = new DataInputStream(System.in);
8254System.out.println("Connected to the server...");
8255DataOutputStream out = new DataOutputStream(s.getOutputStream());
8256
8257String line = null;
8258System.out.println("Write a message to the server..");
8259
8260line=read.readLine();
8261out.writeUTF(line);
8262out.flush();}
8263catch (Exception e)
8264{
8265e.printStackTrace();
8266}
8267}
8268}
8269
82705)Develop a TCP client/server application for transferring a text file from client to server
8271
8272
8273CLIENt:
8274import java.io.*;
8275 import java.net.*;
8276import java.util.*;
8277public class FTPClient {
8278public static void main(String args[]) throws Exception
8279
8280{
8281 Socket ss = new Socket("localhost",5000);
8282while(true)
8283{
8284
8285Scanner pbn = new Scanner(System.in);
8286System.out.println("Enter the path of the file ");
8287String path = pbn.nextLine();
8288System.out.println(path);
8289
8290File f = new File(path);
8291FileInputStream fis = new FileInputStream(f);
8292
8293BufferedInputStream bis = new BufferedInputStream(fis);
8294System.out.println("Sending file...");
8295
8296System.out.println("File sent");
8297
8298 }
8299
8300 }
8301}
8302server:
8303
8304//////////////////
8305import java.io.*;
8306import java.net.*;
8307import java.util.*;
8308public class FTPServer {
8309public static void main(String args[]) throws IOException
8310{ServerSocket ss = new ServerSocket(5000);
8311
8312 Scanner pbn = new Scanner(System.in);
8313 boolean flag = true;
8314 while(flag)
8315 {
8316 flag = false;
8317 try
8318 {System.out.println("waiting...");
8319Socket s = ss.accept();
8320System.out.println("Accepted connection "+s);
8321 System.out.println("Enter the path where you want to store the file");
8322 String path1 = pbn.nextLine();
8323 FileOutputStream fos = new FileOutputStream(path1);
8324 BufferedOutputStream bos = new BufferedOutputStream(fos);
8325 InputStream is = s.getInputStream();
8326 byte[] b = new byte[600000];
8327 int n = 0;
8328 int o = 0;
8329 while((n=is.read(b,o,b.length-o))>=0)
8330 {
8331 o+=n;
8332 }
8333 bos.write(b,0,o);
8334
8335 bos.flush();
8336 System.out.println("File Received");
8337 }
8338
8339 catch(FileNotFoundException f)
8340 {
8341 flag = true;
8342 String msg = f.getMessage();
8343 System.out.println("Error Message:"+msg);
8344 System.out.println("Please Enter a correct file path");
8345 }
8346 }
8347
8348 }
8349}
8350
8351
83526. Implement a TCP based server program to authenticate the client’s User Name and Password. The validity of the client must be sent as the reply message to the client and display it on the standard output.
8353
8354import java.io.*;
8355import java.net.*;
8356
8357public class AuthServer
8358{
8359 public static void main(String args[]) throws IOException
8360 {
8361 try
8362 {
8363 ServerSocket ss = new ServerSocket(6666);
8364 System.out.println("Waiting for client.....");
8365 Socket s = ss.accept();
8366 System.out.println("Connected to client....");
8367
8368 DataInputStream in = new DataInputStream (s.getInputStream());
8369 DataOutputStream out = new DataOutputStream (s.getOutputStream());
8370
8371 String line = null;
8372 String line1 = null;
8373 String sendline = null;
8374
8375
8376line = in.readUTF();
8377line1 = in.readUTF();
8378 if((line.equals("aid")|| line.equals("bid"))&&((line1.equals("apass")|| line1.equals("bpass"))))
8379 {
8380 sendline ="Valid user id and password.Successfully logged in !!!!";
8381 out.writeUTF(sendline);
8382 out.flush();
8383
8384 }
8385 else
8386
8387 {
8388 sendline ="Invalid details";
8389 out.writeUTF(sendline);
8390 out.flush();
8391 }
8392
8393 }
8394 catch (Exception e)
8395 {
8396 e.printStackTrace();
8397 }
8398 }
8399}
8400
8401import java.io.*;
8402import java.net.*;
8403
8404public class AuthClient
8405{
8406 public static void main(String args[]) throws IOException
8407 {
8408 try
8409 {
8410 InetAddress ipaddress = InetAddress.getByName("127.0.0.1");
8411 Socket s = new Socket(ipaddress,6666);
8412
8413 System.out.println("Connected to the server...");
8414
8415 DataInputStream read = new DataInputStream(System.in);
8416
8417 DataInputStream in = new DataInputStream(s.getInputStream());
8418 DataOutputStream out = new DataOutputStream(s.getOutputStream());
8419
8420 String line = null;
8421 String line1 = null;
8422 String receiveline = null;
8423
8424 System.out.println("Enter User id ");
8425 line = read.readLine();
8426 out.writeUTF(line);
8427 out.flush();
8428
8429System.out.println("Enter Password ");
8430line1 = read.readLine();
8431out.writeUTF(line1);
8432out.flush();
8433
8434
8435 receiveline = in.readUTF();
8436 System.out.println("SERVER: " + receiveline);
8437
8438
8439 }
8440 catch (Exception e)
8441 {
8442 e.printStackTrace();
8443 }
8444 }
8445}
8446
84477. Write a program to develop a simple (text based) Chat application using TCP/IP.
8448//chat
8449import java.io.*;
8450import java.net.*;
8451
8452public class TCPserver
8453{
8454 public static void main(String args[]) throws IOException
8455 {
8456 try
8457 {
8458 ServerSocket ss = new ServerSocket(6666);
8459 System.out.println("Waiting for client.....");
8460DataInputStream read = new DataInputStream(System.in);
8461 Socket s = ss.accept();
8462 System.out.println("Connected to client....");
8463
8464 DataInputStream in = new DataInputStream (s.getInputStream());
8465 DataOutputStream out = new DataOutputStream (s.getOutputStream());
8466
8467 String line = null;
8468
8469
8470 do
8471 {
8472 line = in.readUTF();
8473 System.out.println("CLIENT: " + line);
8474 line = read.readLine();
8475 out.writeUTF(line);
8476 out.flush();
8477
8478 System.out.println("Waiting for the next line.....");
8479 }while(!line.equals("bye"));
8480 }
8481 catch (Exception e)
8482 {
8483 e.printStackTrace();
8484 }
8485 }
8486}
8487
8488
8489//chat
8490import java.io.*;
8491import java.net.*;
8492
8493public class TCPClient
8494{
8495 public static void main(String args[]) throws IOException
8496 {
8497 try
8498 {
8499 InetAddress ipaddress = InetAddress.getByName("127.0.0.1");
8500 Socket s = new Socket(ipaddress,6666);
8501
8502 System.out.println("Connected to the server...");
8503
8504 DataInputStream read = new DataInputStream(System.in);
8505
8506 DataInputStream in = new DataInputStream(s.getInputStream());
8507 DataOutputStream out = new DataOutputStream(s.getOutputStream());
8508
8509 String line = null;
8510 String receiveline = null;
8511
8512 System.out.println("Enter data to send to the server: ");
8513
8514 do
8515 {
8516 System.out.print("CLIENT: ");
8517 line = read.readLine();
8518 out.writeUTF(line);
8519 out.flush();
8520
8521 receiveline = in.readUTF();
8522 System.out.println("SERVER: " + receiveline);
8523
8524 }while(!line.equals("bye"));
8525 }
8526 catch (Exception e)
8527 {
8528 e.printStackTrace();
8529 }
8530 }
8531}
8532
85338. Implement a simple message transfer from client to server process using UDP.
8534import java.io.*;
8535import java.net.*;
8536class UDPServerss {
8537public static void main(String args[]) throws Exception {
8538 DatagramSocket serverSocket = new DatagramSocket(9876);
8539
8540 byte[] receiveData = new byte[1024];
8541 byte[] sendData = new byte[1024];
8542 while(true) {
8543
8544 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
8545 serverSocket.receive(receivePacket);
8546 String sentence = new String( receivePacket.getData());
8547 System.out.println("RECEIVED: " + sentence);
8548 InetAddress IPAddress = receivePacket.getAddress();
8549 int port = receivePacket.getPort();
8550 String capitalizedSentence = sentence.toUpperCase();
8551 sendData = capitalizedSentence.getBytes();
8552 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
8553 serverSocket.send(sendPacket);
8554 }
8555}
8556}
8557import java.io.*;
8558import java.net.*;
8559 class UDPClientssss {
8560 public static void main(String args[]) throws Exception {
8561 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
8562 DatagramSocket clientSocket = new DatagramSocket();
8563 InetAddress IPAddress = InetAddress.getByName("localhost");
8564 byte[] sendData = new byte[1024];
8565 byte[] receiveData = new byte[1024];
8566 String sentence = inFromUser.readLine();
8567 sendData = sentence.getBytes();
8568 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
8569 clientSocket.send(sendPacket);
8570 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
8571 clientSocket.receive(receivePacket);
8572 String modifiedSentence = new String(receivePacket.getData());
8573 System.out.println("FROM SERVER:" + modifiedSentence);
8574 clientSocket.close();
8575 }
8576 }
8577
85789. Write a program to implement an Echo UDP server. Test the working of the server by writing a client application.
8579import java.net.*;
8580 import java.util.*;
8581 public class EchoServer
8582{
8583 public static void main( String args[]) throws Exception
8584 {
8585 DatagramSocket dsock = new DatagramSocket(7);
8586byte arr1[] = new byte[150];
8587DatagramPacket dpack = new DatagramPacket(arr1, arr1.length );
8588while(true)
8589{ dsock.receive(dpack);
8590byte arr2[] = dpack.getData();
8591 int packSize = dpack.getLength();
8592String s2 = new String(arr2, 0, packSize);
8593System.out.println( new Date( ) + " " + dpack.getAddress( ) + " : " + dpack.getPort( ) + " "+ s2);
8594dsock.send(dpack);
8595}
8596}
8597}----------------------------------
8598import java.net.*;
8599import java.util.*;
8600 public class EchoClient
8601{ public static void main( String args[] ) throws Exception {
8602InetAddress add = InetAddress.getByName("127.0.0.1");
8603DatagramSocket dsock = new DatagramSocket( );
8604 String message1 = "This is client calling";
8605 byte arr[] = message1.getBytes( );
8606 DatagramPacket dpack = new DatagramPacket(arr, arr.length, add, 7);
8607 dsock.send(dpack); // send the packet
8608Date sendTime = new Date( ); // note the time of sending the message
8609dsock.receive(dpack); // receive the packet
8610String message2 = new String(dpack.getData( ));
8611 Date receiveTime = new Date( ); // note the time of receiving the message
8612 System.out.println((receiveTime.getTime( ) - sendTime.getTime( )) + " milliseconds echo time for " + message2);
8613 }
8614 }
8615
861610. Write a program to implement the DISCARD server using UDP. Test the working of the server by writing a client application. Let the server log the client details on its standard output.
8617import java.io.*;
8618import java.net.*;
8619public class UDPdiscardServer {
8620 public final static int DEFAULT_PORT=9;
8621 public final static int MAX_PACKET_SIZE=65507;
8622public static void main(String args[])
8623{
8624 int port=DEFAULT_PORT;
8625 byte[] buffer=new byte[MAX_PACKET_SIZE];
8626
8627 try{
8628 port=9;
8629 }
8630catch(Exception ex)
8631{}
8632 try{
8633 DatagramSocket server=new DatagramSocket(port);
8634DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
8635
8636while(true)
8637{
8638 try{
8639 server.receive(packet);
8640 String s=new String(packet.getData(),0,packet.getLength(),"UTF-8");
8641 System.out.println(packet.getAddress()+" at port "+packet.getPort()+" says "+s);
8642 packet.setLength(buffer.length);
8643 }
8644 catch(IOException ex){ System.err.println(ex);}
8645}
8646
8647 }
8648 catch(SocketException ex)
8649 {System.err.println(ex);}
8650}
8651}
8652import java.io.*;
8653import java.net.*;
8654public class UDPdiscardClient {
8655 public final static int DEFAULT_PORT=9;
8656
8657public static void main(String args[])
8658{String hostname="localhost";
8659 int port=DEFAULT_PORT;
8660
8661
8662 try{
8663 InetAddress server=InetAddress.getByName(hostname);
8664 BufferedReader userInput=new BufferedReader(new InputStreamReader(System.in));
8665 DatagramSocket theSocket=new DatagramSocket();
8666
8667 while(true)
8668 {
8669 String theLine=userInput.readLine();
8670 if(theLine.equals(".")) break;
8671 byte[] data=theLine.getBytes("UTF-8");
8672 DatagramPacket theOutput=new DatagramPacket(data,data.length,server,port);
8673 theSocket.send(theOutput);
8674 }
8675 }
8676 catch(UnknownHostException ex)
8677 {System.err.println(ex);}
8678 catch(SocketException ex)
8679 {System.err.println(ex);}
8680 catch(IOException ioex)
8681 {System.err.println(ioex);}
8682}
8683}
8684Find the physical address of a host when its logical address is known (ARP protocol) using TCP/IP.
8685
8686import java.net.InetAddress;
8687import java.net.NetworkInterface;
8688import java.net.SocketException;
8689import java.net.UnknownHostException;
8690import java.util.Scanner;
8691
8692public class MacAddress {
8693 public static void main(String[] args)
8694 {
8695 try
8696 {
8697 Scanner console = new Scanner(System.in);
8698 System.out.println("Enter System Name: ");
8699 String ipaddr = console.nextLine();
8700 InetAddress address = InetAddress.getByName(ipaddr);
8701 System.out.println("address = "+address);
8702 NetworkInterface ni = NetworkInterface.getByInetAddress(address);
8703 if (ni!=null)
8704 {
8705 byte[] mac = ni.getHardwareAddress();
8706 if (mac != null)
8707 {
8708 System.out.print("MAC Address : ");
8709 for (int i=0; i<mac.length; i++)
8710 {
8711 System.out.format("%02X%s", mac[i], (i<mac.length - 1) ? "-" :"");
8712 }
8713 }
8714 else
8715 {
8716 System.out.println("Address doesn't exist or is not accessible/");
8717
8718 }
8719 }
8720 else
8721 {
8722 System.out.println("Network Interface for the specified address is not found");
8723 }
8724 }
8725 catch(UnknownHostException he)
8726 {
8727 }
8728 catch(SocketException e)
8729 {
8730 }
8731 }
8732}
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
8744basics
8745Basic network commands
8746ping
8747The ping command (named after the sound of an active sonar system) sends echo requests to the host
8748specified on the command line, and lists the responses received.
8749$ ping ipAddress or hostname
8750e.g
8751$ ping www.vit.ac.in
8752• ping - sends an ICMP ECHO_REQUEST packet to the specified host. If the host responds, an
8753ICMP packet is received.
8754• One can “ping†an IP address to see if a machine is alive.
8755• It provides a very quick way to see if a machine is up and connected to the network.
8756netstat
8757• It works with the LINUX Network Subsystem, it will tell you what the status of ports are ie. open,
8758closed, waiting connections. It is used to display the TCP/IP network protocol statistics and
8759information.
8760tcpdump
8761This is a sniffer, a program that captures packets off a network interface and interprets them.
8762hostname
8763Tells the user the host name of the computer they are logged into.
8764traceroute
8765traceroute will show the route of a packet. It attempts to list the series of hosts through which your
8766packets travel on their way to a given destination.
8767Command syntax:
8768traceroute machine_name_or_ip
8769e.g traceroute www.vit.ac.in
8770Each host will be displayed, along with the response times at each host.
8771finger
8772Retrieves information about the specified user.
8773e.g finger bit50001
8774ifconfig ( In Windows use ipconfig )
8775This command is used to configure network interfaces, or to display their current configuration.
8776dig
8777The "domain information groper" tool. If you give a hostname as an argument to output information
8778about that host, including it's IP address, hostname and various other information.
8779e.g dig vitlinux
8780telnet
8781telnet allows you to log in to a computer, just as if you were sitting at the terminal. Once your
8782username and password are verified, you are given a shell prompt. From here, you can do anything
8783requiring a text console.
8784ftp
8785To connect to an FTP server use
8786ftp ipaddress
8787netstat
8788Displays contents of /proc/net files. It works with the LINUX Network Subsystem, it will tell
8789you what the status of ports are ie. open, closed, waiting, masquerade connections. It will also
8790display various other things. It has many different options.
8791tcpdump
8792This is a sniffer, a program that captures packets off a network interface and interprets them
8793for you. It understands all basic internet protocols, and can be used to save entire packets for
8794later inspection.
8795ping
8796The ping command (named after the sound of an active sonar system) sends echo requests to
8797the host you specify on the command line, and lists the responses received their round trip
8798time.
8799You simply use ping as:
8800ping ip_or_host_name
8801hostname
8802Tells the user the host name of the computer they are logged into. Note: may be called host.
8803traceroute
8804traceroute will show the route of a packet. It attempts to list the series of hosts through which
8805your packets travel on their way to a given destination. Also have a look at xtraceroute (one
8806of several graphical equivalents of this program).
8807Command syntax:
8808traceroute machine_name_or_ip
8809tracepath
8810tracepath performs a very simlar function to traceroute the main difference is that tracepath
8811doesn't take complicated options.
8812Command syntax:
8813tracepath machine_name_or_ip
8814findsmb
8815findsmb is used to list info about machines that respond to SMB name queries (for example
8816windows based machines sharing their hard disk's).
8817Command syntax:
8818Findsmb
8819This would find all machines possible, you may need to specify a particular subnet to query
8820those machines only...
8821nmap
8822“ network exploration tool and security scannerâ€. nmap is a very advanced network tool used
8823to query machines (local or remote) as to whether they are up and what ports are open on
8824these machines.
8825A simple usage example:
8826nmap machine_name
8827This would query your own machine as to what ports it keeps open. nmap is a very powerful
8828tool, documentation is available on the nmap site as well as the information in the manual
8829page.
8830telnet
8831Someone once stated that telnet(1) was the coolest thing he had ever seen on computers. The ability
8832to remotely log in and do stuff on another computer is what separates Unix and Unix-like operating
8833systems from other operating systems.
8834telnet allows you to log in to a computer, just as if you were sitting at the terminal. Once your
8835username and password are verified, you are given a shell prompt. From here, you can do anything
8836requiring a text console. Compose email, read newsgroups, move files around, and so on. If you are
8837running X and you telnet to another machine, you can run X programs on the remote computer and
8838display them on yours.
8839To login to a remote machine, use this syntax:
8840% telnet <hostname>
8841If the host responds, you will receive a login prompt. Give it your username and password. That's it.
8842You are now at a shell. To quit your telnet session, use either the exit command or the logout
8843command.
8844telnet does not encrypt the information it sends. Everything is sent in plain text, even passwords.
8845It is not advisable to use telnet over the Internet. Instead, consider the Secure Shell. It encrypts
8846all traffic and is available for free.
8847The other use of telnet
8848Now that we have convinced you not to use the telnet protocol anymore to log into a remote machine,
8849we'll show you a couple of useful ways to use telnet.
8850You can also use the telnet command to connect to a host on a certain port.
8851% telnet <hostname> [port]
8852This can be quite handy when you quickly need to test a certain service, and you need full control
8853over the commands, and you need to see what exactly is going on. You can interactively test or use
8854an SMTP server, a POP3 server, an HTTP server, etc. this way.
8855In the next figure you'll see how you can telnet to a HTTP server on port 80, and get some basic
8856information from it.
8857Figure 13-1. Telnetting to a webserver
8858% telnet store.slackware.com 80
8859Trying 69.50.233.153...
8860Connected to store.slackware.com.
8861Escape character is '^]'.
8862HEAD / HTTP/1.0
8863HTTP/1.1 200 OK
8864Date: Mon, 25 Apr 2005 20:47:01 GMT
8865Server: Apache/1.3.33 (Unix) mod_ssl/2.8.22 OpenSSL/0.9.7d
8866Last-Modified: Fri, 18 Apr 2003 10:58:54 GMT
8867ETag: "193424-c0-3e9fda6e"
8868Accept-Ranges: bytes
8869Content-Length: 192
8870Connection: close
8871Content-Type: text/html
8872Connection closed by foreign host.
8873%
88741-)arp :
8875When we need an Ethernet (MAC) address we can use arp(address resolution protocol).
8876In other words it shows the physical address of an host.
8877Example:
8878C:\Documents and Settings\sysadm>arp -a
8879Interface: 169.254.195.199 --- 0x2
8880Internet Address Physical Address Type
8881216.109.127.60 00-53-45-00-00-00 static
88822-)nslookup:
8883Displays information from Domain Name System (DNS) name servers.
8884Example:
8885C:\Documents and Settings\sysadm>nslookup itu.dk
8886Server: ns3.inet.tele.dk
8887Address: 193.162.153.164
8888Non-authoritative answer:
8889Name: itu.dk
8890Address: 130.226.133.2
8891NOTE :If you write the command as above it shows as default your pc's server name firstly.
8892C:\Documents and Settings\sysadm>nslookup mail.yahoo.com itu.dk
8893Server: superman.itu.dk
8894Address: 130.226.133.2
8895Non-authoritative answer:
8896Name: login.yahoo.akadns.net
8897Address: 216.109.127.60
8898Aliases: mail.yahoo.com, login.yahoo.com
8899NOTE:Remark that in the second example we do not see the default server name.
8900There are many nslookup with optional commands.To read them type nslookup and enter
8901then type help and enter.
89023-)finger:
8903Displays the information about a user on the system.
8904Example:
8905NOTE :I could not find out the name of the server that we log on (windows) at the school.
8906Sysadmin does not know that either:o)
8907But as an example I tried it on the our unix server.
8908[hilmiolgun@ssh hilmiolgun]$ finger
8909Login Name Tty Idle Login Time Office Office Phone
8910adel Adel Abu-Sharkh pts/1 7 Sep 10 00:11 (cpe.atm2-0-
89111091080.0x50a0bcb2.albnxx13.customer.tele.dk)
8912adel Adel Abu-Sharkh pts/2 9 Sep 9 23:56 (cpe.atm2-0-
89131091080.0x50a0bcb2.albnxx13.customer.tele.dk)
8914hilmiolgun Hilmi Olgun pts/9 Sep 10 00:20 (0x3ef3e2fe.albnxx8.adsl.tele.dk)
8915hm Hanne Munkholm pts/6 1:56 Sep 8 21:27 (off180.palombia.dk)
8916jcg Jens Christian Godsk pts/4 1d Sep 8 10:28 (toscana.itu.dk)
8917kaj Kenneth Ahn Jensen pts/7 Sep 10 00:11 (cpe.atm2-0-
891854493.0x50a4ad32.boanxx12.customer.tele.dk)
8919root root pts/8 1 Sep 10 00:12 (sysadm2.itu.dk)
8920troels Troels Arvin pts/5 3:49 Sep 9 20:31 (62.79.119.132.adsl.vbr.worldonline.dk)
8921webclaus Claus Bech Rasmussen pts/0 6 Sep 10 00:11 (port967.ds1-khk.adsl.cybercity.dk)
8922NOTE :What I did is :I first check the online users,and get a list of them(above).
8923Then i just choosed one user to get information about him(below)
8924[hilmiolgun@ssh hilmiolgun]$ finger hm
8925Login: hm Name: Hanne Munkholm
8926Directory: /import/home/hm Shell: /bin/bash
8927On since Mon Sep 8 21:27 (CEST) on pts/6 from off180.palombia.dk
89281 hour 56 minutes idle
8929Last login Tue Sep 9 11:05 (CEST) on pts/12 from stud127.itu.dk
8930New mail received Mon Nov 11 23:01 2002 (CET)
8931Unread since Sat Oct 5 00:00 2002 (CEST)
8932Plan:
8933World Domination... fast.
8934[hilmiolgun@ssh hilmiolgun]$
89354-)ping:
8936Simpy shows if the remote machine is available or not....
8937Example:
8938C:\Documents and Settings\sysadm>ping webmail.itu.dk
8939Pinging tarzan.itu.dk [130.226.133.3] with 32 bytes of data:
8940Reply from 130.226.133.3: bytes=32 time=29ms TTL=55
8941Reply from 130.226.133.3: bytes=32 time=30ms TTL=55
8942Reply from 130.226.133.3: bytes=32 time=30ms TTL=55
8943Reply from 130.226.133.3: bytes=32 time=30ms TTL=55
8944Ping statistics for 130.226.133.3:
8945Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
8946Approximate round trip times in milli-seconds:
8947Minimum = 29ms, Maximum = 30ms, Average = 29ms
8948NOTE :Remark that the remote machine is replying.Otherwise the output will be "Request time out"
8949which means the
8950remote machine is not working well.(Not answering)
89515-)tracert:
8952It simply shows the path between source and destination address.
8953Example:
8954C:\Documents and Settings\sysadm>tracert webmail.itu.dk
8955Tracing route to tarzan.itu.dk [130.226.133.3]
8956over a maximum of 30 hops:
89571 * * * Request timed out.
89582 29 ms 19 ms 29 ms ge-0-2-1-2.1000M.albnxu1.ip.tele.dk [195.249.1.2 9]
89593 29 ms 29 ms 19 ms pos1-0.622M.lynxg1.ip.tele.dk [195.249.2.46]
89604 29 ms 19 ms 29 ms herman.fsknet.lyngby.forskningsnettet.dk [192.38 .7.1]
89615 29 ms 29 ms 19 ms 130.225.244.214
89626 29 ms 29 ms 29 ms 1.ku.forskningsnettet.dk [130.225.245.90]
89637 29 ms 29 ms 29 ms rk.itu.forskningsnettet.dk [130.226.249.30]
89648 29 ms 29 ms 29 ms 130.225.245.86
89659 29 ms 29 ms 29 ms tarzan.itu.dk [130.226.133.3]
8966Trace complete.
89676-)ftp:
8968For file transferring..(File transfer protocol)
8969Example:Lets you dont have an ftp software and you want to get a file from your school harddisk.
8970So to do that:
8971C:\Documents and Settings\sysadm>ftp
8972ftp> open
8973To ftp.itu.dk
8974Connected to ssh.itu.dk.
8975220 ProFTPD 1.2.8rc2 Server (ProFTPD Default Installation) [ssh.it-c.dk]
8976NOTE:What am I doing is simply:typing them one-by-one(after each typing remember to enter)
8977ftp,open,ftp.itu.dk
8978User (ssh.itu.dk:(none)): hilmiolgun
8979331 Password required for hilmiolgun.
8980Password:
8981230 User hilmiolgun logged in.
8982NOTE:The server will require username and password..
8983ftp> help
8984Commands may be abbreviated. Commands are:
8985! delete literal prompt send
8986? debug ls put status
8987append dir mdelete pwd trace
8988ascii disconnect mdir quit type
8989bell get mget quote user
8990binary glob mkdir recv verbose
8991bye hash mls remotehelp
8992cd help mput rename
8993close lcd open rmdir
8994ftp> help dir
8995dir List contents of remote directory
8996NOTE: If it is your first time to those commands just type help and get the commands.If you dont
8997know how to use
8998them type help commandname..
8999ftp> dir
9000200 PORT command successful
9001150 Opening ASCII mode data connection for file list
9002drwx------ 4 hilmiolgun hilmiolgun 155 Jul 1 14:02 Desktop
9003drwx------ 2 hilmiolgun hilmiolgun 4096 May 30 10:21 Mail
9004drwxr-xr-x 5 hilmiolgun hilmiolgun 90 Sep 2 02:59 MobilePositionSDK
9005drwx------ 7 hilmiolgun hilmiolgun 4096 Aug 8 2002 NTnetscape
9006drwxr--r-- 13 hilmiolgun hilmiolgun 4096 Sep 4 01:56 New Folder
9007-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 TTI409B
9008drwx------ 2 hilmiolgun hilmiolgun 6 Jan 21 2002 cgi-bin
9009-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 geu
9010-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 hilmiolgun
9011drwxr-xr-x 6 hilmiolgun hilmiolgun 4096 Aug 14 15:59 image
9012drwxr-xr-x 3 hilmiolgun hilmiolgun 4096 Jul 29 16:03 jmf20-apidocs
9013drwxr-xr-x 4 hilmiolgun hilmiolgun 4096 Sep 9 14:10 NOTEsieee
9014drwx------ 2 hilmiolgun hilmiolgun 6 Feb 21 2002 nsmail
9015drwx------ 3 hilmiolgun hilmiolgun 103 Feb 21 2002 office52
9016drwx------ 2 hilmiolgun hilmiolgun 6 Jan 21 2002 private
9017drwxr--rwx 2 hilmiolgun hilmiolgun 4096 Aug 23 12:02 public_html
9018drwxr-xr-x 5 hilmiolgun hilmiolgun 4096 Sep 6 03:30 speech
9019-rw-rw-r-- 1 hilmiolgun hilmiolgun 2630 Sep 9 13:58 test.txt
9020-rw-rw-r-- 1 hilmiolgun hilmiolgun 148 Sep 9 14:03 testing.txt
9021226 Transfer complete.
9022ftp: 1318 bytes received in 0,24Seconds 5,49Kbytes/sec.
9023ftp> get testing.txt
9024200 PORT command successful
9025150 Opening ASCII mode data connection for testing.txt (148 bytes)
9026226 Transfer complete.
9027ftp: 161 bytes received in 0,02Seconds 8,05Kbytes/sec.
9028NOTE :After taking a look to the school harddisk ,I copied a file "testing.txt" to my local harddisk....
9029ftp> !dir
9030Volume in drive C has no label.
9031Volume Serial Number is 0868-D52D
9032Directory of C:\Documents and Settings\sysadm
903310-09-2003 00:21 <DIR> .
903410-09-2003 00:21 <DIR> ..
903531-08-2003 07:28 <DIR> .java
903625-04-2003 12:18 <DIR> .javaws
903723-04-2003 15:26 <DIR> .jpi_cache
903826-08-2003 04:59 <DIR> .Nokia
903907-09-2003 01:46 12.546 .plugin140_03.trace
904007-09-2003 04:46 693 .plugin141_02.trace
904107-09-2003 01:20 164 .saves-3824-IBMR31IMAGE
904207-09-2003 01:20 <DIR> Desktop
904307-09-2003 08:05 <DIR> Favorites
904406-09-2003 05:29 80.140 love.wav
904509-09-2003 23:45 <DIR> mindterm
904609-09-2003 11:02 <DIR> My Documents
904710-09-2003 00:21 2.903 plugin131_08.trace
904825-04-2003 11:44 <DIR> Start Menu
904906-09-2003 21:21 <DIR> studio5se_user
905006-09-2003 05:32 18 test.txt
905106-09-2003 05:20 70 testing
905210-09-2003 00:37 161 testing.txt
905326-08-2003 03:46 <DIR> WINDOWS
90548 File(s) 96.695 bytes
905513 Dir(s) 3.842.056.192 bytes free
9056ftp> send love.wav
9057200 PORT command successful
9058150 Opening ASCII mode data connection for love.wav
9059226 Transfer complete.
9060ftp: 80140 bytes sent in 3,97Seconds 20,21Kbytes/sec.
9061ftp> dir
9062200 PORT command successful
9063150 Opening ASCII mode data connection for file list
9064drwx------ 4 hilmiolgun hilmiolgun 155 Jul 1 14:02 Desktop
9065drwx------ 2 hilmiolgun hilmiolgun 4096 May 30 10:21 Mail
9066drwxr-xr-x 5 hilmiolgun hilmiolgun 90 Sep 2 02:59 MobilePositionSDK
9067drwx------ 7 hilmiolgun hilmiolgun 4096 Aug 8 2002 NTnetscape
9068drwxr--r-- 13 hilmiolgun hilmiolgun 4096 Sep 4 01:56 New Folder
9069-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 TTI409B
9070drwx------ 2 hilmiolgun hilmiolgun 6 Jan 21 2002 cgi-bin
9071-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 geu
9072-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 hilmiolgun
9073drwxr-xr-x 6 hilmiolgun hilmiolgun 4096 Aug 14 15:59 image
9074drwxr-xr-x 3 hilmiolgun hilmiolgun 4096 Jul 29 16:03 jmf20-apidocs
9075-rw-rw-r-- 1 hilmiolgun hilmiolgun 80137 Sep 9 22:36 love.wav
9076drwxr-xr-x 4 hilmiolgun hilmiolgun 4096 Sep 9 14:10 NOTEsieee
9077drwx------ 2 hilmiolgun hilmiolgun 6 Feb 21 2002 nsmail
9078drwx------ 3 hilmiolgun hilmiolgun 103 Feb 21 2002 office52
9079drwx------ 2 hilmiolgun hilmiolgun 6 Jan 21 2002 private
9080drwxr--rwx 2 hilmiolgun hilmiolgun 4096 Aug 23 12:02 public_html
9081drwxr-xr-x 5 hilmiolgun hilmiolgun 4096 Sep 6 03:30 speech
9082-rw-rw-r-- 1 hilmiolgun hilmiolgun 2630 Sep 9 13:58 test.txt
9083-rw-rw-r-- 1 hilmiolgun hilmiolgun 148 Sep 9 14:03 testing.txt
9084226 Transfer complete.
9085ftp: 1387 bytes received in 0,07Seconds 19,81Kbytes/sec.
9086ftp>
9087NOTE:At the end first looking at the local working directory and sending a file "love.wav" to the
9088school harddisk.
90897-)net:
9090It has many options,which are for checking/starting/stopping nt
9091services,users,messaging,configuration and so on...
9092Some of those options require administration privileges..
9093Example:
9094NOTE: To have an overview of commands options....
9095C:\Documents and Settings\sysadm>net
9096The syntax of this command is:
9097NET COMMANDS
9098NET [ ACCOUNTS | COMPUTER | CONFIG | CONTINUE | FILE | GROUP | HELP |
9099HELPMSG | LOCALGROUP | NAME | PAUSE | PRINT | SEND | SESSION |
9100SHARE | START | STATISTICS | STOP | TIME | USE | USER | VIEW ]
9101NOTE: And furthermore to get an overview of a specific option ...
9102C:\Documents and Settings\sysadm>net help print
9103The syntax of this command is:
9104NET PRINT
9105\\computername\sharename
9106[\\computername] job# [/HOLD | /RELEASE | /DELETE]
9107NET PRINT displays print jobs and shared queues.
9108For each queue, the display lists jobs, showing the size
9109and status of each job, and the status of the queue.
9110\\computername Is the name of the computer sharing the printer
9111queue(s).
9112sharename Is the name of the shared printer queue.
9113job# Is the identification number assigned to a print
9114job. A computer with one or more printer queues
9115assigns each print job a unique number.
9116/HOLD Prevents a job in a queue from printing.
9117The job stays in the printer queue, and other
9118jobs bypass it until it is released.
9119/RELEASE Reactivates a job that is held.
9120/DELETE Removes a job from a queue.
9121NET HELP command | MORE displays Help one screen at a time.
9122Finally in addition to above there are also those commands: hostname ,lpq, lpr ,rsh ,tftp ,nbstat
9123,netstat.
9124To get familiar with those commands simply type commandname /? at the command line.
9125C:\>net
9126The syntax of this command is:
9127NET [ ACCOUNTS | COMPUTER | CONFIG | CONTINUE | FILE | GROUP | HELP |
9128HELPMSG | LOCALGROUP | NAME | PAUSE | PRINT | SEND | SESSION |
9129SHARE | START | STATISTICS | STOP | TIME | USE | USER | VIEW ]
9130C:\>net use
9131New connections will not be remembered.
9132Status Local Remote Network
9133-------------------------------------------------------------------------------
9134OK F: \\cse-sec\fac Microsoft Windows Network
9135C:\>net user
9136User accounts for \\CSE-DEPT-05
9137-------------------------------------------------------------------------------
9138Administrator Guest
9139C:\>net statistics
9140Statistics are available for the following running services:
9141Server
9142Workstation
9143Displays protocol statistics and current TCP/IP network connections.
9144NETSTAT [-a] [-e] [-n] [-s] [-p proto] [-r] [interval]
9145-a Displays all connections and listening ports.
9146-e Displays Ethernet statistics. This may be combined with the
9147-s option.
9148-n Displays addresses and port numbers in numerical form.
9149-p proto Shows connections for the protocol specified by proto; proto
9150may be TCP or UDP. If used with the -s option to display
9151per-protocol statistics, proto may be TCP, UDP, or IP.
9152-r Displays the routing table.
9153-s Displays per-protocol statistics. By default, statistics
9154are shown for TCP, UDP and IP; the -p option may be used
9155to specify a subset of the default.
9156interval Redisplays selected statistics, pausing interval seconds
9157between each display. Press CTRL+C to stop redisplaying
9158statistics. If omitted, netstat will print the current
9159configuration information once.
9160C:\>net name
9161Name
9162-------------------------------------------------------------------------------
9163CSE-DEPT-05
9164C:\>net session
9165Computer User name Client Type Opens Idle time
9166-------------------------------------------------------------------------------
9167\\ENGLISH-03 Windows NT 1381 0 00:10:47
9168\\ENGLISHBDC Windows NT 1381 0 00:02:01
9169C:\>net accounts
9170Force user logoff how long after time expires?: Never
9171Minimum password age (days): 0
9172Maximum password age (days): 42
9173Minimum password length: 0
9174Length of password history maintained: None
9175Lockout threshold: Never
9176Lockout duration (minutes): 30
9177Lockout observation window (minutes): 30
9178Computer role: WORKSTATION
9179C:\>net localgroup
9180Aliases for \\CSE-DEPT-05
9181-------------------------------------------------------------------------------
9182*Administrators *Backup Operators *Guests
9183*Power Users *Replicator *Users
9184C:\>net config server
9185Server Name \\CSE-DEPT-05
9186Server Comment
9187Software version Windows NT 4.0
9188Server is active on NetBT_DLKRTS1 (0050ba8b326b) NetBT_DLKRTS1
9189(0050ba8b326b) NwlnkIpx (0050ba8b326b) NwlnkNb (0050ba8b326b) Nbf_DLKRTS1 (0050
9190ba8b326b)
9191Server hidden No
9192Maximum Logged On Users 10
9193Maximum open files per session 2048
9194Idle session time (min) 15
9195C:\>net config workstation
9196Computer name \\CSE-DEPT-05
9197User name Administrator
9198Workstation active on NwlnkNb (0050BA8B326B) NetBT_DLKRTS1 (0050B
9199A8B326B) Nbf_DLKRTS1 (0050BA8B326B)
9200Software version Windows NT 4.0
9201Workstation domain WORKGROUP
9202Logon domain CSE-DEPT-05
9203COM Open Timeout (sec) 3600
9204COM Send Count (byte) 16
9205COM Send Timeout (msec) 250
9206C:\>net share
9207Share name Resource Remark
9208-------------------------------------------------------------------------------
9209D$ D:\ Default share
9210IPC$ Remote IPC
9211C$ C:\ Default share
9212ADMIN$ C:\WINNT Remote Admin
9213E$ E:\ Default share
9214abishek E:\abishek
9215akshu E:\akshu
9216HARSHINI D:\ HARSHINI
9217DHARSHINI E:\ DHARSHINI
9218C:\>net stop messenger
9219The Messenger service is stopping.
9220The Messenger service was stopped successfully.
9221C:\>net start messenger
9222The Messenger service is starting...
9223The Messenger service was started successfully.
9224Network Configuration commands
9225ifconfig
9226This command is used to configure network interfaces, or to display their current
9227configuration. In addition to activating and deactivating interfaces with the “up†and “downâ€
9228settings, this command is necessary for setting an interface's address information if you don't
9229have the ifcfg script.
9230Use ifconfig as either:
9231ifconfig
9232This will simply list all information on all network devices currently up.
9233ifconfig eth0 down
9234This will take eth0 (assuming the device exists) down, it won't be able to receive or send
9235anything until you put the device back “up†again.
9236Clearly there are a lot more options for this tool, you will need to read the manual/info page to
9237learn more about them.
9238ifup
9239Use ifup device-name to bring an interface up by following a script (which will contain your
9240default networking settings). Simply type ifup and you will get help on using the script.
9241For example typing:
9242ifup eth0
9243Will bring eth0 up if it is currently down.
9244ifdown
9245Use ifdown device-name to bring an interface down using a script (which will contain your
9246default network settings). Simply type ifdown and you will get help on using the script.
9247For example typing:
9248ifdown eth0
9249Will bring eth0 down if it is currently up.
9250ifcfg
9251Use ifcfg to configure a particular interface. Simply type ifcfg to get help on using this script.
9252For example, to change eth0 from 192.168.0.1 to 192.168.0.2 you could do:
9253ifcfg eth0 del 192.168.0.1
9254ifcfg eth0 add 192.168.0.2
9255The first command takes eth0 down and removes that stored IP address and the second one
9256brings it back up with the new address.
9257route
9258The route command is the tool used to display or modify the routing table. To add a gateway
9259as the default you would type:
9260route add default gw some_computer
9261INTERNET SPECIFIC COMMANDS
9262host
9263Performs a simple lookup of an internet address (using the Domain Name System, DNS).
9264Simply type:
9265host ip_address
9266or
9267host domain_name
9268dig
9269The "domain information groper" tool. More advanced then host... If you give a hostname as
9270an argument to output information about that host, including it's IP address, hostname and
9271various other information.
9272For example, to look up information about “www.amazon.com†type:
9273dig www.amazon.com
9274To find the host name for a given IP address (ie a reverse lookup), use dig with the `-x' option.
9275dig -x 100.42.30.95
9276This will look up the address (which may or may not exist) and returns the address of the
9277host, for example if that was the address of “http://slashdot.org†then it would return
9278“http://slashdot.orgâ€.
9279dig takes a huge number of options (at the point of being too many), refer to the manual page
9280for more information.
9281whois
9282(now BW whois) is used to look up the contact information from the “whois†databases, the
9283servers are only likely to hold major sites. Note that contact information is likely to be hidden
9284or restricted as it is often abused by crackers and others looking for a way to cause malicious
9285damage to organisation's.
9286wget
9287(GNU Web get) used to download files from the World Wide Web.
9288To archive a single web-site, use the -m or --mirror (mirror) option.
9289Use the -nc (no clobber) option to stop wget from overwriting a file if you already have it.
9290Use the -c or --continue option to continue a file that was unfinished by wget or another
9291program.
9292Simple usage example:
9293wget url_for_file
9294This would simply get a file from a site.
9295wget can also retrieve multiple files using standard wildcards, the same as the type used in
9296bash, like *, [ ], ?. Simply use wget as per normal but use single quotation marks (' ') on the
9297URL to prevent bash from expanding the wildcards. There are complications if you are
9298retrieving from a http site (see below...).
9299Advanced usage example, (used from wget manual page):
9300wget --spider --force-html -i bookmarks.html
9301This will parse the file bookmarks.html and check that all the links exist.
9302Advanced usage: this is how you can download multiple files using http (using a wildcard...).
9303Notes: http doesn't support downloading using standard wildcards, ftp does so you may use
9304wildcards with ftp and it will work fine. A work-around for this http limitation is shown
9305below:
9306wget -r -l1 --no-parent -A.gif http://www.website.com[1]
9307This will download (recursively), to a depth of one, in other words in the current directory and
9308not below that. This command will ignore references to the parent directory, and downloads
9309anything that ends in “.gifâ€. If you wanted to download say, anything that ends with “.pdf†as
9310well than add a -A.pdf before the website address. Simply change the website address and the
9311type of file being downloaded to download something else. Note that doing -A.gif is the same
9312as doing -A “*.gif†(double quotes only, single quotes will not work).
9313wget has many more options refer to the examples section of the manual page, this tool is very
9314well documented.
9315Alternative website downloaders: You may like to try alternatives like httrack. A full GUI
9316website downloader written in python and available for GNU/Linux
9317curl
9318curl is another remote downloader. This remote downloader is designed to work without user
9319interaction and supports a variety of protocols, can upload/download and has a large number
9320of tricks/work-arounds for various things. It can access dictionary servers (dict), ldap servers,
9321ftp, http, gopher, see the manual page for full details.
9322To access the full manual (which is huge) for this command type:
9323curl -M
9324For general usage you can use it like wget. You can also login using a user name by using the
9325-u option and typing your username and password like this:
9326curl -u username:password http://www.placetodownload/file
9327To upload using ftp you the -T option:
9328curl -T file_name ftp://ftp.uploadsite.com
9329To continue a file use the -C option:
9330curl -C - -o file http://www.site.com
9331View and modify network interfaces
9332ifconfig -a Show information about all network interfaces
9333ifconfig eth0 Show information only about the interface eth0
9334ifconfig eth0 up Bring up the interface eth0
9335ifconfig eth0 down Take down the interface eth0
9336Simple network diagnostic commands
9337ping hostname Send ICMP echo requests to the host hostname
9338traceroute hostname Trace the network path to hostname
9339View open network connections
9340netstat -a Show information about all open network connections
9341netstat -a | grep LISTEN Show information about all open network ports
9342Set/view routing information
9343netstat -r View system routing tables
9344route View system routing tables
9345The command route can also be used to add or delete routes. Examples:
9346route add -host 192.168.3.4 gw 192.168.3.1 netmask 255.255.0.0
9347route del -host 192.168.3.4
9348NETSTAT.exe TCP/IP Network Statistics
9349Displays protocol statistics and current TCP/IP network connections.
9350NETSTAT [-a] [-e] [-n] [-s] [-p proto] [-r] [interval]
9351-a Displays all connections and listening ports.
9352-e Displays Ethernet statistics. This may be combined with the -s option.
9353-n Displays addresses and port numbers in numerical form.
9354-p proto Shows connections for the protocol specified by proto; proto may be TCP or UDP.
9355If used with the -s option to display per-protocol statistics, proto may be TCP, UDP,
9356or IP.
9357-r Displays the routing table.
9358-s Displays per-protocol statistics. By default, statistics are shown for TCP, UDP and IP;
9359the -p option may be used to specify a subset of the default.
9360interval Redisplays selected statistics, pausing interval seconds between each display. Press
9361CTRL+C to stop redisplaying statistics. If omitted, netstat will print the current
9362configuration information once.
9363C:\WINDOWS>netstat -a
9364Active Connections
9365Proto Local Address Foreign Address State
9366TCP My_Comp:ftp localhost:0 LISTENING
9367TCP My_Comp:80 localhost:0 LISTENING
9368Or with the "-an" parameters:
9369C:\WINDOWS>netstat -an
9370Active Connections
9371Proto Local Address Foreign Address State
9372TCP 0.0.0.0:21 0.0.0.0:0 LISTENING
9373TCP 0.0.0.0:80 0.0.0.0:0 LISTENING
9374By simply opening a browser connection to both the HTTP (port 80) and FTP (port 21) servers
9375(while still offline!), I saw the following:
9376C:\WINDOWS>netstat -a
9377Active Connections
9378Proto Local Address Foreign Address State
9379TCP My_Comp:ftp localhost:0 LISTENING
9380TCP My_Comp:80 localhost:0 LISTENING
9381TCP My_Comp:1104 localhost:0 LISTENING
9382TCP My_Comp:ftp localhost:1104 ESTABLISHED
9383TCP My_Comp:1102 localhost:0 LISTENING
9384TCP My_Comp:1103 localhost:0 LISTENING
9385TCP My_Comp:80 localhost:1111 TIME_WAIT
9386TCP My_Comp:1104 localhost:ftp ESTABLISHED
9387TCP My_Comp:1107 localhost:0 LISTENING
9388TCP My_Comp:1112 localhost:80 TIME_WAIT
9389UDP My_Comp:1102 *:*
9390UDP My_Comp:1103 *:*
9391UDP My_Comp:1107 *:*
9392This may be a bit confusing to some people, but remember I'm running BOTH the servers and clients
9393on the same machine in these examples. A little later (using both 'a' and 'n') I got this:
9394C:\WINDOWS>netstat -an
9395Active Connections
9396Proto Local Address Foreign Address State
9397TCP 0.0.0.0:21 0.0.0.0:0 LISTENING
9398TCP 0.0.0.0:80 0.0.0.0:0 LISTENING
9399TCP 0.0.0.0:1104 0.0.0.0:0 LISTENING
9400TCP 127.0.0.1:21 127.0.0.1:1104 FIN_WAIT_2
9401TCP 127.0.0.1:1102 0.0.0.0:0 LISTENING
9402TCP 127.0.0.1:1103 0.0.0.0:0 LISTENING
9403TCP 127.0.0.1:1104 127.0.0.1:21 CLOSE_WAIT
9404TCP 127.0.0.1:1107 0.0.0.0:0 LISTENING
9405UDP 127.0.0.1:1102 *:*
9406UDP 127.0.0.1:1103 *:*
9407UDP 127.0.0.1:1107 *:*
9408After turning off my server, I ended up with this for a while:
9409C:\WINDOWS>netstat -an
9410Active Connections
9411Proto Local Address Foreign Address State
9412TCP 127.0.0.1:80 127.0.0.1:1150 TIME_WAIT
9413TCP 127.0.0.1:80 127.0.0.1:1151 TIME_WAIT
9414PING.exe
9415Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
9416[-r count] [-s count] [[-j host-list] | [-k host-list]]
9417[-w timeout] destination-list
9418Options:
9419-t Ping the specifed host until interrupted.
9420-a Resolve addresses to hostnames.
9421-n count Number of echo requests to send.
9422-l size Send buffer size.
9423-f Set "Don't Fragment" flag in packet.
9424-i TTL Time To Live.
9425-v TOS Type Of Service.
9426-r count Record route for count hops.
9427-s count Timestamp for count hops.
9428-j host-list Loose source route along host-list.
9429-k host-list Strict source route along host-list.
9430-w timeout Timeout in milliseconds to wait for each reply.
9431There's one special IP number everyone should know about:
9432127.0.0.1 - localhost (or loopback).
9433This is used to connect ( through a browser, for example) to a Web server on your own computer.
9434(127 being reserved for this purpose.) You can use this IP number at all times. It doesn't matter if
9435you're connected to the Internet or not.
9436It's also called the loopback address because you can ping it and get returns even when you're
9437offline (not connected to any network). If you don't get any valid replies, then there's a problem with
9438the computer's Network settings. Here's a typical response to the 'ping' command:
9439Here's another recent example using the name of my computer which I have tied to the IP number
9440127.0.0.1 in my C:\WINDOWS\HOSTS file:
9441C:\WINDOWS>ping My_Comp
9442Pinging My_Comp [127.0.0.1] with 32 bytes of data:
9443Reply from 127.0.0.1: bytes=32 time=1ms TTL=128
9444Reply from 127.0.0.1: bytes=32 time=1ms TTL=128
9445Reply from 127.0.0.1: bytes=32 time<10ms TTL=128
9446Reply from 127.0.0.1: bytes=32 time=1ms TTL=128
9447Ping statistics for 127.0.0.1:
9448Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
9449Approximate round trip times in milli-seconds:
9450Minimum = 0ms, Maximum = 1ms, Average = 0ms
9451TRACERT.exe Trace Route
9452Usage:
9453tracert [-d] [-h maximum_hops] [-j host-list] [-w timeout] target_name
9454Options:
9455-d Do not resolve addresses to hostnames.
9456-h maximum_hops Maximum number of hops to search for target.
9457-j host-list Loose source route along host-list.
9458-w timeout Wait timeout milliseconds for each reply.
9459Here's an example which traces the route from some ISP in Los Angeles to the main server at UCLA
9460in California ( note how two computers relatively close to each other may be routed way round
9461about! ):
9462C:\WINDOWS>tracert www.ucla.edu
9463Tracing route to www.ucla.edu [169.232.33.129]
9464over a maximum of 30 hops:
94651 141 ms 132 ms 140 ms wla-ca-pm6.icg.net [165.236.29.85]
94662 134 ms 131 ms 139 ms whv-ca-gw1.icg.net [165.236.29.65]
94673 157 ms 132 ms 143 ms f3-1-0.lai-ca-gw1.icg.net [165.236.24.89]
94684 194 ms 193 ms 188 ms a0-0-0-1.dai-tx-gw1.icg.net [163.179.235.61]
94695 300 ms 211 ms 214 ms a1-1-0-1.ati-ga-gw1.icg.net [163.179.235.186]
94706 236 ms 237 ms 247 ms a5-0-0-1.was-dc-gw1.icg.net [163.179.235.129]
94717 258 ms 236 ms 244 ms 163.179.243.205
94728 231 ms 233 ms 230 ms wdc-brdr-03.inet.qwest.net [205.171.4.153]
94739 240 ms 230 ms 236 ms wdc-core-03.inet.qwest.net [205.171.24.69]
947410 262 ms 264 ms 263 ms hou-core-01.inet.qwest.net [205.171.5.187]
947511 281 ms 263 ms 259 ms hou-core-03.inet.qwest.net [205.171.23.9]
947612 272 ms 229 ms 222 ms lax-core-02.inet.qwest.net [205.171.5.163]
947713 230 ms 217 ms 230 ms lax-edge-07.inet.qwest.net [205.171.19.58]
947814 228 ms 219 ms 220 ms 63-145-160-42.cust.qwest.net [63.145.160.42]
947915 218 ms 222 ms 218 ms ISI-7507--ISI.POS.calren2.net [198.32.248.21]
948016 232 ms 222 ms 214 ms UCLA--ISI.POS.calren2.net [198.32.248.30]
948117 234 ms 226 ms 226 ms cbn5-gsr.calren2.ucla.edu [169.232.1.18]
948218 245 ms 227 ms 235 ms www.ucla.edu [169.232.33.129]
9483Trace complete.
9484Net Bios Stats
9485NBTSTAT.exe
9486Displays protocol statistics and current TCP/IP connections using NBT
9487(NetBIOS over TCP/IP).
9488NBTSTAT [-a RemoteName] [-A IP address] [-c] [-n] [-r] [-R] [-s] [S] [interval]
9489-a (adapter status) Lists the remote machine's name table given its name.
9490-A (Adapter status) Lists the remote machine's name table given its IP address.
9491-c (cache) Lists the remote name cache including the IP addresses.
9492-n (names) Lists local NetBIOS names.
9493-r (resolved) Lists names resolved by broadcast and via WINS
9494-R (Reload) Purges and reloads the remote cache name table
9495-S (Sessions) Lists sessions table with the destination IP addresses.
9496-s (sessions) Lists sessions table converting destination IP addresses to host names via the
9497hosts file.
9498RemoteName Remote host machine name.
9499IP address Dotted decimal representation of the IP address.
9500interval Redisplays selected statistics, pausing interval seconds between each display. Press
9501Ctrl+C to stop redisplaying statistics.
9502ROUTE.exe
9503Manipulates network routing tables.
9504ROUTE [-f] [command [destination] [MASK netmask] [gateway]]
9505-f Clears the routing tables of all gateway entries. If this is used in conjunction
9506with one of the commands, the tables are cleared prior to running the command.
9507command Specifies one of four commands
9508PRINT Prints a route
9509ADD Adds a route
9510DELETE Deletes a route
9511CHANGE Modifies an existing route
9512destination Specifies the host to send command.
9513MASK If the MASK keyword is present, the next parameter is interpreted as the
9514netmask parameter.
9515netmask If provided, specifies a sub-net mask value to be associated with this route entry.
9516If not specified, if defaults to 255.255.255.255.
9517gateway Specifies gateway.
9518All symbolic names used for destination or gateway are looked up in the network and host
9519name database files NETWORKS and HOSTS, respectively.
9520If the command is print or delete, wildcards may be used for the destination and gateway, or
9521the gateway argument may be omitted.
9522ARP.exe Address Resolution Protocol
9523ARP -s inet_addr eth_addr [if_addr]
9524ARP -d inet_addr [if_addr]
9525ARP -a [inet_addr] [-N if_addr]
9526-a Displays current ARP entries by interrogating the current protocol data. If inet_addr
9527is specified, the IP and Physical addresses for only the specified computer are
9528displayed. If more than one network interface uses ARP, entries for each ARP
9529table are displayed.
9530-g (Same as -a)
9531inet_addr Specifies an internet address.
9532-N if_addr Displays the ARP entries for the network interface specified by if_addr.
9533-d Deletes the host specified by inet_addr.
9534-s Adds the host and associates the Internet address inet_addr with the Physical address
9535eth_addr. The Physical address is given as 6 hexadecimal bytes separated by hyphens.
9536The entry is permanent.
9537eth_addr Specifies a physical address.
9538if_addr If present, this specifies the Internet address of the interface
9539whose address translation table should be modified. If not present, the first
9540applicable interface will be used.