· 9 years ago · Mar 20, 2017, 07:34 AM
1question one
2Implement echo server and client in java using UDP sockets.
3
4Client program – ServerEcho.java
5
6import java.net.*;
7import java.util.*;
8
9public class ServerEcho
10{
11 public static void main( String args[]) throws Exception
12 {
13 DatagramSocket dsock = new DatagramSocket(7);
14 byte arr1[] = new byte[150];
15 DatagramPacket dpack = new DatagramPacket(arr1, arr1.length );
16
17 while(true)
18 {
19 dsock.receive(dpack);
20
21 byte arr2[] = dpack.getData();
22 int packSize = dpack.getLength();
23 String s2 = new String(arr2, 0, packSize);
24
25 System.out.println( new Date( ) + " " + dpack.getAddress( ) + " : " + dpack.getPort( ) + " "+ s2);
26 dsock.send(dpack);
27 }
28 }
29}
30
31Client program – ClientEcho.java
32import java.net.*;
33import java.util.*;
34
35public class ClientEcho
36{
37 public static void main( String args[] ) throws Exception
38 {
39 InetAddress add = InetAddress.getByName("snrao");
40
41 DatagramSocket dsock = new DatagramSocket( );
42 String message1 = "This is client calling";
43 byte arr[] = message1.getBytes( );
44 DatagramPacket dpack = new DatagramPacket(arr, arr.length, add, 7);
45 dsock.send(dpack); // send the packet
46 Date sendTime = new Date(); // note the time of sending the message
47
48 dsock.receive(dpack); // receive the packet
49 String message2 = new String(dpack.getData( ));
50 Date receiveTime = new Date( ); // note the time of receiving the message
51 System.out.println((receiveTime.getTime( ) - sendTime.getTime( )) + " milliseconds echo time for " + message2);
52 }
53}
54
55
56 OR
57
58import java.net.*;
59 import java.util.*;
60 public class EchoServer
61{
62 public static void main( String args[]) throws Exception
63 {
64 DatagramSocket dsock = new DatagramSocket(7);
65byte arr1[] = new byte[150];
66DatagramPacket dpack = new DatagramPacket(arr1, arr1.length );
67while(true)
68{ dsock.receive(dpack);
69byte arr2[] = dpack.getData();
70 int packSize = dpack.getLength();
71String s2 = new String(arr2, 0, packSize);
72System.out.println( new Date( ) + " " + dpack.getAddress( ) + " : " + dpack.getPort( ) + " "+ s2);
73dsock.send(dpack);
74}
75}
76}----------------------------------
77import java.net.*;
78import java.util.*;
79 public class EchoClient
80{ public static void main( String args[] ) throws Exception {
81InetAddress add = InetAddress.getByName("127.0.0.1");
82DatagramSocket dsock = new DatagramSocket( );
83 String message1 = "This is client calling";
84 byte arr[] = message1.getBytes( );
85 DatagramPacket dpack = new DatagramPacket(arr, arr.length, add, 7);
86 dsock.send(dpack); // send the packet
87Date sendTime = new Date( ); // note the time of sending the message
88dsock.receive(dpack); // receive the packet
89String message2 = new String(dpack.getData( ));
90 Date receiveTime = new Date( ); // note the time of receiving the message
91 System.out.println((receiveTime.getTime( ) - sendTime.getTime( )) + " milliseconds echo time for " + message2);
92 }
93 }
94
95
96
97
98
99
100
101
102question 2
103Implement a simple message transfer from client to server process using UDP.
104import java.io.*;
105import java.net.*;
106class UDPServerss {
107public static void main(String args[]) throws Exception {
108 DatagramSocket serverSocket = new DatagramSocket(9876);
109
110 byte[] receiveData = new byte[1024];
111 byte[] sendData = new byte[1024];
112 while(true) {
113
114 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
115 serverSocket.receive(receivePacket);
116 String sentence = new String( receivePacket.getData());
117 System.out.println("RECEIVED: " + sentence);
118 InetAddress IPAddress = receivePacket.getAddress();
119 int port = receivePacket.getPort();
120 String capitalizedSentence = sentence.toUpperCase();
121 sendData = capitalizedSentence.getBytes();
122 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
123 serverSocket.send(sendPacket);
124 }
125}
126}
127import java.io.*;
128import java.net.*;
129 class UDPClientssss {
130 public static void main(String args[]) throws Exception {
131 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
132 DatagramSocket clientSocket = new DatagramSocket();
133 InetAddress IPAddress = InetAddress.getByName("localhost");
134 byte[] sendData = new byte[1024];
135 byte[] receiveData = new byte[1024];
136 String sentence = inFromUser.readLine();
137 sendData = sentence.getBytes();
138 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
139 clientSocket.send(sendPacket);
140 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
141 clientSocket.receive(receivePacket);
142 String modifiedSentence = new String(receivePacket.getData());
143 System.out.println("FROM SERVER:" + modifiedSentence);
144 clientSocket.close();
145 }
146 }
147
148
149
150
151
152
153question 3
154 Simple chat application in java using datagram socket and datagram packet
155Algorithm
156Start the UDP chat program
157Import the package java.net.*;
158Declare the datagramsocket,datagrampacket,BufferedReader,InetAddress.
159Start the main function
160In the main function using while loop it perform the loop until str.equals is STOP
161There important while loop function are
162clientsocket = new DatagramSocket(cport);
163dp = new DatagramPacket(buf, buf.length);
164dis = new BufferedReader(new
165InputStreamReader(System.in));
166ia = InetAddress.getLocalHost(); f it is stop then break the while loop
167Terminate the UDP client program
168source code java programming UDP Chat server
169import java.io.*;
170import java.net.*;
171class UDPServer
172{
173public static DatagramSocket serversocket;
174public static DatagramPacket dp;
175public static BufferedReader dis;
176public static InetAddress ia;
177public static byte buf[] = new byte[1024];
178public static int cport = 789,sport=790;
179public static void main(String[] a) throws IOException
180{
181serversocket = new DatagramSocket(sport);
182dp = new DatagramPacket(buf,buf.length);
183dis = new BufferedReader
184(new InputStreamReader(System.in));
185ia = InetAddress.getLocalHost();
186System.out.println("Server is Running...");
187while(true)
188{
189serversocket.receive(dp);
190String str = new String(dp.getData(), 0,
191dp.getLength());
192if(str.equals("STOP"))
193{
194System.out.println("Terminated...");
195break;
196}
197System.out.println("Client: " + str);
198String str1 = new String(dis.readLine());
199buf = str1.getBytes();
200serversocket.send(new
201DatagramPacket(buf,str1.length(), ia, cport));
202}
203}
204}
205
206Output:-
207C:\IPLAB>javac UDPServer.java
208C:\IPLAB>java UDPServer
209Server is Running...
210Client: Hello
211Welcome
212Terminated...
213
214source code java programming UDP Chat Client
215import java.io.*;
216import java.net.*;
217class UDPClient
218{
219public static DatagramSocket clientsocket;
220public static DatagramPacket dp;
221public static BufferedReader dis;
222public static InetAddress ia;
223public static byte buf[] = new byte[1024];
224public static int cport = 789, sport = 790;
225public static void main(String[] a) throws IOException
226{
227clientsocket = new DatagramSocket(cport);
228dp = new DatagramPacket(buf, buf.length);
229dis = new BufferedReader(new
230InputStreamReader(System.in));
231ia = InetAddress.getLocalHost();
232System.out.println("Client is Running... Type 'STOP'
233to Quit");
234while(true)
235{
236String str = new String(dis.readLine());
237buf = str.getBytes();
238if(str.equals("STOP"))
239{
240System.out.println("Terminated...");
241clientsocket.send(new
242DatagramPacket(buf,str.length(), ia,
243sport));
244break;
245}
246clientsocket.send(new DatagramPacket(buf,
247str.length(), ia, sport));
248clientsocket.receive(dp);
249String str2 = new String(dp.getData(), 0,
250dp.getLength());
251System.out.println("Server: " + str2);
252}
253}
254}
255
256Output UDP Chat Client
257C:\IPLAB>javac UDPClient.java
258C:\IPLAB>java UDPClient
259Client is Running... Type ‘STOP’ to Quit
260Hello
261Server: Welcome
262STOP
263Terminated...
264BB / REC - 41
265
266
267
268 or
269
270
271 Client interface:
272
273 import java.awt.*;
274 import javax.swing.*;
275 public class UDPClient extends JFrame
276 {
277 // Variables
278 private JFrame frame;
279 private JPanel panel;
280 private JLabel label;
281 private JButton sendbutton;
282 private JTextField textfield;
283 private JTextArea textarea;
284 private JScrollPane scrollpane;
285
286 public static void main (String args[]) {
287
288 new UDPClient();
289 }
290
291 // Constructor
292 public UDPClient() {
293
294 frame = this;
295 panel = new JPanel(new GridBagLayout());
296 panel.setBackground(Color.cyan);
297 frame.setTitle("Chat Applet Client");
298 frame.getContentPane().add(panel, BorderLayout.NORTH);
299 frame.setVisible(true);
300 frame.setSize(430, 364);
301 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
302 //frame.setResizable(false);
303 GridBagConstraints c = new GridBagConstraints();
304 c.insets = new Insets(5, 5, 5, 5);
305
306 // Server address label
307 label = new JLabel("Server:");
308 c.fill = GridBagConstraints.HORIZONTAL;
309 c.gridx = 0;
310 c.gridy = 0;
311 panel.add(label, c);
312
313 // Server address textfield
314 textfield = new JTextField(20);
315 c.fill = GridBagConstraints.HORIZONTAL;
316 c.gridx = 1;
317 c.gridy = 0;
318 panel.add(textfield, c);
319
320 // 'Port#:' label
321 label = new JLabel("Port# :");
322 c.fill = GridBagConstraints.HORIZONTAL;
323 c.gridx = 2;
324 c.gridy = 0;
325 panel.add(label, c);
326
327 // Port# textfield
328 textfield = new JTextField(6);
329 c.fill = GridBagConstraints.HORIZONTAL;
330 c.gridx = 3;
331 c.gridy = 0;
332 panel.add(textfield, c);
333
334 // 'Conversation:' label
335 label = new JLabel("Conversation:");
336 c.fill = GridBagConstraints.HORIZONTAL;
337 c.gridx = 0;
338 c.gridy = 1;
339 c.gridwidth = 4;
340 panel.add(label, c);
341
342 // Conversation Window
343 textarea = new JTextArea(10, 2);
344 scrollpane = new JScrollPane(textarea);
345 textarea.setLineWrap(true);
346 textarea.setWrapStyleWord(true);
347 textarea.setEditable(false);
348 c.fill = GridBagConstraints.HORIZONTAL;
349 c.gridx = 0;
350 c.gridy = 2;
351 c.gridwidth = 4;
352 panel.add(scrollpane, c);
353
354 // 'Message:' label
355 label = new JLabel("Message to Send:");
356 c.fill = GridBagConstraints.HORIZONTAL;
357 c.gridx = 0;
358 c.gridy = 3;
359 panel.add(label, c);
360
361 // Message Window
362 textarea = new JTextArea(2, 2);
363 scrollpane = new JScrollPane(textarea);
364 textarea.setLineWrap(true);
365 textarea.setWrapStyleWord(true);
366 c.fill = GridBagConstraints.HORIZONTAL;
367 c.gridx = 0;
368 c.gridy = 4;
369 c.gridwidth = 4;
370 panel.add(scrollpane, c);
371
372 // 'Send' button
373 sendbutton = new JButton("Send");
374 c.fill = GridBagConstraints.HORIZONTAL;
375 c.gridx = 0;
376 c.gridy = 5;
377 c.gridwidth = 4;
378 panel.add(sendbutton, c);
379 }
380 }
381
382
383
384
385
386Server interface:
387
388 import java.awt.*;
389 import javax.swing.*;
390 public class UDPServer extends JFrame {
391 // Variables
392 private JFrame frame;
393 private JPanel panel;
394 private JLabel label;
395 private JButton startbutton;
396 private JButton stopbutton;
397 private JButton sendbutton;
398 private JTextField textfield;
399 private JTextArea textarea;
400 private JScrollPane scrollpane;
401
402 //http://www.youtube.com/watch?v=IkEz5tW5bok
403 public static void main (String args[]) {
404
405 new UDPServer();
406 }
407
408 // Constructor
409 public UDPServer() {
410
411 frame = this;
412 panel = new JPanel(new GridBagLayout());
413 panel.setBackground(Color.darkGray);
414 frame.setTitle("Chat Applet Server");
415 frame.getContentPane().add(panel, BorderLayout.NORTH);
416 frame.setVisible(true);
417 //frame.pack();
418
419 frame.setSize(430, 364);
420 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
421 frame.setResizable(true);
422 GridBagConstraints c = new GridBagConstraints();
423 c.insets = new Insets(5, 5, 5, 5);
424
425 // 'Start Server' button
426 startbutton = new JButton("Start Server");
427 startbutton.setPreferredSize(new Dimension(130,20));
428 c.fill = GridBagConstraints.HORIZONTAL;
429 c.gridx = 0;
430 c.gridy = 0;
431 c.gridwidth = 1;
432 panel.add(startbutton, c);
433
434 // 'Stop Server' button
435 stopbutton = new JButton("Stop Server");
436 stopbutton.setPreferredSize(new Dimension(130,20));
437 c.fill = GridBagConstraints.HORIZONTAL;
438 c.gridx = 1;
439 c.gridy = 0;
440 c.gridwidth = 1;
441 panel.add(stopbutton, c);
442
443 // 'Port#:' label
444 label = new JLabel("Port# :");
445 label.setForeground(Color.white);
446 c.fill = GridBagConstraints.HORIZONTAL;
447 c.gridx = 2;
448 c.gridy = 0;
449 panel.add(label, c);
450
451 // Port# textfield
452 textfield = new JTextField(6);
453 c.fill = GridBagConstraints.HORIZONTAL;
454 c.gridx = 3;
455 c.gridy = 0;
456 panel.add(textfield, c);
457
458 // 'Conversation:' label
459 label = new JLabel("Conversation:");
460 label.setForeground(Color.white);
461 c.fill = GridBagConstraints.HORIZONTAL;
462 c.gridx = 0;
463 c.gridy = 1;
464 c.gridwidth = 4;
465 panel.add(label, c);
466
467 // Conversation Window
468 textarea = new JTextArea("<Server not yet started!>", 10, 2);
469 scrollpane = new JScrollPane(textarea);
470 textarea.setLineWrap(true);
471 textarea.setWrapStyleWord(true);
472 textarea.setEditable(false);
473 c.fill = GridBagConstraints.HORIZONTAL;
474 c.gridx = 0;
475 c.gridy = 2;
476 c.gridwidth = 4;
477 panel.add(scrollpane, c);
478
479 // 'Message:' label
480 label = new JLabel("Message to Send:");
481 label.setForeground(Color.white);
482 c.fill = GridBagConstraints.HORIZONTAL;
483 c.gridx = 0;
484 c.gridy = 3;
485 panel.add(label, c);
486
487 // Message Window
488 textarea = new JTextArea(2, 2);
489 scrollpane = new JScrollPane(textarea);
490 textarea.setLineWrap(true);
491 textarea.setWrapStyleWord(true);
492 c.fill = GridBagConstraints.HORIZONTAL;
493 c.gridx = 0;
494 c.gridy = 4;
495 c.gridwidth = 4;
496 panel.add(scrollpane, c);
497
498 // 'Send' button
499 sendbutton = new JButton("Send");
500 c.fill = GridBagConstraints.HORIZONTAL;
501 c.gridx = 0;
502 c.gridy = 5;
503 c.gridwidth = 4;
504 panel.add(sendbutton, c);
505 }
506 }
507
508
509
510
511
512
513question 4-----------------------------
514UDP Program – DNS CLIENT-SERVER
515
516UDP Program (DNS CLIENT-SERVER)
517
518AIM : To create a client server program to Domain Name System using the UDP protocol client server.
519
520ALGORITHM
521
522Server
523
524 Declare the necessary arrays and variables.
525 Set server port address using socket().
526 Get the current message.
527 Connect to the client.
528 Stop the process.
529
530Client
531
532 Set the client machine address.
533 Connect to the server.
534 Read from the server the current message.
535 Display the current message.
536 Close the connection.
537
538PROGRAM:
539
540UDPclient
541
542import java .io.*;
543
544import java.net.*;
545
546classUDPclient
547
548{
549
550public static DatagramSocket ds;
551
552public static intclientport=789,serverport=790;
553
554public static void main(String args[])throws Exception
555
556{
557
558byte buffer[]=new byte[1024];
559
560ds=new DatagramSocket(serverport);
561
562BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
563
564System.out.println(“server waitingâ€);
565
566InetAddressia=InetAddress.getLocalHost();
567
568while(true)
569
570{
571
572System.out.println(“Client:â€);
573
574String str=dis.readLine();
575
576if(str.equals(“endâ€))
577
578break;
579
580buffer=str.getBytes();
581
582ds.send(new DatagramPacket(buffer,str.length(),ia,clientport));
583
584DatagramPacket p=new DatagramPacket(buffer,buffer.length);
585
586ds.receive(p);
587
588String psx=new String(p.getData(),0,p.getLength());
589
590System.out.println(“Server:†+ psx);
591
592}
593
594}
595
596}
597
598UDP server
599
600import java.io.*;
601
602import java.net.*;
603
604classUDPserver
605
606{
607
608public static DatagramSocket ds;
609
610public static byte buffer[]=new byte[1024];
611
612public static intclientport=789,serverport=790;
613
614public static void main(String args[])throws Exception
615
616{
617
618ds=new DatagramSocket(clientport);
619
620System.out.println(“press ctrl+c to quit the programâ€);
621
622BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
623
624InetAddressia=InetAddress.getLocalHost();
625
626while(true)
627
628{
629
630DatagramPacket p=new DatagramPacket(buffer,buffer.length);
631
632ds.receive(p);
633
634String psx=new String(p.getData(),0,p.getLength());
635
636System.out.println(“Client:†+ psx);
637
638InetAddressib=InetAddress.getByName(psx);
639
640System.out.println(“Server output:â€+ib);
641
642String str=dis.readLine();
643
644if(str.equals(“endâ€))
645
646break;
647
648buffer=str.getBytes();
649
650ds.send(new DatagramPacket(buffer,str.length(),ia,serverport));
651
652}
653
654}
655
656}
657
658OUTPUT:
659
660UDPclient
661
662C:\Program Files\Java\jdk1.6.0\bin>javac UDPclient.java
663
664C:\Program Files\Java\jdk1.6.0\bin>java UDPclient
665
666Server waiting
667
668Client:www.yahoo.com
669
670UDPserver
671
672C:\Program Files\Java\jdk1.6.0\bin>javac UDPserver.java
673
674C:\Program Files\Java\jdk1.6.0\bin>java UDPserver
675
676Press ctrl+c to quit the program
677
678Client:www.yahoo.com
679
680Server output:www.yahoo.com/106.10.170.115
681
682RESULT:
683
684Thus client server program to Domain Name System using the UDP protocol client server has been executed and verified successfully.
685
686
687
688
689
690QUESTION 5------------------------------------------------
691UDP DATE SERVER
692
693Server Program >>>>> Server.java
694
695
696import java.net.*;
697import java.io.*;
698import java.util.*;
699
700public class Server {
701
702public static void main(String[] args) throws Exception{
703
704DatagramSocket ss=new DatagramSocket(1234);
705
706while(true){
707
708System.out.println("Server is up....");
709
710byte[] rd=new byte[100];
711byte[] sd=new byte[100];
712
713DatagramPacket rp=new DatagramPacket(rd,rd.length);
714
715ss.receive(rp);
716
717InetAddress ip= rp.getAddress();
718
719int port=rp.getPort();
720
721Date d=new Date(); // getting system time
722
723String time= d + ""; // converting it to String
724
725sd=time.getBytes(); // converting that String to byte
726
727DatagramPacket sp=new DatagramPacket(sd,sd.length,ip,port);
728
729ss.send(sp);
730
731rp=null;
732
733System.out.println("Done !! ");
734
735}
736
737}
738
739}
740
741
742Client program >>>>>>>>> Clientnew.java
743import java.net.*;
744import java.io.*;
745
746public class Clientnew {
747
748public static void main(String[] args) throws Exception{
749
750 System.out.println("Server Time >>>>");
751
752 DatagramSocket cs=new DatagramSocket();
753
754 InetAddress ip=InetAddress.getByName("localhost");
755
756 byte[] rd=new byte[100];
757 byte[] sd=new byte[100];
758
759 DatagramPacket sp=new DatagramPacket(sd,sd.length,ip,1234);
760
761 DatagramPacket rp=new DatagramPacket(rd,rd.length);
762
763 cs.send(sp);
764
765 cs.receive(rp);
766
767 String time=new String(rp.getData());
768
769 System.out.println(time);
770
771 cs.close();
772
773}
774
775}
776
777
778
779
780
781
782
783
784
785------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
786SIR UPLOADED MATERIAL
787
788
7891)Write a program to list all ports hosting a TCP server in a specified host.
790
791import java.net.*;
792import java.io.*;
793public class ports{
794public static void main(String args[])
795{
796for(int i=1;i<1024;i++)
797{
798try{
799Socket s=new Socket("127.0.0.1",i);
800System.out.println("There is server on port"+i+"of 127.0.0.1");
801}
802catch(UnknownHostException e){
803System.err.println(e);
804break;
805}
806catch(IOException e){
807//must not be server on this port
808}
809}
810}
811}
812
8132)Write a program to display the server’s date and time details at the client end.
814
815import java.io.IOException;
816import java.io.PrintWriter;
817import java.net.ServerSocket;
818import java.net.Socket;
819import java.util.Date;
820
821public class dateserver {
822
823 public static void main(String[] args) throws IOException {
824 ServerSocket listener = new ServerSocket(9090);
825 try {
826 while (true) {
827 Socket socket = listener.accept();
828 try {
829 PrintWriter out =
830 new PrintWriter(socket.getOutputStream(), true);
831 out.println(new Date().toString());
832 } finally {
833 socket.close();
834 }
835 }
836 }
837 finally {
838 listener.close();
839 }
840 }
841}
842
843------------------------------
844import java.io.*;
845import java.net.Socket;
846
847public class dateClient {
848
849 public static void main(String[] args) throws IOException {
850 Socket s = new Socket("127.0.0.1", 9090);
851 BufferedReader input =
852 new BufferedReader(new InputStreamReader(s.getInputStream()));
853 String answer = input.readLine();
854 System.out.println("The date and time details are "+answer );
855
856 System.exit(0);
857 }
858}
859
860
8613)Write a program to display the client’s address at the server end.
862
863
864import java.io.*;
865import java.net.*;
866
867public class ServerAddr
868{
869public static void main(String args[]) throws IOException
870{
871try
872{
873ServerSocket ss = new ServerSocket(6666);
874System.out.println("Waiting for client.....");
875
876Socket s = ss.accept();
877System.out.println("Connected to client....");
878
879DataInputStream in = new DataInputStream (s.getInputStream());
880String line = null;
881line = in.readUTF();
882System.out.println("Client's IP adress: " + line);
883}
884catch (Exception e)
885{
886e.printStackTrace();
887}
888}
889}
890
891--------------------------------
892
893import java.io.*;
894import java.net.*;
895
896public class ClientAddr
897{
898public static void main(String args[]) throws IOException
899{
900try
901{
902InetAddress ipaddress = InetAddress.getByName("");
903Socket s = new Socket(ipaddress,6666);
904
905System.out.println("Connected to the server...");
906DataOutputStream out = new DataOutputStream(s.getOutputStream());
907
908String line = null;
909System.out.println("Sending my IP Address to server...");
910
911line=ipaddress.getHostAddress();
912
913out.writeUTF(line);
914out.flush();}
915catch (Exception e)
916{
917e.printStackTrace();
918}
919}
920}
921
9224)Implement a simple message transfer from client to server process using TCP/IP.
923
924import java.io.*;
925import java.net.*;
926
927public class Tcpserver
928{
929public static void main(String args[]) throws IOException
930{
931try
932{
933ServerSocket ss = new ServerSocket(6666);
934System.out.println("Waiting for client.....");
935
936Socket s = ss.accept();
937System.out.println("Connected to client....");
938
939DataInputStream in = new DataInputStream (s.getInputStream());
940String line = null;
941line = in.readUTF();
942System.out.println("Mesage from Client:" + line);
943}
944catch (Exception e)
945{
946e.printStackTrace();
947}
948}
949}
950
951--------------------------------------
952import java.io.*;
953import java.net.*;
954
955public class TCPClient
956{
957public static void main(String args[]) throws IOException
958{
959try
960{
961InetAddress ipaddress = InetAddress.getByName("");
962Socket s = new Socket(ipaddress,6666);
963DataInputStream read = new DataInputStream(System.in);
964System.out.println("Connected to the server...");
965DataOutputStream out = new DataOutputStream(s.getOutputStream());
966
967String line = null;
968System.out.println("Write a message to the server..");
969
970line=read.readLine();
971out.writeUTF(line);
972out.flush();}
973catch (Exception e)
974{
975e.printStackTrace();
976}
977}
978}
979
9805)Develop a TCP client/server application for transferring a text file from client to server
981
982
983CLIENt:
984import java.io.*;
985 import java.net.*;
986import java.util.*;
987public class FTPClient {
988public static void main(String args[]) throws Exception
989
990{
991 Socket ss = new Socket("localhost",5000);
992while(true)
993{
994
995Scanner pbn = new Scanner(System.in);
996System.out.println("Enter the path of the file ");
997String path = pbn.nextLine();
998System.out.println(path);
999
1000File f = new File(path);
1001FileInputStream fis = new FileInputStream(f);
1002
1003BufferedInputStream bis = new BufferedInputStream(fis);
1004System.out.println("Sending file...");
1005
1006System.out.println("File sent");
1007
1008 }
1009
1010 }
1011}
1012server:
1013
1014//////////////////
1015import java.io.*;
1016import java.net.*;
1017import java.util.*;
1018public class FTPServer {
1019public static void main(String args[]) throws IOException
1020{ServerSocket ss = new ServerSocket(5000);
1021
1022 Scanner pbn = new Scanner(System.in);
1023 boolean flag = true;
1024 while(flag)
1025 {
1026 flag = false;
1027 try
1028 {System.out.println("waiting...");
1029Socket s = ss.accept();
1030System.out.println("Accepted connection "+s);
1031 System.out.println("Enter the path where you want to store the file");
1032 String path1 = pbn.nextLine();
1033 FileOutputStream fos = new FileOutputStream(path1);
1034 BufferedOutputStream bos = new BufferedOutputStream(fos);
1035 InputStream is = s.getInputStream();
1036 byte[] b = new byte[600000];
1037 int n = 0;
1038 int o = 0;
1039 while((n=is.read(b,o,b.length-o))>=0)
1040 {
1041 o+=n;
1042 }
1043 bos.write(b,0,o);
1044
1045 bos.flush();
1046 System.out.println("File Received");
1047 }
1048
1049 catch(FileNotFoundException f)
1050 {
1051 flag = true;
1052 String msg = f.getMessage();
1053 System.out.println("Error Message:"+msg);
1054 System.out.println("Please Enter a correct file path");
1055 }
1056 }
1057
1058 }
1059}
1060
1061
10626. 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.
1063
1064import java.io.*;
1065import java.net.*;
1066
1067public class AuthServer
1068{
1069 public static void main(String args[]) throws IOException
1070 {
1071 try
1072 {
1073 ServerSocket ss = new ServerSocket(6666);
1074 System.out.println("Waiting for client.....");
1075 Socket s = ss.accept();
1076 System.out.println("Connected to client....");
1077
1078 DataInputStream in = new DataInputStream (s.getInputStream());
1079 DataOutputStream out = new DataOutputStream (s.getOutputStream());
1080
1081 String line = null;
1082 String line1 = null;
1083 String sendline = null;
1084
1085
1086line = in.readUTF();
1087line1 = in.readUTF();
1088 if((line.equals("aid")|| line.equals("bid"))&&((line1.equals("apass")|| line1.equals("bpass"))))
1089 {
1090 sendline ="Valid user id and password.Successfully logged in !!!!";
1091 out.writeUTF(sendline);
1092 out.flush();
1093
1094 }
1095 else
1096
1097 {
1098 sendline ="Invalid details";
1099 out.writeUTF(sendline);
1100 out.flush();
1101 }
1102
1103 }
1104 catch (Exception e)
1105 {
1106 e.printStackTrace();
1107 }
1108 }
1109}
1110
1111import java.io.*;
1112import java.net.*;
1113
1114public class AuthClient
1115{
1116 public static void main(String args[]) throws IOException
1117 {
1118 try
1119 {
1120 InetAddress ipaddress = InetAddress.getByName("127.0.0.1");
1121 Socket s = new Socket(ipaddress,6666);
1122
1123 System.out.println("Connected to the server...");
1124
1125 DataInputStream read = new DataInputStream(System.in);
1126
1127 DataInputStream in = new DataInputStream(s.getInputStream());
1128 DataOutputStream out = new DataOutputStream(s.getOutputStream());
1129
1130 String line = null;
1131 String line1 = null;
1132 String receiveline = null;
1133
1134 System.out.println("Enter User id ");
1135 line = read.readLine();
1136 out.writeUTF(line);
1137 out.flush();
1138
1139System.out.println("Enter Password ");
1140line1 = read.readLine();
1141out.writeUTF(line1);
1142out.flush();
1143
1144
1145 receiveline = in.readUTF();
1146 System.out.println("SERVER: " + receiveline);
1147
1148
1149 }
1150 catch (Exception e)
1151 {
1152 e.printStackTrace();
1153 }
1154 }
1155}
1156
11577. Write a program to develop a simple (text based) Chat application using TCP/IP.
1158//chat
1159import java.io.*;
1160import java.net.*;
1161
1162public class TCPserver
1163{
1164 public static void main(String args[]) throws IOException
1165 {
1166 try
1167 {
1168 ServerSocket ss = new ServerSocket(6666);
1169 System.out.println("Waiting for client.....");
1170DataInputStream read = new DataInputStream(System.in);
1171 Socket s = ss.accept();
1172 System.out.println("Connected to client....");
1173
1174 DataInputStream in = new DataInputStream (s.getInputStream());
1175 DataOutputStream out = new DataOutputStream (s.getOutputStream());
1176
1177 String line = null;
1178
1179
1180 do
1181 {
1182 line = in.readUTF();
1183 System.out.println("CLIENT: " + line);
1184 line = read.readLine();
1185 out.writeUTF(line);
1186 out.flush();
1187
1188 System.out.println("Waiting for the next line.....");
1189 }while(!line.equals("bye"));
1190 }
1191 catch (Exception e)
1192 {
1193 e.printStackTrace();
1194 }
1195 }
1196}
1197
1198
1199//chat
1200import java.io.*;
1201import java.net.*;
1202
1203public class TCPClient
1204{
1205 public static void main(String args[]) throws IOException
1206 {
1207 try
1208 {
1209 InetAddress ipaddress = InetAddress.getByName("127.0.0.1");
1210 Socket s = new Socket(ipaddress,6666);
1211
1212 System.out.println("Connected to the server...");
1213
1214 DataInputStream read = new DataInputStream(System.in);
1215
1216 DataInputStream in = new DataInputStream(s.getInputStream());
1217 DataOutputStream out = new DataOutputStream(s.getOutputStream());
1218
1219 String line = null;
1220 String receiveline = null;
1221
1222 System.out.println("Enter data to send to the server: ");
1223
1224 do
1225 {
1226 System.out.print("CLIENT: ");
1227 line = read.readLine();
1228 out.writeUTF(line);
1229 out.flush();
1230
1231 receiveline = in.readUTF();
1232 System.out.println("SERVER: " + receiveline);
1233
1234 }while(!line.equals("bye"));
1235 }
1236 catch (Exception e)
1237 {
1238 e.printStackTrace();
1239 }
1240 }
1241}
1242
12438. Implement a simple message transfer from client to server process using UDP.
1244import java.io.*;
1245import java.net.*;
1246class UDPServerss {
1247public static void main(String args[]) throws Exception {
1248 DatagramSocket serverSocket = new DatagramSocket(9876);
1249
1250 byte[] receiveData = new byte[1024];
1251 byte[] sendData = new byte[1024];
1252 while(true) {
1253
1254 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
1255 serverSocket.receive(receivePacket);
1256 String sentence = new String( receivePacket.getData());
1257 System.out.println("RECEIVED: " + sentence);
1258 InetAddress IPAddress = receivePacket.getAddress();
1259 int port = receivePacket.getPort();
1260 String capitalizedSentence = sentence.toUpperCase();
1261 sendData = capitalizedSentence.getBytes();
1262 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
1263 serverSocket.send(sendPacket);
1264 }
1265}
1266}
1267import java.io.*;
1268import java.net.*;
1269 class UDPClientssss {
1270 public static void main(String args[]) throws Exception {
1271 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
1272 DatagramSocket clientSocket = new DatagramSocket();
1273 InetAddress IPAddress = InetAddress.getByName("localhost");
1274 byte[] sendData = new byte[1024];
1275 byte[] receiveData = new byte[1024];
1276 String sentence = inFromUser.readLine();
1277 sendData = sentence.getBytes();
1278 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
1279 clientSocket.send(sendPacket);
1280 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
1281 clientSocket.receive(receivePacket);
1282 String modifiedSentence = new String(receivePacket.getData());
1283 System.out.println("FROM SERVER:" + modifiedSentence);
1284 clientSocket.close();
1285 }
1286 }
1287
12889. Write a program to implement an Echo UDP server. Test the working of the server by writing a client application.
1289import java.net.*;
1290 import java.util.*;
1291 public class EchoServer
1292{
1293 public static void main( String args[]) throws Exception
1294 {
1295 DatagramSocket dsock = new DatagramSocket(7);
1296byte arr1[] = new byte[150];
1297DatagramPacket dpack = new DatagramPacket(arr1, arr1.length );
1298while(true)
1299{ dsock.receive(dpack);
1300byte arr2[] = dpack.getData();
1301 int packSize = dpack.getLength();
1302String s2 = new String(arr2, 0, packSize);
1303System.out.println( new Date( ) + " " + dpack.getAddress( ) + " : " + dpack.getPort( ) + " "+ s2);
1304dsock.send(dpack);
1305}
1306}
1307}----------------------------------
1308import java.net.*;
1309import java.util.*;
1310 public class EchoClient
1311{ public static void main( String args[] ) throws Exception {
1312InetAddress add = InetAddress.getByName("127.0.0.1");
1313DatagramSocket dsock = new DatagramSocket( );
1314 String message1 = "This is client calling";
1315 byte arr[] = message1.getBytes( );
1316 DatagramPacket dpack = new DatagramPacket(arr, arr.length, add, 7);
1317 dsock.send(dpack); // send the packet
1318Date sendTime = new Date( ); // note the time of sending the message
1319dsock.receive(dpack); // receive the packet
1320String message2 = new String(dpack.getData( ));
1321 Date receiveTime = new Date( ); // note the time of receiving the message
1322 System.out.println((receiveTime.getTime( ) - sendTime.getTime( )) + " milliseconds echo time for " + message2);
1323 }
1324 }
1325
132610. 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.
1327import java.io.*;
1328import java.net.*;
1329public class UDPdiscardServer {
1330 public final static int DEFAULT_PORT=9;
1331 public final static int MAX_PACKET_SIZE=65507;
1332public static void main(String args[])
1333{
1334 int port=DEFAULT_PORT;
1335 byte[] buffer=new byte[MAX_PACKET_SIZE];
1336
1337 try{
1338 port=9;
1339 }
1340catch(Exception ex)
1341{}
1342 try{
1343 DatagramSocket server=new DatagramSocket(port);
1344DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
1345
1346while(true)
1347{
1348 try{
1349 server.receive(packet);
1350 String s=new String(packet.getData(),0,packet.getLength(),"UTF-8");
1351 System.out.println(packet.getAddress()+" at port "+packet.getPort()+" says "+s);
1352 packet.setLength(buffer.length);
1353 }
1354 catch(IOException ex){ System.err.println(ex);}
1355}
1356
1357 }
1358 catch(SocketException ex)
1359 {System.err.println(ex);}
1360}
1361}
1362import java.io.*;
1363import java.net.*;
1364public class UDPdiscardClient {
1365 public final static int DEFAULT_PORT=9;
1366
1367public static void main(String args[])
1368{String hostname="localhost";
1369 int port=DEFAULT_PORT;
1370
1371
1372 try{
1373 InetAddress server=InetAddress.getByName(hostname);
1374 BufferedReader userInput=new BufferedReader(new InputStreamReader(System.in));
1375 DatagramSocket theSocket=new DatagramSocket();
1376
1377 while(true)
1378 {
1379 String theLine=userInput.readLine();
1380 if(theLine.equals(".")) break;
1381 byte[] data=theLine.getBytes("UTF-8");
1382 DatagramPacket theOutput=new DatagramPacket(data,data.length,server,port);
1383 theSocket.send(theOutput);
1384 }
1385 }
1386 catch(UnknownHostException ex)
1387 {System.err.println(ex);}
1388 catch(SocketException ex)
1389 {System.err.println(ex);}
1390 catch(IOException ioex)
1391 {System.err.println(ioex);}
1392}
1393}
1394Find the physical address of a host when its logical address is known (ARP protocol) using TCP/IP.
1395
1396import java.net.InetAddress;
1397import java.net.NetworkInterface;
1398import java.net.SocketException;
1399import java.net.UnknownHostException;
1400import java.util.Scanner;
1401
1402public class MacAddress {
1403 public static void main(String[] args)
1404 {
1405 try
1406 {
1407 Scanner console = new Scanner(System.in);
1408 System.out.println("Enter System Name: ");
1409 String ipaddr = console.nextLine();
1410 InetAddress address = InetAddress.getByName(ipaddr);
1411 System.out.println("address = "+address);
1412 NetworkInterface ni = NetworkInterface.getByInetAddress(address);
1413 if (ni!=null)
1414 {
1415 byte[] mac = ni.getHardwareAddress();
1416 if (mac != null)
1417 {
1418 System.out.print("MAC Address : ");
1419 for (int i=0; i<mac.length; i++)
1420 {
1421 System.out.format("%02X%s", mac[i], (i<mac.length - 1) ? "-" :"");
1422 }
1423 }
1424 else
1425 {
1426 System.out.println("Address doesn't exist or is not accessible/");
1427
1428 }
1429 }
1430 else
1431 {
1432 System.out.println("Network Interface for the specified address is not found");
1433 }
1434 }
1435 catch(UnknownHostException he)
1436 {
1437 }
1438 catch(SocketException e)
1439 {
1440 }
1441 }
1442}
1443
1444
1445
1446cycle sheet 1
14471. Write a Java program to display the server’s date and time details at the client end.
1448
1449Client:
1450import java.io.*;
1451import java.net.*;
1452class dateclient
1453{
1454 public static void main(String args[]) throws Exception
1455 {
1456 Socket soc=new Socket(InetAddress.getLocalHost(),5217);
1457 BufferedReader in=new BufferedReader(new InputStreamReader( soc.getInputStream() ) );
1458 System.out.println(in.readLine());
1459 }
1460}
1461
1462Server:
1463import java.net.*;
1464import java.io.*;
1465import java.util.*;
1466class dateserver
1467{
1468 public static void main(String args[]) throws Exception
1469 {
1470 ServerSocket s=new ServerSocket(5217);
1471 while(true)
1472 {
1473 System.out.println("Waiting For Connection ...");
1474 Socket soc=s.accept();
1475 DataOutputStream out=new DataOutputStream(soc.getOutputStream());
1476 out.writeBytes("Server Date" + (new Date()).toString() + "\n");
1477 out.close();
1478 soc.close();
1479 }
1480 }
1481}
1482
1483OUTPUT:
1484
1485
1486 2. Write a Java program to display the client’s address at the server end.
1487
1488CODE:
1489Server:
1490import java.io.BufferedReader;
1491import java.io.IOException;
1492import java.io.InputStream;
1493import java.io.InputStreamReader;
1494import java.io.OutputStream;
1495import java.io.OutputStreamWriter;
1496import java.io.PrintWriter;
1497import java.net.ServerSocket;
1498import java.net.Socket;
1499
1500
1501public class gs{
1502
1503 public static void main(String[] args) throws Exception {
1504 ServerSocket sersock=new ServerSocket(3000);
1505 System.out.println("Server retreiving hostname...");
1506 Socket sock=sersock.accept();
1507
1508 BufferedReader keyread=new BufferedReader(new InputStreamReader(System.in));
1509
1510 OutputStream ostream=sock.getOutputStream();
1511 PrintWriter pwrite=new PrintWriter(ostream,true);
1512
1513 InputStream istream=sock.getInputStream();
1514 BufferedReader receiveread= new BufferedReader(new InputStreamReader(istream));
1515
1516 String Sendmsg,receivemsg;
1517 while(true)
1518 {
1519 if((receivemsg=receiveread.readLine())!=null)
1520 {
1521 System.out.println(receivemsg);
1522 }
1523 Sendmsg=keyread.readLine();
1524 pwrite.println(Sendmsg);
1525 pwrite.flush();
1526 }
1527
1528
1529 }
1530}
1531
1532Client:
1533import java.io.BufferedReader;
1534import java.io.IOException;
1535import java.io.InputStream;
1536import java.io.InputStreamReader;
1537import java.io.OutputStream;
1538import java.io.OutputStreamWriter;
1539import java.io.PrintWriter;
1540import java.net.InetAddress;
1541import java.net.ServerSocket;
1542import java.net.Socket;
1543
1544
1545public class gc{
1546
1547 public static void main(String[] args) throws Exception {
1548 InetAddress addr= InetAddress.getLocalHost();
1549 //InetAddress add= InetAddress.getHostName(addr);
1550 Socket sock=new Socket(addr,3000);
1551
1552 //BufferedReader keyread=new BufferedReader(new InputStreamReader(System.in));
1553
1554 OutputStream ostream=sock.getOutputStream();
1555 PrintWriter pwrite=new PrintWriter(ostream,true);
1556
1557 InputStream istream=sock.getInputStream();
1558 BufferedReader receiveread= new BufferedReader(new InputStreamReader(istream));
1559 System.out.println("Client is ready");
1560 String Sendmsg,receivemsg;
1561 pwrite.println(addr.getHostAddress());
1562
1563 }
1564}
1565OUTPUT:
1566
1567
15683. Write a Java program to implement an echo UDP server.
1569
1570Server:
1571import java.net.*;
1572import java.io.*;
1573import java.util.*;
1574class dateserver
1575{
1576 public static void main(String args[]) throws Exception
1577 {
1578 ServerSocket s=new ServerSocket(5217);
1579 while(true)
1580 {
1581 System.out.println("Waiting For Connection ...");
1582 Socket soc=s.accept();
1583 DataOutputStream out=new DataOutputStream(soc.getOutputStream());
1584 out.writeBytes("Server Date" + (new Date()).toString() + "\n");
1585 out.close();
1586 soc.close();
1587 }
1588 }
1589}
1590
1591Client:
1592import java.io.*;
1593import java.net.*;
1594public class eclient
1595{
1596 public static void main(String[] args) throws IOException
1597 {
1598 Socket C = new Socket("localhost",3000);
1599 BufferedReader buff = new BufferedReader(new InputStreamReader (System.in));
1600 String Str = buff.readLine();
1601 OutputStream out = C.getOutputStream();
1602 DataOutputStream Dos = new DataOutputStream(out);
1603 Dos.writeUTF("Client Say :: " + Str);
1604 Dos.flush();
1605 ServerSocket S = new ServerSocket(4000);
1606 Socket Client = S.accept();
1607 InputStream in = Client.getInputStream();
1608 DataInputStream Dis = new DataInputStream(in);
1609 System.out.println(Dis.readUTF());
1610 Client.close();
1611 }
1612}
1613
1614
1615
1616OUTPUT:
1617
1618
16194. Write a Java program to develop a simple Chat application.
1620
1621Server:
1622import java.io.*;
1623import java.net.*;
1624public class chatserver
1625{
1626 public static void main(String[] args) throws Exception
1627 {
1628 ServerSocket sersock = new ServerSocket(3000);
1629 Socket sock = sersock.accept( );
1630 BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
1631
1632 OutputStream ostream = sock.getOutputStream();
1633 PrintWriter pwrite = new PrintWriter(ostream, true);
1634 InputStream istream = sock.getInputStream();
1635 BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
1636 String receiveMessage, sendMessage;
1637 while(true)
1638 {
1639 if((receiveMessage = receiveRead.readLine()) != null)
1640 {
1641 System.out.println(receiveMessage);
1642 }
1643 sendMessage = keyRead.readLine();
1644 pwrite.println(sendMessage);
1645 pwrite.flush();
1646 }
1647 }
1648}
1649
1650Client:
1651import java.io.*;
1652import java.net.*;
1653public class chatclient
1654{
1655 public static void main(String[] args) throws Exception
1656 {
1657 Socket sock = new Socket("127.0.0.1", 3000);
1658 BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
1659
1660 OutputStream ostream = sock.getOutputStream();
1661 PrintWriter pwrite = new PrintWriter(ostream, true);
1662 InputStream istream = sock.getInputStream();
1663 BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
1664 System.out.println("Start the chitchat, type and press Enter key");
1665 String receiveMessage, sendMessage;
1666 while(true)
1667 {
1668 sendMessage = keyRead.readLine();
1669 pwrite.println(sendMessage);
1670 pwrite.flush();
1671 if((receiveMessage = receiveRead.readLine()) != null)
1672 {
1673 System.out.println(receiveMessage);
1674 }
1675 }
1676 }
1677}
1678
1679
1680Q5) 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 the TCP/IP protocol. Write a Java program for the above.
1681
1682Code :
1683//server
1684
1685import java.net.*;
1686
1687import java.io.*;
1688
1689import java.util.*;
1690
1691
1692
1693class EncServer
1694
1695{
1696
1697 public static void main(String args[]) throws Exception
1698
1699 {
1700
1701 ServerSocket se=new ServerSocket(5217);
1702 Socket soc=se.accept();
1703
1704 BufferedReader in=new BufferedReader(
1705
1706 new InputStreamReader(
1707
1708 soc.getInputStream()
1709
1710 )
1711
1712 );
1713
1714 String s = in.readLine();
1715 System.out.println(s);
1716 String sp ="";
1717 char cp;
1718 for(int i=0;i<s.length();i++)
1719 {
1720 if(s.charAt(i) == 'z')
1721 {
1722 cp = 'a';
1723 }
1724 else{
1725 int c = (int) s.charAt(i);
1726
1727 c++;
1728 cp = (char) c;
1729
1730 }
1731 sp = sp + cp;
1732 }
1733
1734
1735
1736
1737 OutputStream out = soc.getOutputStream();
1738 PrintWriter pr=new PrintWriter(out);
1739 pr.println(sp);
1740 out.close();
1741 soc.close();
1742
1743
1744
1745
1746 }
1747
1748}
1749//client
1750import java.io.*;
1751
1752import java.net.*;
1753
1754import java.util.*;
1755
1756class EncClient
1757
1758{
1759
1760 public static void main(String args[]) throws Exception
1761
1762 {
1763
1764 Scanner sc = new Scanner(System.in);
1765
1766
1767 System.out.println("Enter Message to Encode");
1768 String name = sc.next();
1769
1770 Socket soc=new Socket(InetAddress.getLocalHost(),5217);
1771 OutputStream out = soc.getOutputStream();
1772 PrintWriter pr=new PrintWriter(out);
1773 //System.out.println(name);
1774 pr.println(name);
1775
1776
1777
1778 BufferedReader in=new BufferedReader(
1779
1780 new InputStreamReader(
1781
1782 soc.getInputStream()
1783
1784 )
1785
1786 );
1787
1788 System.out.println(in.readLine());
1789
1790 soc.close();
1791
1792 }
1793
1794}
1795
1796Q6) 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 Java program for the above.
1797
1798Code :
1799
1800import java.io.*;
1801
1802import java.net.*;
1803
1804public class client{
1805public static void main (string args[])
1806{
1807try{
1808InetAddress a = InetAddress.getByName("localhost");
1809Scanner sc = new Scanner(System.in);
1810
1811
1812 System.out.println("Enter Message to Encode");
1813 String name = sc.next();
1814
1815 Socket soc=new Socket(InetAddress.getLocalHost(),5217);
1816 OutputStream out = soc.getOutputStream();
1817 PrintWriter pr=new PrintWriter(out);
1818 //System.out.println(name);
1819 pr.println(name);
1820
1821
1822
1823 BufferedReader in=new Buffered(new InputStreamReader(soc.getInputStream());
1824 System.out.println(in.readLine());
1825
1826 soc.close();
1827
1828
1829
1830
1831
1832 }
1833
1834}
1835}
1836
1837//Server
1838class Server
1839
1840{
1841
1842 public static void main(String args[]) throws Exception
1843
1844 {
1845
1846 ServerSocket se=new ServerSocket(5217);
1847 Socket soc=se.accept();
1848
1849 BufferedReader in=new BufferedReader(
1850
1851 new InputStreamReader(
1852
1853 soc.getInputStream()
1854
1855 )
1856
1857 );
1858
1859 String s = in.readLine();
1860 System.out.println(s);
1861 String sp ="";
1862 char cp;
1863 for(int i=0;i<s.length();i++)
1864 {
1865 if(s.charAt(i) == 'z')
1866 {
1867 cp = 'a';
1868 }
1869 else{
1870 int c = (int) s.charAt(i);
1871
1872 c++;
1873 cp = (char) c;
1874
1875 }
1876 sp = sp + cp;
1877 }
1878
1879
1880
1881
1882 OutputStream out = soc.getOutputStream();
1883 PrintWriter pr=new PrintWriter(out);
1884 pr.println(sp);
1885 out.close();
1886 soc.close();
1887
1888
1889
1890
1891 }
1892
1893}
1894
18957. Write a Java program to display the name and address of the computer that we are currently working on.
1896CODE:
1897import java.net.*;
1898public class ques7 {
1899public static void main (String[] args) {
1900try {
1901InetAddress address = InetAddress.getLocalHost();
1902System.out.println(address);
1903}
1904catch (UnknownHostException ex) {
1905System.out.println("Could not find this computer's address.");
1906}
1907}
1908}
1909
1910OUTPUT:
1911
1912
1913
1914
1915
1916
1917
1918
1919 9. Using threading concepts, write a Java program to create a daemon process.
1920
1921CODE:
1922public class TestDaemonThread extends Thread{
1923 public void run(){
1924 if(Thread.currentThread().isDaemon()){
1925 System.out.println("daemon thread work");
1926 }
1927 else{
1928 System.out.println("user thread work");
1929 }
1930 }
1931 public static void main(String[] args){
1932 TestDaemonThread t1=new TestDaemonThread();
1933 TestDaemonThread t2=new TestDaemonThread();
1934 TestDaemonThread t3=new TestDaemonThread();
1935
1936 t1.setDaemon(true);
1937 t2.setDaemon(true);
1938 t1.start();
1939 t2.start();
1940 t3.start();
1941 }
1942}
1943
1944
1945
1946
1947
1948
1949
1950OUTPUT:
1951
1952Q10) A server should run for 10 secs and generate numbers continuously. The client connecting to it should read data and find out the sum of the data thus read. Write a Java program to implement this scenario.
1953
1954Code : Client
1955import java.io.*;
1956
1957import java.net.*;
1958import java.util.*;
1959
1960
1961class RandomClient
1962
1963{
1964
1965 public static void main(String args[]) throws Exception
1966
1967 {
1968
1969 Socket soc=new Socket(InetAddress.getLocalHost(),5217);
1970 int sum = 0;
1971 BufferedReader in=new BufferedReader(
1972
1973 new InputStreamReader(
1974
1975 soc.getInputStream()
1976
1977 )
1978
1979 );
1980
1981
1982 int count =0;
1983 int n=1;
1984 while(n!=-1)
1985 {
1986 try{
1987 n = Integer.parseInt(in.readLine());
1988 System.out.println(n);
1989 sum = sum + n;
1990 count ++;
1991 }catch(Exception e)
1992 {
1993 n=-1;
1994 }
1995
1996
1997 }
1998 soc.close();
1999 System.out.println("Sum " + sum/count);
2000 }
2001
2002}
2003//server
2004
2005import java.net.*;
2006
2007import java.io.*;
2008
2009import java.util.*;
2010
2011
2012
2013class RandomServer
2014
2015{
2016
2017 public static void main(String args[]) throws Exception
2018
2019 {
2020
2021 ServerSocket s=new ServerSocket(5217);
2022 Date d = new Date();
2023 Random r = new Random();
2024 Socket soc=s.accept();
2025 int n=1;
2026 OutputStream out = soc.getOutputStream();
2027 PrintWriter pr=new PrintWriter(out);
2028 while(soc.isConnected() && n != -1)
2029 {
2030 long t= System.currentTimeMillis();
2031 long end = t+10000;
2032
2033 //System.out.println("hello");
2034 while((System.currentTimeMillis() < end))
2035
2036 {
2037 int x=15;
2038 n = r.nextInt(10);
2039 pr.println(n);
2040 pr.flush();
2041
2042
2043 }
2044 pr.flush();
2045 n=-1;
2046 pr.println(n);
2047 out.close();
2048 soc.close();
2049
2050 }
2051
2052
2053 }
2054
2055}
2056
2057
2058
2059
2060
2061
2062
2063
2064------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2065basics
2066Basic network commands
2067ping
2068The ping command (named after the sound of an active sonar system) sends echo requests to the host
2069specified on the command line, and lists the responses received.
2070$ ping ipAddress or hostname
2071e.g
2072$ ping www.vit.ac.in
2073• ping - sends an ICMP ECHO_REQUEST packet to the specified host. If the host responds, an
2074ICMP packet is received.
2075• One can “ping†an IP address to see if a machine is alive.
2076• It provides a very quick way to see if a machine is up and connected to the network.
2077netstat
2078• It works with the LINUX Network Subsystem, it will tell you what the status of ports are ie. open,
2079closed, waiting connections. It is used to display the TCP/IP network protocol statistics and
2080information.
2081tcpdump
2082This is a sniffer, a program that captures packets off a network interface and interprets them.
2083hostname
2084Tells the user the host name of the computer they are logged into.
2085traceroute
2086traceroute will show the route of a packet. It attempts to list the series of hosts through which your
2087packets travel on their way to a given destination.
2088Command syntax:
2089traceroute machine_name_or_ip
2090e.g traceroute www.vit.ac.in
2091Each host will be displayed, along with the response times at each host.
2092finger
2093Retrieves information about the specified user.
2094e.g finger bit50001
2095ifconfig ( In Windows use ipconfig )
2096This command is used to configure network interfaces, or to display their current configuration.
2097dig
2098The "domain information groper" tool. If you give a hostname as an argument to output information
2099about that host, including it's IP address, hostname and various other information.
2100e.g dig vitlinux
2101telnet
2102telnet allows you to log in to a computer, just as if you were sitting at the terminal. Once your
2103username and password are verified, you are given a shell prompt. From here, you can do anything
2104requiring a text console.
2105ftp
2106To connect to an FTP server use
2107ftp ipaddress
2108netstat
2109Displays contents of /proc/net files. It works with the LINUX Network Subsystem, it will tell
2110you what the status of ports are ie. open, closed, waiting, masquerade connections. It will also
2111display various other things. It has many different options.
2112tcpdump
2113This is a sniffer, a program that captures packets off a network interface and interprets them
2114for you. It understands all basic internet protocols, and can be used to save entire packets for
2115later inspection.
2116ping
2117The ping command (named after the sound of an active sonar system) sends echo requests to
2118the host you specify on the command line, and lists the responses received their round trip
2119time.
2120You simply use ping as:
2121ping ip_or_host_name
2122hostname
2123Tells the user the host name of the computer they are logged into. Note: may be called host.
2124traceroute
2125traceroute will show the route of a packet. It attempts to list the series of hosts through which
2126your packets travel on their way to a given destination. Also have a look at xtraceroute (one
2127of several graphical equivalents of this program).
2128Command syntax:
2129traceroute machine_name_or_ip
2130tracepath
2131tracepath performs a very simlar function to traceroute the main difference is that tracepath
2132doesn't take complicated options.
2133Command syntax:
2134tracepath machine_name_or_ip
2135findsmb
2136findsmb is used to list info about machines that respond to SMB name queries (for example
2137windows based machines sharing their hard disk's).
2138Command syntax:
2139Findsmb
2140This would find all machines possible, you may need to specify a particular subnet to query
2141those machines only...
2142nmap
2143“ network exploration tool and security scannerâ€. nmap is a very advanced network tool used
2144to query machines (local or remote) as to whether they are up and what ports are open on
2145these machines.
2146A simple usage example:
2147nmap machine_name
2148This would query your own machine as to what ports it keeps open. nmap is a very powerful
2149tool, documentation is available on the nmap site as well as the information in the manual
2150page.
2151telnet
2152Someone once stated that telnet(1) was the coolest thing he had ever seen on computers. The ability
2153to remotely log in and do stuff on another computer is what separates Unix and Unix-like operating
2154systems from other operating systems.
2155telnet allows you to log in to a computer, just as if you were sitting at the terminal. Once your
2156username and password are verified, you are given a shell prompt. From here, you can do anything
2157requiring a text console. Compose email, read newsgroups, move files around, and so on. If you are
2158running X and you telnet to another machine, you can run X programs on the remote computer and
2159display them on yours.
2160To login to a remote machine, use this syntax:
2161% telnet <hostname>
2162If the host responds, you will receive a login prompt. Give it your username and password. That's it.
2163You are now at a shell. To quit your telnet session, use either the exit command or the logout
2164command.
2165telnet does not encrypt the information it sends. Everything is sent in plain text, even passwords.
2166It is not advisable to use telnet over the Internet. Instead, consider the Secure Shell. It encrypts
2167all traffic and is available for free.
2168The other use of telnet
2169Now that we have convinced you not to use the telnet protocol anymore to log into a remote machine,
2170we'll show you a couple of useful ways to use telnet.
2171You can also use the telnet command to connect to a host on a certain port.
2172% telnet <hostname> [port]
2173This can be quite handy when you quickly need to test a certain service, and you need full control
2174over the commands, and you need to see what exactly is going on. You can interactively test or use
2175an SMTP server, a POP3 server, an HTTP server, etc. this way.
2176In the next figure you'll see how you can telnet to a HTTP server on port 80, and get some basic
2177information from it.
2178Figure 13-1. Telnetting to a webserver
2179% telnet store.slackware.com 80
2180Trying 69.50.233.153...
2181Connected to store.slackware.com.
2182Escape character is '^]'.
2183HEAD / HTTP/1.0
2184HTTP/1.1 200 OK
2185Date: Mon, 25 Apr 2005 20:47:01 GMT
2186Server: Apache/1.3.33 (Unix) mod_ssl/2.8.22 OpenSSL/0.9.7d
2187Last-Modified: Fri, 18 Apr 2003 10:58:54 GMT
2188ETag: "193424-c0-3e9fda6e"
2189Accept-Ranges: bytes
2190Content-Length: 192
2191Connection: close
2192Content-Type: text/html
2193Connection closed by foreign host.
2194%
21951-)arp :
2196When we need an Ethernet (MAC) address we can use arp(address resolution protocol).
2197In other words it shows the physical address of an host.
2198Example:
2199C:\Documents and Settings\sysadm>arp -a
2200Interface: 169.254.195.199 --- 0x2
2201Internet Address Physical Address Type
2202216.109.127.60 00-53-45-00-00-00 static
22032-)nslookup:
2204Displays information from Domain Name System (DNS) name servers.
2205Example:
2206C:\Documents and Settings\sysadm>nslookup itu.dk
2207Server: ns3.inet.tele.dk
2208Address: 193.162.153.164
2209Non-authoritative answer:
2210Name: itu.dk
2211Address: 130.226.133.2
2212NOTE :If you write the command as above it shows as default your pc's server name firstly.
2213C:\Documents and Settings\sysadm>nslookup mail.yahoo.com itu.dk
2214Server: superman.itu.dk
2215Address: 130.226.133.2
2216Non-authoritative answer:
2217Name: login.yahoo.akadns.net
2218Address: 216.109.127.60
2219Aliases: mail.yahoo.com, login.yahoo.com
2220NOTE:Remark that in the second example we do not see the default server name.
2221There are many nslookup with optional commands.To read them type nslookup and enter
2222then type help and enter.
22233-)finger:
2224Displays the information about a user on the system.
2225Example:
2226NOTE :I could not find out the name of the server that we log on (windows) at the school.
2227Sysadmin does not know that either:o)
2228But as an example I tried it on the our unix server.
2229[hilmiolgun@ssh hilmiolgun]$ finger
2230Login Name Tty Idle Login Time Office Office Phone
2231adel Adel Abu-Sharkh pts/1 7 Sep 10 00:11 (cpe.atm2-0-
22321091080.0x50a0bcb2.albnxx13.customer.tele.dk)
2233adel Adel Abu-Sharkh pts/2 9 Sep 9 23:56 (cpe.atm2-0-
22341091080.0x50a0bcb2.albnxx13.customer.tele.dk)
2235hilmiolgun Hilmi Olgun pts/9 Sep 10 00:20 (0x3ef3e2fe.albnxx8.adsl.tele.dk)
2236hm Hanne Munkholm pts/6 1:56 Sep 8 21:27 (off180.palombia.dk)
2237jcg Jens Christian Godsk pts/4 1d Sep 8 10:28 (toscana.itu.dk)
2238kaj Kenneth Ahn Jensen pts/7 Sep 10 00:11 (cpe.atm2-0-
223954493.0x50a4ad32.boanxx12.customer.tele.dk)
2240root root pts/8 1 Sep 10 00:12 (sysadm2.itu.dk)
2241troels Troels Arvin pts/5 3:49 Sep 9 20:31 (62.79.119.132.adsl.vbr.worldonline.dk)
2242webclaus Claus Bech Rasmussen pts/0 6 Sep 10 00:11 (port967.ds1-khk.adsl.cybercity.dk)
2243NOTE :What I did is :I first check the online users,and get a list of them(above).
2244Then i just choosed one user to get information about him(below)
2245[hilmiolgun@ssh hilmiolgun]$ finger hm
2246Login: hm Name: Hanne Munkholm
2247Directory: /import/home/hm Shell: /bin/bash
2248On since Mon Sep 8 21:27 (CEST) on pts/6 from off180.palombia.dk
22491 hour 56 minutes idle
2250Last login Tue Sep 9 11:05 (CEST) on pts/12 from stud127.itu.dk
2251New mail received Mon Nov 11 23:01 2002 (CET)
2252Unread since Sat Oct 5 00:00 2002 (CEST)
2253Plan:
2254World Domination... fast.
2255[hilmiolgun@ssh hilmiolgun]$
22564-)ping:
2257Simpy shows if the remote machine is available or not....
2258Example:
2259C:\Documents and Settings\sysadm>ping webmail.itu.dk
2260Pinging tarzan.itu.dk [130.226.133.3] with 32 bytes of data:
2261Reply from 130.226.133.3: bytes=32 time=29ms TTL=55
2262Reply from 130.226.133.3: bytes=32 time=30ms TTL=55
2263Reply from 130.226.133.3: bytes=32 time=30ms TTL=55
2264Reply from 130.226.133.3: bytes=32 time=30ms TTL=55
2265Ping statistics for 130.226.133.3:
2266Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
2267Approximate round trip times in milli-seconds:
2268Minimum = 29ms, Maximum = 30ms, Average = 29ms
2269NOTE :Remark that the remote machine is replying.Otherwise the output will be "Request time out"
2270which means the
2271remote machine is not working well.(Not answering)
22725-)tracert:
2273It simply shows the path between source and destination address.
2274Example:
2275C:\Documents and Settings\sysadm>tracert webmail.itu.dk
2276Tracing route to tarzan.itu.dk [130.226.133.3]
2277over a maximum of 30 hops:
22781 * * * Request timed out.
22792 29 ms 19 ms 29 ms ge-0-2-1-2.1000M.albnxu1.ip.tele.dk [195.249.1.2 9]
22803 29 ms 29 ms 19 ms pos1-0.622M.lynxg1.ip.tele.dk [195.249.2.46]
22814 29 ms 19 ms 29 ms herman.fsknet.lyngby.forskningsnettet.dk [192.38 .7.1]
22825 29 ms 29 ms 19 ms 130.225.244.214
22836 29 ms 29 ms 29 ms 1.ku.forskningsnettet.dk [130.225.245.90]
22847 29 ms 29 ms 29 ms rk.itu.forskningsnettet.dk [130.226.249.30]
22858 29 ms 29 ms 29 ms 130.225.245.86
22869 29 ms 29 ms 29 ms tarzan.itu.dk [130.226.133.3]
2287Trace complete.
22886-)ftp:
2289For file transferring..(File transfer protocol)
2290Example:Lets you dont have an ftp software and you want to get a file from your school harddisk.
2291So to do that:
2292C:\Documents and Settings\sysadm>ftp
2293ftp> open
2294To ftp.itu.dk
2295Connected to ssh.itu.dk.
2296220 ProFTPD 1.2.8rc2 Server (ProFTPD Default Installation) [ssh.it-c.dk]
2297NOTE:What am I doing is simply:typing them one-by-one(after each typing remember to enter)
2298ftp,open,ftp.itu.dk
2299User (ssh.itu.dk:(none)): hilmiolgun
2300331 Password required for hilmiolgun.
2301Password:
2302230 User hilmiolgun logged in.
2303NOTE:The server will require username and password..
2304ftp> help
2305Commands may be abbreviated. Commands are:
2306! delete literal prompt send
2307? debug ls put status
2308append dir mdelete pwd trace
2309ascii disconnect mdir quit type
2310bell get mget quote user
2311binary glob mkdir recv verbose
2312bye hash mls remotehelp
2313cd help mput rename
2314close lcd open rmdir
2315ftp> help dir
2316dir List contents of remote directory
2317NOTE: If it is your first time to those commands just type help and get the commands.If you dont
2318know how to use
2319them type help commandname..
2320ftp> dir
2321200 PORT command successful
2322150 Opening ASCII mode data connection for file list
2323drwx------ 4 hilmiolgun hilmiolgun 155 Jul 1 14:02 Desktop
2324drwx------ 2 hilmiolgun hilmiolgun 4096 May 30 10:21 Mail
2325drwxr-xr-x 5 hilmiolgun hilmiolgun 90 Sep 2 02:59 MobilePositionSDK
2326drwx------ 7 hilmiolgun hilmiolgun 4096 Aug 8 2002 NTnetscape
2327drwxr--r-- 13 hilmiolgun hilmiolgun 4096 Sep 4 01:56 New Folder
2328-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 TTI409B
2329drwx------ 2 hilmiolgun hilmiolgun 6 Jan 21 2002 cgi-bin
2330-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 geu
2331-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 hilmiolgun
2332drwxr-xr-x 6 hilmiolgun hilmiolgun 4096 Aug 14 15:59 image
2333drwxr-xr-x 3 hilmiolgun hilmiolgun 4096 Jul 29 16:03 jmf20-apidocs
2334drwxr-xr-x 4 hilmiolgun hilmiolgun 4096 Sep 9 14:10 NOTEsieee
2335drwx------ 2 hilmiolgun hilmiolgun 6 Feb 21 2002 nsmail
2336drwx------ 3 hilmiolgun hilmiolgun 103 Feb 21 2002 office52
2337drwx------ 2 hilmiolgun hilmiolgun 6 Jan 21 2002 private
2338drwxr--rwx 2 hilmiolgun hilmiolgun 4096 Aug 23 12:02 public_html
2339drwxr-xr-x 5 hilmiolgun hilmiolgun 4096 Sep 6 03:30 speech
2340-rw-rw-r-- 1 hilmiolgun hilmiolgun 2630 Sep 9 13:58 test.txt
2341-rw-rw-r-- 1 hilmiolgun hilmiolgun 148 Sep 9 14:03 testing.txt
2342226 Transfer complete.
2343ftp: 1318 bytes received in 0,24Seconds 5,49Kbytes/sec.
2344ftp> get testing.txt
2345200 PORT command successful
2346150 Opening ASCII mode data connection for testing.txt (148 bytes)
2347226 Transfer complete.
2348ftp: 161 bytes received in 0,02Seconds 8,05Kbytes/sec.
2349NOTE :After taking a look to the school harddisk ,I copied a file "testing.txt" to my local harddisk....
2350ftp> !dir
2351Volume in drive C has no label.
2352Volume Serial Number is 0868-D52D
2353Directory of C:\Documents and Settings\sysadm
235410-09-2003 00:21 <DIR> .
235510-09-2003 00:21 <DIR> ..
235631-08-2003 07:28 <DIR> .java
235725-04-2003 12:18 <DIR> .javaws
235823-04-2003 15:26 <DIR> .jpi_cache
235926-08-2003 04:59 <DIR> .Nokia
236007-09-2003 01:46 12.546 .plugin140_03.trace
236107-09-2003 04:46 693 .plugin141_02.trace
236207-09-2003 01:20 164 .saves-3824-IBMR31IMAGE
236307-09-2003 01:20 <DIR> Desktop
236407-09-2003 08:05 <DIR> Favorites
236506-09-2003 05:29 80.140 love.wav
236609-09-2003 23:45 <DIR> mindterm
236709-09-2003 11:02 <DIR> My Documents
236810-09-2003 00:21 2.903 plugin131_08.trace
236925-04-2003 11:44 <DIR> Start Menu
237006-09-2003 21:21 <DIR> studio5se_user
237106-09-2003 05:32 18 test.txt
237206-09-2003 05:20 70 testing
237310-09-2003 00:37 161 testing.txt
237426-08-2003 03:46 <DIR> WINDOWS
23758 File(s) 96.695 bytes
237613 Dir(s) 3.842.056.192 bytes free
2377ftp> send love.wav
2378200 PORT command successful
2379150 Opening ASCII mode data connection for love.wav
2380226 Transfer complete.
2381ftp: 80140 bytes sent in 3,97Seconds 20,21Kbytes/sec.
2382ftp> dir
2383200 PORT command successful
2384150 Opening ASCII mode data connection for file list
2385drwx------ 4 hilmiolgun hilmiolgun 155 Jul 1 14:02 Desktop
2386drwx------ 2 hilmiolgun hilmiolgun 4096 May 30 10:21 Mail
2387drwxr-xr-x 5 hilmiolgun hilmiolgun 90 Sep 2 02:59 MobilePositionSDK
2388drwx------ 7 hilmiolgun hilmiolgun 4096 Aug 8 2002 NTnetscape
2389drwxr--r-- 13 hilmiolgun hilmiolgun 4096 Sep 4 01:56 New Folder
2390-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 TTI409B
2391drwx------ 2 hilmiolgun hilmiolgun 6 Jan 21 2002 cgi-bin
2392-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 geu
2393-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 hilmiolgun
2394drwxr-xr-x 6 hilmiolgun hilmiolgun 4096 Aug 14 15:59 image
2395drwxr-xr-x 3 hilmiolgun hilmiolgun 4096 Jul 29 16:03 jmf20-apidocs
2396-rw-rw-r-- 1 hilmiolgun hilmiolgun 80137 Sep 9 22:36 love.wav
2397drwxr-xr-x 4 hilmiolgun hilmiolgun 4096 Sep 9 14:10 NOTEsieee
2398drwx------ 2 hilmiolgun hilmiolgun 6 Feb 21 2002 nsmail
2399drwx------ 3 hilmiolgun hilmiolgun 103 Feb 21 2002 office52
2400drwx------ 2 hilmiolgun hilmiolgun 6 Jan 21 2002 private
2401drwxr--rwx 2 hilmiolgun hilmiolgun 4096 Aug 23 12:02 public_html
2402drwxr-xr-x 5 hilmiolgun hilmiolgun 4096 Sep 6 03:30 speech
2403-rw-rw-r-- 1 hilmiolgun hilmiolgun 2630 Sep 9 13:58 test.txt
2404-rw-rw-r-- 1 hilmiolgun hilmiolgun 148 Sep 9 14:03 testing.txt
2405226 Transfer complete.
2406ftp: 1387 bytes received in 0,07Seconds 19,81Kbytes/sec.
2407ftp>
2408NOTE:At the end first looking at the local working directory and sending a file "love.wav" to the
2409school harddisk.
24107-)net:
2411It has many options,which are for checking/starting/stopping nt
2412services,users,messaging,configuration and so on...
2413Some of those options require administration privileges..
2414Example:
2415NOTE: To have an overview of commands options....
2416C:\Documents and Settings\sysadm>net
2417The syntax of this command is:
2418NET COMMANDS
2419NET [ ACCOUNTS | COMPUTER | CONFIG | CONTINUE | FILE | GROUP | HELP |
2420HELPMSG | LOCALGROUP | NAME | PAUSE | PRINT | SEND | SESSION |
2421SHARE | START | STATISTICS | STOP | TIME | USE | USER | VIEW ]
2422NOTE: And furthermore to get an overview of a specific option ...
2423C:\Documents and Settings\sysadm>net help print
2424The syntax of this command is:
2425NET PRINT
2426\\computername\sharename
2427[\\computername] job# [/HOLD | /RELEASE | /DELETE]
2428NET PRINT displays print jobs and shared queues.
2429For each queue, the display lists jobs, showing the size
2430and status of each job, and the status of the queue.
2431\\computername Is the name of the computer sharing the printer
2432queue(s).
2433sharename Is the name of the shared printer queue.
2434job# Is the identification number assigned to a print
2435job. A computer with one or more printer queues
2436assigns each print job a unique number.
2437/HOLD Prevents a job in a queue from printing.
2438The job stays in the printer queue, and other
2439jobs bypass it until it is released.
2440/RELEASE Reactivates a job that is held.
2441/DELETE Removes a job from a queue.
2442NET HELP command | MORE displays Help one screen at a time.
2443Finally in addition to above there are also those commands: hostname ,lpq, lpr ,rsh ,tftp ,nbstat
2444,netstat.
2445To get familiar with those commands simply type commandname /? at the command line.
2446C:\>net
2447The syntax of this command is:
2448NET [ ACCOUNTS | COMPUTER | CONFIG | CONTINUE | FILE | GROUP | HELP |
2449HELPMSG | LOCALGROUP | NAME | PAUSE | PRINT | SEND | SESSION |
2450SHARE | START | STATISTICS | STOP | TIME | USE | USER | VIEW ]
2451C:\>net use
2452New connections will not be remembered.
2453Status Local Remote Network
2454-------------------------------------------------------------------------------
2455OK F: \\cse-sec\fac Microsoft Windows Network
2456C:\>net user
2457User accounts for \\CSE-DEPT-05
2458-------------------------------------------------------------------------------
2459Administrator Guest
2460C:\>net statistics
2461Statistics are available for the following running services:
2462Server
2463Workstation
2464Displays protocol statistics and current TCP/IP network connections.
2465NETSTAT [-a] [-e] [-n] [-s] [-p proto] [-r] [interval]
2466-a Displays all connections and listening ports.
2467-e Displays Ethernet statistics. This may be combined with the
2468-s option.
2469-n Displays addresses and port numbers in numerical form.
2470-p proto Shows connections for the protocol specified by proto; proto
2471may be TCP or UDP. If used with the -s option to display
2472per-protocol statistics, proto may be TCP, UDP, or IP.
2473-r Displays the routing table.
2474-s Displays per-protocol statistics. By default, statistics
2475are shown for TCP, UDP and IP; the -p option may be used
2476to specify a subset of the default.
2477interval Redisplays selected statistics, pausing interval seconds
2478between each display. Press CTRL+C to stop redisplaying
2479statistics. If omitted, netstat will print the current
2480configuration information once.
2481C:\>net name
2482Name
2483-------------------------------------------------------------------------------
2484CSE-DEPT-05
2485C:\>net session
2486Computer User name Client Type Opens Idle time
2487-------------------------------------------------------------------------------
2488\\ENGLISH-03 Windows NT 1381 0 00:10:47
2489\\ENGLISHBDC Windows NT 1381 0 00:02:01
2490C:\>net accounts
2491Force user logoff how long after time expires?: Never
2492Minimum password age (days): 0
2493Maximum password age (days): 42
2494Minimum password length: 0
2495Length of password history maintained: None
2496Lockout threshold: Never
2497Lockout duration (minutes): 30
2498Lockout observation window (minutes): 30
2499Computer role: WORKSTATION
2500C:\>net localgroup
2501Aliases for \\CSE-DEPT-05
2502-------------------------------------------------------------------------------
2503*Administrators *Backup Operators *Guests
2504*Power Users *Replicator *Users
2505C:\>net config server
2506Server Name \\CSE-DEPT-05
2507Server Comment
2508Software version Windows NT 4.0
2509Server is active on NetBT_DLKRTS1 (0050ba8b326b) NetBT_DLKRTS1
2510(0050ba8b326b) NwlnkIpx (0050ba8b326b) NwlnkNb (0050ba8b326b) Nbf_DLKRTS1 (0050
2511ba8b326b)
2512Server hidden No
2513Maximum Logged On Users 10
2514Maximum open files per session 2048
2515Idle session time (min) 15
2516C:\>net config workstation
2517Computer name \\CSE-DEPT-05
2518User name Administrator
2519Workstation active on NwlnkNb (0050BA8B326B) NetBT_DLKRTS1 (0050B
2520A8B326B) Nbf_DLKRTS1 (0050BA8B326B)
2521Software version Windows NT 4.0
2522Workstation domain WORKGROUP
2523Logon domain CSE-DEPT-05
2524COM Open Timeout (sec) 3600
2525COM Send Count (byte) 16
2526COM Send Timeout (msec) 250
2527C:\>net share
2528Share name Resource Remark
2529-------------------------------------------------------------------------------
2530D$ D:\ Default share
2531IPC$ Remote IPC
2532C$ C:\ Default share
2533ADMIN$ C:\WINNT Remote Admin
2534E$ E:\ Default share
2535abishek E:\abishek
2536akshu E:\akshu
2537HARSHINI D:\ HARSHINI
2538DHARSHINI E:\ DHARSHINI
2539C:\>net stop messenger
2540The Messenger service is stopping.
2541The Messenger service was stopped successfully.
2542C:\>net start messenger
2543The Messenger service is starting...
2544The Messenger service was started successfully.
2545Network Configuration commands
2546ifconfig
2547This command is used to configure network interfaces, or to display their current
2548configuration. In addition to activating and deactivating interfaces with the “up†and “downâ€
2549settings, this command is necessary for setting an interface's address information if you don't
2550have the ifcfg script.
2551Use ifconfig as either:
2552ifconfig
2553This will simply list all information on all network devices currently up.
2554ifconfig eth0 down
2555This will take eth0 (assuming the device exists) down, it won't be able to receive or send
2556anything until you put the device back “up†again.
2557Clearly there are a lot more options for this tool, you will need to read the manual/info page to
2558learn more about them.
2559ifup
2560Use ifup device-name to bring an interface up by following a script (which will contain your
2561default networking settings). Simply type ifup and you will get help on using the script.
2562For example typing:
2563ifup eth0
2564Will bring eth0 up if it is currently down.
2565ifdown
2566Use ifdown device-name to bring an interface down using a script (which will contain your
2567default network settings). Simply type ifdown and you will get help on using the script.
2568For example typing:
2569ifdown eth0
2570Will bring eth0 down if it is currently up.
2571ifcfg
2572Use ifcfg to configure a particular interface. Simply type ifcfg to get help on using this script.
2573For example, to change eth0 from 192.168.0.1 to 192.168.0.2 you could do:
2574ifcfg eth0 del 192.168.0.1
2575ifcfg eth0 add 192.168.0.2
2576The first command takes eth0 down and removes that stored IP address and the second one
2577brings it back up with the new address.
2578route
2579The route command is the tool used to display or modify the routing table. To add a gateway
2580as the default you would type:
2581route add default gw some_computer
2582INTERNET SPECIFIC COMMANDS
2583host
2584Performs a simple lookup of an internet address (using the Domain Name System, DNS).
2585Simply type:
2586host ip_address
2587or
2588host domain_name
2589dig
2590The "domain information groper" tool. More advanced then host... If you give a hostname as
2591an argument to output information about that host, including it's IP address, hostname and
2592various other information.
2593For example, to look up information about “www.amazon.com†type:
2594dig www.amazon.com
2595To find the host name for a given IP address (ie a reverse lookup), use dig with the `-x' option.
2596dig -x 100.42.30.95
2597This will look up the address (which may or may not exist) and returns the address of the
2598host, for example if that was the address of “http://slashdot.org†then it would return
2599“http://slashdot.orgâ€.
2600dig takes a huge number of options (at the point of being too many), refer to the manual page
2601for more information.
2602whois
2603(now BW whois) is used to look up the contact information from the “whois†databases, the
2604servers are only likely to hold major sites. Note that contact information is likely to be hidden
2605or restricted as it is often abused by crackers and others looking for a way to cause malicious
2606damage to organisation's.
2607wget
2608(GNU Web get) used to download files from the World Wide Web.
2609To archive a single web-site, use the -m or --mirror (mirror) option.
2610Use the -nc (no clobber) option to stop wget from overwriting a file if you already have it.
2611Use the -c or --continue option to continue a file that was unfinished by wget or another
2612program.
2613Simple usage example:
2614wget url_for_file
2615This would simply get a file from a site.
2616wget can also retrieve multiple files using standard wildcards, the same as the type used in
2617bash, like *, [ ], ?. Simply use wget as per normal but use single quotation marks (' ') on the
2618URL to prevent bash from expanding the wildcards. There are complications if you are
2619retrieving from a http site (see below...).
2620Advanced usage example, (used from wget manual page):
2621wget --spider --force-html -i bookmarks.html
2622This will parse the file bookmarks.html and check that all the links exist.
2623Advanced usage: this is how you can download multiple files using http (using a wildcard...).
2624Notes: http doesn't support downloading using standard wildcards, ftp does so you may use
2625wildcards with ftp and it will work fine. A work-around for this http limitation is shown
2626below:
2627wget -r -l1 --no-parent -A.gif http://www.website.com[1]
2628This will download (recursively), to a depth of one, in other words in the current directory and
2629not below that. This command will ignore references to the parent directory, and downloads
2630anything that ends in “.gifâ€. If you wanted to download say, anything that ends with “.pdf†as
2631well than add a -A.pdf before the website address. Simply change the website address and the
2632type of file being downloaded to download something else. Note that doing -A.gif is the same
2633as doing -A “*.gif†(double quotes only, single quotes will not work).
2634wget has many more options refer to the examples section of the manual page, this tool is very
2635well documented.
2636Alternative website downloaders: You may like to try alternatives like httrack. A full GUI
2637website downloader written in python and available for GNU/Linux
2638curl
2639curl is another remote downloader. This remote downloader is designed to work without user
2640interaction and supports a variety of protocols, can upload/download and has a large number
2641of tricks/work-arounds for various things. It can access dictionary servers (dict), ldap servers,
2642ftp, http, gopher, see the manual page for full details.
2643To access the full manual (which is huge) for this command type:
2644curl -M
2645For general usage you can use it like wget. You can also login using a user name by using the
2646-u option and typing your username and password like this:
2647curl -u username:password http://www.placetodownload/file
2648To upload using ftp you the -T option:
2649curl -T file_name ftp://ftp.uploadsite.com
2650To continue a file use the -C option:
2651curl -C - -o file http://www.site.com
2652View and modify network interfaces
2653ifconfig -a Show information about all network interfaces
2654ifconfig eth0 Show information only about the interface eth0
2655ifconfig eth0 up Bring up the interface eth0
2656ifconfig eth0 down Take down the interface eth0
2657Simple network diagnostic commands
2658ping hostname Send ICMP echo requests to the host hostname
2659traceroute hostname Trace the network path to hostname
2660View open network connections
2661netstat -a Show information about all open network connections
2662netstat -a | grep LISTEN Show information about all open network ports
2663Set/view routing information
2664netstat -r View system routing tables
2665route View system routing tables
2666The command route can also be used to add or delete routes. Examples:
2667route add -host 192.168.3.4 gw 192.168.3.1 netmask 255.255.0.0
2668route del -host 192.168.3.4
2669NETSTAT.exe TCP/IP Network Statistics
2670Displays protocol statistics and current TCP/IP network connections.
2671NETSTAT [-a] [-e] [-n] [-s] [-p proto] [-r] [interval]
2672-a Displays all connections and listening ports.
2673-e Displays Ethernet statistics. This may be combined with the -s option.
2674-n Displays addresses and port numbers in numerical form.
2675-p proto Shows connections for the protocol specified by proto; proto may be TCP or UDP.
2676If used with the -s option to display per-protocol statistics, proto may be TCP, UDP,
2677or IP.
2678-r Displays the routing table.
2679-s Displays per-protocol statistics. By default, statistics are shown for TCP, UDP and IP;
2680the -p option may be used to specify a subset of the default.
2681interval Redisplays selected statistics, pausing interval seconds between each display. Press
2682CTRL+C to stop redisplaying statistics. If omitted, netstat will print the current
2683configuration information once.
2684C:\WINDOWS>netstat -a
2685Active Connections
2686Proto Local Address Foreign Address State
2687TCP My_Comp:ftp localhost:0 LISTENING
2688TCP My_Comp:80 localhost:0 LISTENING
2689Or with the "-an" parameters:
2690C:\WINDOWS>netstat -an
2691Active Connections
2692Proto Local Address Foreign Address State
2693TCP 0.0.0.0:21 0.0.0.0:0 LISTENING
2694TCP 0.0.0.0:80 0.0.0.0:0 LISTENING
2695By simply opening a browser connection to both the HTTP (port 80) and FTP (port 21) servers
2696(while still offline!), I saw the following:
2697C:\WINDOWS>netstat -a
2698Active Connections
2699Proto Local Address Foreign Address State
2700TCP My_Comp:ftp localhost:0 LISTENING
2701TCP My_Comp:80 localhost:0 LISTENING
2702TCP My_Comp:1104 localhost:0 LISTENING
2703TCP My_Comp:ftp localhost:1104 ESTABLISHED
2704TCP My_Comp:1102 localhost:0 LISTENING
2705TCP My_Comp:1103 localhost:0 LISTENING
2706TCP My_Comp:80 localhost:1111 TIME_WAIT
2707TCP My_Comp:1104 localhost:ftp ESTABLISHED
2708TCP My_Comp:1107 localhost:0 LISTENING
2709TCP My_Comp:1112 localhost:80 TIME_WAIT
2710UDP My_Comp:1102 *:*
2711UDP My_Comp:1103 *:*
2712UDP My_Comp:1107 *:*
2713This may be a bit confusing to some people, but remember I'm running BOTH the servers and clients
2714on the same machine in these examples. A little later (using both 'a' and 'n') I got this:
2715C:\WINDOWS>netstat -an
2716Active Connections
2717Proto Local Address Foreign Address State
2718TCP 0.0.0.0:21 0.0.0.0:0 LISTENING
2719TCP 0.0.0.0:80 0.0.0.0:0 LISTENING
2720TCP 0.0.0.0:1104 0.0.0.0:0 LISTENING
2721TCP 127.0.0.1:21 127.0.0.1:1104 FIN_WAIT_2
2722TCP 127.0.0.1:1102 0.0.0.0:0 LISTENING
2723TCP 127.0.0.1:1103 0.0.0.0:0 LISTENING
2724TCP 127.0.0.1:1104 127.0.0.1:21 CLOSE_WAIT
2725TCP 127.0.0.1:1107 0.0.0.0:0 LISTENING
2726UDP 127.0.0.1:1102 *:*
2727UDP 127.0.0.1:1103 *:*
2728UDP 127.0.0.1:1107 *:*
2729After turning off my server, I ended up with this for a while:
2730C:\WINDOWS>netstat -an
2731Active Connections
2732Proto Local Address Foreign Address State
2733TCP 127.0.0.1:80 127.0.0.1:1150 TIME_WAIT
2734TCP 127.0.0.1:80 127.0.0.1:1151 TIME_WAIT
2735PING.exe
2736Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
2737[-r count] [-s count] [[-j host-list] | [-k host-list]]
2738[-w timeout] destination-list
2739Options:
2740-t Ping the specifed host until interrupted.
2741-a Resolve addresses to hostnames.
2742-n count Number of echo requests to send.
2743-l size Send buffer size.
2744-f Set "Don't Fragment" flag in packet.
2745-i TTL Time To Live.
2746-v TOS Type Of Service.
2747-r count Record route for count hops.
2748-s count Timestamp for count hops.
2749-j host-list Loose source route along host-list.
2750-k host-list Strict source route along host-list.
2751-w timeout Timeout in milliseconds to wait for each reply.
2752There's one special IP number everyone should know about:
2753127.0.0.1 - localhost (or loopback).
2754This is used to connect ( through a browser, for example) to a Web server on your own computer.
2755(127 being reserved for this purpose.) You can use this IP number at all times. It doesn't matter if
2756you're connected to the Internet or not.
2757It's also called the loopback address because you can ping it and get returns even when you're
2758offline (not connected to any network). If you don't get any valid replies, then there's a problem with
2759the computer's Network settings. Here's a typical response to the 'ping' command:
2760Here's another recent example using the name of my computer which I have tied to the IP number
2761127.0.0.1 in my C:\WINDOWS\HOSTS file:
2762C:\WINDOWS>ping My_Comp
2763Pinging My_Comp [127.0.0.1] with 32 bytes of data:
2764Reply from 127.0.0.1: bytes=32 time=1ms TTL=128
2765Reply from 127.0.0.1: bytes=32 time=1ms TTL=128
2766Reply from 127.0.0.1: bytes=32 time<10ms TTL=128
2767Reply from 127.0.0.1: bytes=32 time=1ms TTL=128
2768Ping statistics for 127.0.0.1:
2769Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
2770Approximate round trip times in milli-seconds:
2771Minimum = 0ms, Maximum = 1ms, Average = 0ms
2772TRACERT.exe Trace Route
2773Usage:
2774tracert [-d] [-h maximum_hops] [-j host-list] [-w timeout] target_name
2775Options:
2776-d Do not resolve addresses to hostnames.
2777-h maximum_hops Maximum number of hops to search for target.
2778-j host-list Loose source route along host-list.
2779-w timeout Wait timeout milliseconds for each reply.
2780Here's an example which traces the route from some ISP in Los Angeles to the main server at UCLA
2781in California ( note how two computers relatively close to each other may be routed way round
2782about! ):
2783C:\WINDOWS>tracert www.ucla.edu
2784Tracing route to www.ucla.edu [169.232.33.129]
2785over a maximum of 30 hops:
27861 141 ms 132 ms 140 ms wla-ca-pm6.icg.net [165.236.29.85]
27872 134 ms 131 ms 139 ms whv-ca-gw1.icg.net [165.236.29.65]
27883 157 ms 132 ms 143 ms f3-1-0.lai-ca-gw1.icg.net [165.236.24.89]
27894 194 ms 193 ms 188 ms a0-0-0-1.dai-tx-gw1.icg.net [163.179.235.61]
27905 300 ms 211 ms 214 ms a1-1-0-1.ati-ga-gw1.icg.net [163.179.235.186]
27916 236 ms 237 ms 247 ms a5-0-0-1.was-dc-gw1.icg.net [163.179.235.129]
27927 258 ms 236 ms 244 ms 163.179.243.205
27938 231 ms 233 ms 230 ms wdc-brdr-03.inet.qwest.net [205.171.4.153]
27949 240 ms 230 ms 236 ms wdc-core-03.inet.qwest.net [205.171.24.69]
279510 262 ms 264 ms 263 ms hou-core-01.inet.qwest.net [205.171.5.187]
279611 281 ms 263 ms 259 ms hou-core-03.inet.qwest.net [205.171.23.9]
279712 272 ms 229 ms 222 ms lax-core-02.inet.qwest.net [205.171.5.163]
279813 230 ms 217 ms 230 ms lax-edge-07.inet.qwest.net [205.171.19.58]
279914 228 ms 219 ms 220 ms 63-145-160-42.cust.qwest.net [63.145.160.42]
280015 218 ms 222 ms 218 ms ISI-7507--ISI.POS.calren2.net [198.32.248.21]
280116 232 ms 222 ms 214 ms UCLA--ISI.POS.calren2.net [198.32.248.30]
280217 234 ms 226 ms 226 ms cbn5-gsr.calren2.ucla.edu [169.232.1.18]
280318 245 ms 227 ms 235 ms www.ucla.edu [169.232.33.129]
2804Trace complete.
2805Net Bios Stats
2806NBTSTAT.exe
2807Displays protocol statistics and current TCP/IP connections using NBT
2808(NetBIOS over TCP/IP).
2809NBTSTAT [-a RemoteName] [-A IP address] [-c] [-n] [-r] [-R] [-s] [S] [interval]
2810-a (adapter status) Lists the remote machine's name table given its name.
2811-A (Adapter status) Lists the remote machine's name table given its IP address.
2812-c (cache) Lists the remote name cache including the IP addresses.
2813-n (names) Lists local NetBIOS names.
2814-r (resolved) Lists names resolved by broadcast and via WINS
2815-R (Reload) Purges and reloads the remote cache name table
2816-S (Sessions) Lists sessions table with the destination IP addresses.
2817-s (sessions) Lists sessions table converting destination IP addresses to host names via the
2818hosts file.
2819RemoteName Remote host machine name.
2820IP address Dotted decimal representation of the IP address.
2821interval Redisplays selected statistics, pausing interval seconds between each display. Press
2822Ctrl+C to stop redisplaying statistics.
2823ROUTE.exe
2824Manipulates network routing tables.
2825ROUTE [-f] [command [destination] [MASK netmask] [gateway]]
2826-f Clears the routing tables of all gateway entries. If this is used in conjunction
2827with one of the commands, the tables are cleared prior to running the command.
2828command Specifies one of four commands
2829PRINT Prints a route
2830ADD Adds a route
2831DELETE Deletes a route
2832CHANGE Modifies an existing route
2833destination Specifies the host to send command.
2834MASK If the MASK keyword is present, the next parameter is interpreted as the
2835netmask parameter.
2836netmask If provided, specifies a sub-net mask value to be associated with this route entry.
2837If not specified, if defaults to 255.255.255.255.
2838gateway Specifies gateway.
2839All symbolic names used for destination or gateway are looked up in the network and host
2840name database files NETWORKS and HOSTS, respectively.
2841If the command is print or delete, wildcards may be used for the destination and gateway, or
2842the gateway argument may be omitted.
2843ARP.exe Address Resolution Protocol
2844ARP -s inet_addr eth_addr [if_addr]
2845ARP -d inet_addr [if_addr]
2846ARP -a [inet_addr] [-N if_addr]
2847-a Displays current ARP entries by interrogating the current protocol data. If inet_addr
2848is specified, the IP and Physical addresses for only the specified computer are
2849displayed. If more than one network interface uses ARP, entries for each ARP
2850table are displayed.
2851-g (Same as -a)
2852inet_addr Specifies an internet address.
2853-N if_addr Displays the ARP entries for the network interface specified by if_addr.
2854-d Deletes the host specified by inet_addr.
2855-s Adds the host and associates the Internet address inet_addr with the Physical address
2856eth_addr. The Physical address is given as 6 hexadecimal bytes separated by hyphens.
2857The entry is permanent.
2858eth_addr Specifies a physical address.
2859if_addr If present, this specifies the Internet address of the interface
2860whose address translation table should be modified. If not present, the first
2861applicable interface will be used