· 9 years ago · Feb 27, 2017, 08:30 AM
11.WAJP to display server date and time in client
2Server:
3import java.io.*;
4import java.net.*;
5import java.util.Date;
6class server1 {
7public static void main(String argv[]) throws Exception
8{
9String capitalizedSentence;
10ServerSocket welcomeSocket = new ServerSocket(6789);
11while(true) {
12Socket connectionSocket = welcomeSocket.accept();
13DataOutputStream outToClient = new
14DataOutputStream(connectionSocket.getOutputStream());
15capitalizedSentence = new Date().toString() + '\n';
16outToClient.writeBytes(capitalizedSentence);
17}
18}
19}
20Client:
21import java.io.*;
22import java.net.*;
23class client1 {
24public static void main(String argv[]) throws Exception
25{
26String modifiedSentence;
27Socket clientSocket = new Socket("localhost", 6789);
28BufferedReader inFromServer = new BufferedReader(new
29InputStreamReader(clientSocket.getInputStream()));
30modifiedSentence = inFromServer.readLine();
31System.out.println("FROM SERVER: " + modifiedSentence);
32clientSocket.close();
33}
34}
352.WAJP to display client address in server
36Server:
37import java.io.*;
38import java.net.*;
39class server1 {
40public static void main(String argv[]) throws Exception
41{
42ServerSocket welcomeSocket = new ServerSocket(6789);
43while(true) {
44Socket connectionSocket = welcomeSocket.accept();
45BufferedReader inFromClient = new BufferedReader(new
46InputStreamReader(connectionSocket.getInputStream()));
47System.out.println("Address Received from client : "+ inFromClient.readLine());
48}
49}
50}
51Client:
52import java.io.*;
53import java.net.*;
54class client1 {
55public static void main(String argv[]) throws Exception
56{
57Socket clientSocket = new Socket("localhost", 6789);
58DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
59outToServer.writeBytes(InetAddress.getLocalHost().getHostAddress() + '\n');
60clientSocket.close();
61}
62}
634.WAJP for chat
64SERVER
65import java.io.*;
66import java.net.*;
67import java.util.*;
68class Server
69{
70public static void main(String[] args)throws IOException
71{
72ServerSocket sr=new ServerSocket(6789);
73while(true)
74{
75Socket cons=sr.accept();
76BufferedReader incl=new BufferedReader(new InputStreamReader(cons.getInputStream()));
77OutputStream outcl=cons.getOutputStream();
78PrintWriter pw=new PrintWriter(outcl,true);
79BufferedReader serin=new BufferedReader(new InputStreamReader(System.in));
80String str=" ",str1=" ";
81try
82{
83while( (str=incl.readLine())!=null)
84{
85System.out.println("Client:"+str);
86str1=serin.readLine();
87System.out.println("You:"+str1);
88pw.println(str1);
89}
90}
91catch(SocketException e)
92{
93System.out.println(e);
94}
95}
96}
97}
98CLIENT
99import java.io.*;
100import java.net.*;
101class Client
102{
103public static void main(String[] args)throws IOException
104{
105String str=" ",str1=" ";
106int i=0;
107Socket cls=new Socket("localhost",6789);
108BufferedReader inser=new BufferedReader(new InputStreamReader(cls.getInputStream()));
109OutputStream outser=cls.getOutputStream();
110PrintWriter pw=new PrintWriter(outser,true);
111BufferedReader clin=new BufferedReader(new InputStreamReader(System.in));
112System.out.println("Begin chat");
113str1=clin.readLine();
114System.out.println("You:"+str1);
115pw.println(str1);
116try
117{
118while( (str=inser.readLine())!=null)
119{
120System.out.println("Server:"+str);
121str1=clin.readLine();
122System.out.println("You:"+str1);
123pw.println(str1);
124}
125}
126catch(SocketException e)
127{
128System.out.println(e);
129}//catch
130}
131}
1325.TCP/IP
133server:
134import java.io.*;
135import java.net.*;
136class server1 {
137public static void main(String argv[]) throws Exception {
138String clientSentence;
139ServerSocket welcomeSocket = new ServerSocket(6789);
140while (true) {
141Socket connectionSocket = welcomeSocket.accept();
142BufferedReader inFromClient
143= new BufferedReader(new
144InputStreamReader(connectionSocket.getInputStream()));
145DataOutputStream outToClient
146= new DataOutputStream(connectionSocket.getOutputStream());
147clientSentence = inFromClient.readLine();
148System.out.println("Received from client : " + clientSentence);
149String a = clientSentence.toLowerCase();
150String b = "";//abc
151String x = "abcdefghijklmnopqrstuvwxyz";
152//code to encode
153for (int i = 0; i < a.length(); i++) {
154if (a.charAt(i) == 'z') {
155b += 'a';
156} else {
157for (int j = 0; j < x.length(); j++) {
158if (x.charAt(j) == a.charAt(i)) {
159b += x.charAt(j + 1);
160break;
161}
162}
163}
164}
165outToClient.writeBytes(b+"\n");
166}
167}
168}
169client:
170import java.io.*;
171import java.net.*;
172class client1 {
173public static void main(String argv[]) throws Exception {
174String sentence;
175String modifiedSentence;
176BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
177Socket clientSocket = new Socket("localhost", 6789);
178DataOutputStream outToServer = new
179DataOutputStream(clientSocket.getOutputStream());
180BufferedReader inFromServer = new BufferedReader(new
181InputStreamReader(clientSocket.getInputStream()));
182sentence = inFromUser.readLine();
183outToServer.writeBytes(sentence + '\n');
184modifiedSentence = inFromServer.readLine();
185System.out.println("FROM SERVER: " + modifiedSentence);
186clientSocket.close();
187}
188}
1897.WAJP to display name and address of computer currently working on
190import java.net.InetAddress;
191public class pro1 {
192public static void main(String []args) throws Exception{
193InetAddress a=InetAddress.getLocalHost();
194System.out.println(a);
195}
196}
1978.IPv4 header
1989.Threads
199import java.util.*;
200/**
201*
202* @author mock3
203*/
204class waste extends Thread {
205int a;
206public void run() {
207try {
208Random r = new Random();
209int r1= r.nextInt(1000);
210if(Thread.currentThread().isDaemon()){
211for (a = 0; a < 4; a++) {
212System.out.println(a + " daemon");
213Thread.sleep(r1);
214}
215}
216else{
217for (a = 0; a < 4; a++) {
218System.out.println(a + " haha");
219Thread.sleep(r1);
220}
221}
222} catch (Exception e) {
223}
224}
225}
226public class JavaApplication2 {
227/**
228* @param args the command line arguments
229*/
230public static void main(String[] args) throws Exception {
231// TODO code application logic here
232waste w1 = new waste();
233w1.setDaemon(true);
234waste w2 = new waste();
235waste w3 = new waste();
236w1.start();
237w2.start();
238w3.start();
239}
240}
24110.WAJP to run basic network commands
242import java.net.*;
243import java.util.*;
244import java.io.*;
245public class command
246{
247public static void main(String args[])
248throws Exception
249{
250BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
251System.out.println("enter command:");
252String s=br.readLine();
253Process p=Runtime.getRuntime().exec(s);
254p.waitFor();
255BufferedReader reader=new BufferedReader(new
256InputStreamReader(p.getInputStream()));
257String line=reader.readLine();
258while(line!=null)
259{
260System.out.println(line);
261line=reader.readLine();0
262}
263System.out.println("done!");
264}
265}
266
267
2681.WAJP to display server date and time in client
269
270Server:
271
272import java.io.*;
273import java.net.*;
274import java.util.Date;
275class server1 {
276 public static void main(String argv[]) throws Exception
277 {
278 String capitalizedSentence;
279 ServerSocket welcomeSocket = new ServerSocket(6789);
280 while(true) {
281 Socket connectionSocket = welcomeSocket.accept();
282DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
283 capitalizedSentence = new Date().toString() + '\n';
284 outToClient.writeBytes(capitalizedSentence);
285 }
286 }
287}
288
289
290Client:
291
292import java.io.*;
293import java.net.*;
294class client1 {
295 public static void main(String argv[]) throws Exception
296 {
297 String modifiedSentence;
298 Socket clientSocket = new Socket("localhost", 6789);
299BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
300 modifiedSentence = inFromServer.readLine();
301 System.out.println("FROM SERVER: " + modifiedSentence);
302 clientSocket.close();
303 }
304}
305
306
307
308
3092.WAJP to display client address in server
310Server:
311
312import java.io.*;
313import java.net.*;
314
315class server1 {
316 public static void main(String argv[]) throws Exception
317 {
318 ServerSocket welcomeSocket = new ServerSocket(6789);
319 while(true) {
320 Socket connectionSocket = welcomeSocket.accept();
321 BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
322System.out.println("Address Received from client : "+ inFromClient.readLine());
323 }
324 }
325}
326
327
328Client:
329
330import java.io.*;
331import java.net.*;
332class client1 {
333 public static void main(String argv[]) throws Exception
334 {
335 Socket clientSocket = new Socket("localhost", 6789);
336DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
337 outToServer.writeBytes(InetAddress.getLocalHost().getHostAddress() + '\n');
338 clientSocket.close();
339
340 }
341}
342
343
344
3454.WAJP for chat
346SERVER
347import java.io.*;
348import java.net.*;
349import java.util.*;
350class Server
351{
352public static void main(String[] args)throws IOException
353{
354ServerSocket sr=new ServerSocket(6789);
355while(true)
356{
357Socket cons=sr.accept();
358BufferedReader incl=new BufferedReader(new InputStreamReader(cons.getInputStream()));
359OutputStream outcl=cons.getOutputStream();
360PrintWriter pw=new PrintWriter(outcl,true);
361BufferedReader serin=new BufferedReader(new InputStreamReader(System.in));
362String str=" ",str1=" ";
363try
364{
365while( (str=incl.readLine())!=null)
366{
367System.out.println("Client:"+str);
368str1=serin.readLine();
369System.out.println("You:"+str1);
370pw.println(str1);
371}
372}
373catch(SocketException e)
374{
375System.out.println(e);
376}
377}
378}
379}
380
381CLIENT
382import java.io.*;
383import java.net.*;
384
385class Client
386{
387public static void main(String[] args)throws IOException
388{
389String str=" ",str1=" ";
390int i=0;
391Socket cls=new Socket("localhost",6789);
392BufferedReader inser=new BufferedReader(new InputStreamReader(cls.getInputStream()));
393OutputStream outser=cls.getOutputStream();
394PrintWriter pw=new PrintWriter(outser,true);
395BufferedReader clin=new BufferedReader(new InputStreamReader(System.in));
396System.out.println("Begin chat");
397str1=clin.readLine();
398System.out.println("You:"+str1);
399pw.println(str1);
400try
401{
402while( (str=inser.readLine())!=null)
403{
404System.out.println("Server:"+str);
405str1=clin.readLine();
406System.out.println("You:"+str1);
407pw.println(str1);
408}
409}
410catch(SocketException e)
411{
412System.out.println(e);
413}//catch
414
415}
416}
417
418
4195.TCP/IP
420server:
421
422import java.io.*;
423import java.net.*;
424
425class server1 {
426
427 public static void main(String argv[]) throws Exception {
428 String clientSentence;
429 ServerSocket welcomeSocket = new ServerSocket(6789);
430 while (true) {
431 Socket connectionSocket = welcomeSocket.accept();
432 BufferedReader inFromClient
433 = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
434 DataOutputStream outToClient
435 = new DataOutputStream(connectionSocket.getOutputStream());
436 clientSentence = inFromClient.readLine();
437 System.out.println("Received from client : " + clientSentence);
438 String a = clientSentence.toLowerCase();
439 String b = "";//abc
440 String x = "abcdefghijklmnopqrstuvwxyz";
441//code to encode
442 for (int i = 0; i < a.length(); i++) {
443 if (a.charAt(i) == 'z') {
444 b += 'a';
445 } else {
446 for (int j = 0; j < x.length(); j++) {
447 if (x.charAt(j) == a.charAt(i)) {
448 b += x.charAt(j + 1);
449 break;
450 }
451 }
452 }
453 }
454 outToClient.writeBytes(b+"\n");
455 }
456 }
457}
458
459client:
460
461import java.io.*;
462import java.net.*;
463class client1 {
464 public static void main(String argv[]) throws Exception {
465 String sentence;
466 String modifiedSentence;
467 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
468 Socket clientSocket = new Socket("localhost", 6789);
469 DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
470 BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
471 sentence = inFromUser.readLine();
472 outToServer.writeBytes(sentence + '\n');
473
474 modifiedSentence = inFromServer.readLine();
475
476 System.out.println("FROM SERVER: " + modifiedSentence);
477
478 clientSocket.close();
479
480 }
481}
482
4837.WAJP to display name and address of computer currently working on
484import java.net.InetAddress;
485public class pro1 {
486 public static void main(String []args) throws Exception{
487 InetAddress a=InetAddress.getLocalHost();
488 System.out.println(a);
489 }
490}
491
4928.IPv4 header
493
494
4959.Threads
496import java.util.*;
497/**
498 *
499 * @author mock3
500 */
501class waste extends Thread {
502
503 int a;
504
505 public void run() {
506 try {
507 Random r = new Random();
508 int r1= r.nextInt(1000);
509 if(Thread.currentThread().isDaemon()){
510 for (a = 0; a < 4; a++) {
511 System.out.println(a + " daemon");
512 Thread.sleep(r1);
513 }
514 }
515 else{
516 for (a = 0; a < 4; a++) {
517 System.out.println(a + " haha");
518 Thread.sleep(r1);
519 }
520 }
521 } catch (Exception e) {
522
523 }
524 }
525}
526
527public class JavaApplication2 {
528
529 /**
530 * @param args the command line arguments
531 */
532 public static void main(String[] args) throws Exception {
533 // TODO code application logic here
534 waste w1 = new waste();
535 w1.setDaemon(true);
536 waste w2 = new waste();
537 waste w3 = new waste();
538 w1.start();
539 w2.start();
540 w3.start();
541 }
542
543}
544
54510.WAJP to run basic network commands
546import java.net.*;
547import java.util.*;
548import java.io.*;
549public class command
550{
551 public static void main(String args[])
552 throws Exception
553 {
554 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
555 System.out.println("enter command:");
556 String s=br.readLine();
557 Process p=Runtime.getRuntime().exec(s);
558 p.waitFor();
559 BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
560 String line=reader.readLine();
561 while(line!=null)
562 {
563 System.out.println(line);
564 line=reader.readLine();0
565 }
566 System.out.println("done!");
567
568}
569}
570
571
572
573
574Cyclesheet 1
575
576
5772) Write a Java program to run the basic networking commands
578
579import java.net.*;
580import java.util.*;
581import java.io.*;
582public class command
583{
584 public static void main(String args[])
585 throws Exception
586 {
587 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
588 System.out.println("enter command:");
589 String s=br.readLine();
590 Process p=Runtime.getRuntime().exec(s);
591 p.waitFor();
592 BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
593 String line=reader.readLine();
594 while(line!=null)
595 {
596 System.out.println(line);
597 line=reader.readLine();0
598 }
599 System.out.println("done!");
600
601}
602}
603
6043) Write a program to display the name of the computer and its IP address that you are currently working on.
605
606import java.net.*;
607import java.io.*;
608public class cm
609{
610public static void main(String args[])
611{
612try
613{
614BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
615System.out.println("Enter the url which you want to find ip address and host name");
616String str=br.readLine();
617InetAddress add=InetAddress.getByName(str);
618System.out.println("Local Host Information");
619System.out.println("Host Name:"+add.getHostName());
620System.out.println("IP address:"+add.getHostAddress());
621}
622catch(Exception e)
623{
624System.out.println(e);
625}
626}
627
628
6294) Write a program to print the IP address of www.google.com all IP addresses of www.microsoft.com.
630import java.net.*;
631import java.io.*;
632public class ip
633{
634public static void main(String args[])
635throws UnknownHostException {
636 System.out.println(InetAddress.getByName("www.google.com"));
637 InetAddress[] inetAddresses=InetAddress.getAllByName("www.microsoft.com");
638 for(InetAddress ipAddress:inetAddresses)
639 {
640 System.out.println(ipAddress);
641 }
642}
643}
644
6455) Write a program to print all Network Interfaces of localhost.
646
647import java.net.*;
648import java.util.*;
649import java.io.*;
650public class ni
651{
652public static void main(String args[]) throws UnknownHostException,SocketException
653{
654
655 Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
656if(interfaces==null)
657{
658System.out.println("No network interfaces found");
659}
660else
661{
662for(NetworkInterface netIf:Collections.list(interfaces))
663{
664System.out.println("Display Name:" + netIf.getDisplayName());
665System.out.println("Name : " + netIf.getName());
666System.out.println();
667}
668}
669}
670}
671
672
6736) Implement the simple version of nslookup utility.
674
675import java.net.*;
676import java.io.*;
677import java.util.*;
678public class nslook
679{
680public static void main(String args[]) throws Exception
681{
682 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
683 System.out.println("Enter the hostname");
684 String cmd=br.readLine();
685 Process p=Runtime.getRuntime().exec("nslookup "+cmd);
686 p.waitFor();
687 BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
688 String line=reader.readLine();
689 while(line!=null)
690 {
691 System.out.println(line);
692 line=reader.readLine();
693 }
694 System.out.println("Done");
695}
696}
697
6987) Write a program to download the contents associated with a HTTP URL and save it in a file.
699
700import java.io.*;
701 import java.net.*;
702 public class GetJavaUrl
703 {
704 public static void main(String[] args)
705 {
706 URL u;
707 InputStream is=null;
708 DataInputStream dis;
709 String s;
710 try
711 {
712 u=new URL("ftp://10.30.2.53");
713 is=u.openStream();
714 dis = new DataInputStream(new BufferedInputStream(is));
715 while((s=dis.readLine())!=null)
716 {
717 System.out.println(s);
718 }
719 }
720 catch(MalformedURLException mue)
721 {
722 System.out.println("404: Error NOT FOUND");
723 mue.printStackTrace();
724 System.exit(1);
725 }
726 catch(IOException ioe)
727 {
728 System.out.println("404: Error NOT FOUND");
729 ioe.printStackTrace();
730 System.exit(1);
731 }
732 finally
733 {
734 try
735 {
736 is.close();
737 }
738 catch(IOException ioe)
739 {
740 }
741 }
742 }
743
744}
745
746ITE 304 Computer Networks Lab
747
748Cycle sheet-2
749
750
751
7521. Write a program to list all ports hosting a TCP server in a specified host and identify available servers in well-known ports?
753
7542. Implement echo server and client in java using TCP sockets.
755
7563. Implement date server and client in java using TCP sockets.
757
7584. Write a program to implement a simple message transfer from client to server process using TCP/IP.
759
7605. Develop a TCP client/server application for transferring a text file from client to server?
761
7626. Implement a chat server and client in java using TCP sockets.
763
7647. Implement a TCP based server program to authenticate the clients 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.
765
7668. Find the physical address of a host when its logical address is known (ARP protocol) using TCP/IP.
767
7689. Find the logical address of a host when its physical address is known (RARP protocol) using TCP/IP.
769
77010. Implement Domain Name System (DNS) using TCP/IP
771
77211. 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.
773
77412. Find the class of the IP address using TCP/IP.
775
776
777Solutions
778
779Q1 Write a program to list all ports hosting a TCP server in a specified host and identify available servers in well-known ports?
780
781import java.net.Socket;
782import java.net.*;
783
784public class A {
785public static void main(String[] args) throws Exception{
786 try {
787 for(int i=0;i<1024;i++)
788 {
789 Socket s=new Socket("localhost",i);
790 System.out.println(i);
791 }
792 }
793 catch(Exception e)
794 {
795 System.out.println(e);
796 }
797}
798}
799
800Q2 Implement echo server and client in java using TCP sockets.
801
802
803server
804
805import java.io.*;
806
807import java.net.*;
808
809
810
811public class EchoServer
812
813{
814
815public static void main(String args[]) throws Exception
816
817{
818
819try
820
821{
822
823int Port;
824
825BufferedReader Buf =new BufferedReader(new
826
827InputStreamReader(System.in));
828
829System.out.print(" Enter the Port Address : " );
830
831Port=Integer.parseInt(Buf.readLine());
832
833ServerSocket sok =new ServerSocket(Port);
834
835System.out.println(" Server is Ready To Receive a Message. ");
836
837System.out.println(" Waiting ..... ");
838
839Socket so=sok.accept();
840
841if(so.isConnected()==true)
842
843 System.out.println(" Client Socket is Connected Succecfully. ");
844
845InputStream in=so.getInputStream();
846
847OutputStream ou=so.getOutputStream();
848
849PrintWriter pr=new PrintWriter(ou);
850
851BufferedReader buf=new BufferedReader(new
852
853InputStreamReader(in));
854
855String str=buf.readLine();
856
857System.out.println(" Message Received From Client : " + str);
858
859System.out.println(" This Message is Forwarded To Client. ");
860
861pr.println(str);
862
863pr.flush();
864
865}
866
867 catch(Exception e)
868
869 {
870
871 System.out.println(" Error : " + e.getMessage());
872
873 }
874
875}
876
877}
878
879
880
881client
882
883import java.io.*;
884
885import java.net.*;
886
887
888
889public class EchoClient
890
891{
892
893public static void main(String args[]) throws Exception
894
895{
896
897try {
898
899int Port;
900
901BufferedReader Buf =new BufferedReader(new
902
903InputStreamReader(System.in));
904
905System.out.print(" Enter the Port Address : " );
906
907Port=Integer.parseInt(Buf.readLine());
908
909Socket sok=new Socket("localhost",Port);
910
911if(sok.isConnected()==true)
912
913 System.out.println(" Server Socket is Connected Succecfully. ");
914
915InputStream in=sok.getInputStream();
916
917OutputStream ou=sok.getOutputStream();
918
919PrintWriter pr=new PrintWriter(ou);
920
921BufferedReader buf1=new BufferedReader(new
922
923InputStreamReader(System.in));
924
925
926BufferedReader buf2=new BufferedReader(new
927
928InputStreamReader(in));
929
930String str1,str2;
931
932System.out.print(" Enter the Message : ");
933
934str1=buf1.readLine();
935
936pr.println(str1);
937
938pr.flush();
939
940System.out.println(" Message Send Successfully. ");
941
942str2=buf2.readLine();
943
944System.out.println(" Message From Server : " + str2);
945
946 }
947
948 catch(Exception e)
949
950 {
951
952 System.out.println(" Error : " + e.getMessage());
953
954 }
955
956}
957
958}
959Q3 Implement date server and client in java using TCP sockets.
960
961client
962
963import java.io.*;
964
965import java.net.*;
966
967
968
969class DateClient
970
971{
972
973 public static void main(String args[]) throws Exception
974
975 {
976
977 Socket soc=new Socket(InetAddress.getLocalHost(),5217);
978
979 BufferedReader in=new BufferedReader(new InputStreamReader( soc.getInputStream() ) );
980
981 System.out.println(in.readLine());
982
983 }
984
985}
986
987
988
989server
990
991import java.net.*;
992
993import java.io.*;
994
995import java.util.*;
996
997
998
999class DateServer
1000
1001{
1002
1003 public static void main(String args[]) throws Exception
1004
1005 {
1006
1007 ServerSocket s=new ServerSocket(5217);
1008 while(true)
1009
1010 {
1011
1012 System.out.println("Waiting For Connection ...");
1013
1014 Socket soc=s.accept();
1015
1016 DataOutputStream out=new DataOutputStream(soc.getOutputStream());
1017
1018 out.writeBytes("Server Date" + (new Date()).toString() + "\n");
1019
1020 out.close();
1021
1022 soc.close();
1023
1024 }
1025
1026
1027
1028 }
1029
1030}
1031
1032
1033Q4 , Q6 Write a program to implement a simple message transfer from client to server process using TCP/IP.
1034SERVER
1035
1036import java.io.*;
1037import java.io.BufferedReader;
1038import java.io.InputStream;
1039import java.io.InputStreamReader;
1040import java.io.OutputStream;
1041import java.io.PrintWriter;
1042import java.net.*;
1043public class GossipServer
1044{
1045 public static void main(String[] args) throws Exception
1046 {
1047 ServerSocket sersock = new ServerSocket(3000);
1048 System.out.println("Server ready for chatting");
1049 Socket sock = sersock.accept( );
1050 // reading from keyboard (keyRead object)
1051 BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
1052 // sending to client (pwrite object)
1053 OutputStream ostream = sock.getOutputStream();
1054 PrintWriter pwrite = new PrintWriter(ostream, true);
1055
1056 // receiving from server ( receiveRead object)
1057 InputStream istream = sock.getInputStream();
1058 BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
1059
1060 String receiveMessage, sendMessage;
1061 while(true)
1062 {
1063 if((receiveMessage = receiveRead.readLine()) != null)
1064 {
1065 System.out.println(receiveMessage);
1066 }
1067 sendMessage = keyRead.readLine();
1068 pwrite.println(sendMessage);
1069 pwrite.flush();
1070 }
1071 }
1072}
1073
1074
10755 Develop a TCP client/server application for transferring a text file from client to server?
1076Server:
1077import java.io.BufferedInputStream;
1078import java.io.File;
1079import java.io.FileInputStream;
1080import java.io.OutputStream;
1081import java.net.InetAddress;
1082import java.net.ServerSocket;
1083import java.net.Socket;
1084
1085public class FileTransferServer {
1086
1087 public static void main(String[] args) throws Exception {
1088 //Initialize Sockets
1089 ServerSocket ssock = new ServerSocket(5000);
1090 Socket socket = ssock.accept();
1091
1092 //The InetAddress specification
1093 InetAddress IA = InetAddress.getByName("localhost");
1094
1095 //Specify the file
1096 File file = new File("/home/likewise-open/VITUNIVERSITY/14bit0297/DateServer.java");
1097 FileInputStream fis = new FileInputStream(file);
1098 BufferedInputStream bis = new BufferedInputStream(fis);
1099
1100 //Get socket's output stream
1101 OutputStream os = socket.getOutputStream();
1102
1103 //Read File Contents into contents array
1104 byte[] contents;
1105 long fileLength = file.length();
1106 long current = 0;
1107
1108 long start = System.nanoTime();
1109 while(current!=fileLength){
1110 int size = 10000;
1111 if(fileLength - current >= size)
1112 current += size;
1113 else{
1114 size = (int)(fileLength - current);
1115 current = fileLength;
1116 }
1117 contents = new byte[size];
1118 bis.read(contents, 0, size);
1119 os.write(contents);
1120 System.out.print("Sending file ... "+(current*100)/fileLength+"% complete!");
1121 }
1122
1123 os.flush();
1124 //File transfer done. Close the socket connection!
1125 socket.close();
1126 ssock.close();
1127 System.out.println("File sent succesfully!");
1128 }
1129}
1130
1131Client:
1132import java.io.BufferedOutputStream;
1133import java.io.FileOutputStream;
1134import java.io.InputStream;
1135import java.net.InetAddress;
1136import java.net.Socket;
1137
1138
1139public class FileTransferClient {
1140
1141 public static void main(String[] args) throws Exception{
1142
1143 //Initialize socket
1144 Socket socket = new Socket(InetAddress.getByName("localhost"), 5000);
1145 byte[] contents = new byte[10000];
1146
1147 //Initialize the FileOutputStream to the output file's full path.
1148 FileOutputStream fos = new FileOutputStream("e:\\data2.bin");
1149 BufferedOutputStream bos = new BufferedOutputStream(fos);
1150 InputStream is = socket.getInputStream();
1151
1152 //No of bytes read in one read() call
1153 int bytesRead = 0;
1154
1155 while((bytesRead=is.read(contents))!=-1)
1156 bos.write(contents, 0, bytesRead);
1157
1158 bos.flush();
1159 socket.close();
1160
1161 System.out.println("File saved successfully!");
1162 }
1163}
1164OUTPUT
1165
1166
1167CLINET
1168
1169import java.io.*;
1170import java.net.*;
1171public class GossipClient
1172{
1173 public static void main(String[] args) throws Exception
1174 {
1175 Socket sock = new Socket("127.0.0.1", 3000);
1176 // reading from keyboard (keyRead object)
1177 BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
1178 // sending to client (pwrite object)
1179 OutputStream ostream = sock.getOutputStream();
1180 PrintWriter pwrite = new PrintWriter(ostream, true);
1181
1182 // receiving from server ( receiveRead object)
1183 InputStream istream = sock.getInputStream();
1184 BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
1185
1186 System.out.println("Start the chitchat, type and press Enter key");
1187
1188 String receiveMessage, sendMessage;
1189 while(true)
1190 {
1191 sendMessage = keyRead.readLine(); // keyboard reading
1192 pwrite.println(sendMessage); // sending to server
1193 pwrite.flush(); // flush the data
1194 if((receiveMessage = receiveRead.readLine()) != null) //receive from server
1195 {
1196 System.out.println(receiveMessage); // displaying at DOS prompt
1197 }
1198 }
1199 }
1200}
1201Q7 Implement a TCP based server program to authenticate the clients 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.
1202
1203
1204CLIENT
1205
1206import java.io.*;
1207import java.net.*;
1208class TCPClientAuth {
1209
1210 public static void main(String argv[]) throws Exception
1211 {
1212 String username;
1213 String password;
1214 String auth;
1215
1216 BufferedReader inFromUser =
1217 new BufferedReader(new InputStreamReader(System.in));
1218
1219 Socket clientSocket = new Socket("localhost", 6789);
1220
1221 DataOutputStream outToServer =
1222 new DataOutputStream(clientSocket.getOutputStream());
1223
1224 BufferedReader inFromServer =
1225 new BufferedReader(new
1226 InputStreamReader(clientSocket.getInputStream()));
1227
1228 System.out.print("Username :");
1229 username = inFromUser.readLine();
1230
1231 System.out.print("Password :");
1232 password = inFromUser.readLine();
1233
1234
1235 outToServer.writeBytes(username + '\n' + password + '\n' );
1236
1237 auth = inFromServer.readLine();
1238
1239 System.out.println("FROM SERVER: " + auth);
1240
1241 clientSocket.close();
1242
1243 }
1244}
1245
1246SERVER
1247
1248
1249import java.io.*;
1250import java.net.*;
1251
1252class TCPServerAuth {
1253
1254 public static void main(String argv[]) throws Exception
1255 {
1256 String username;
1257 String password;
1258 String auth;
1259
1260 ServerSocket welcomeSocket = new ServerSocket(6789);
1261
1262 while(true) {
1263
1264 Socket connectionSocket = welcomeSocket.accept();
1265
1266 BufferedReader inFromClient =
1267 new BufferedReader(new
1268 InputStreamReader(connectionSocket.getInputStream()));
1269
1270
1271
1272 DataOutputStream outToClient =
1273 new DataOutputStream(connectionSocket.getOutputStream());
1274
1275 username = inFromClient.readLine();
1276 password = inFromClient.readLine();
1277
1278
1279 if (username.equals("Admin")){
1280 if (password.equals("root")){
1281 auth = "Login Successful!";
1282 }else{
1283 auth = "Wrong Password";
1284 }
1285 }else{
1286 auth = "Wrong Username";
1287 }
1288
1289 outToClient.writeBytes(auth);
1290 connectionSocket.close();
1291 }
1292 }
1293}
1294
1295Q8.Find the physical address of a host when its logical address is known (ARP protocol) using TCP/IP.
1296
1297CLIENT:
1298import java.io.*;
1299import java.util.*;
1300import java.net.*;
1301
1302public class q8client
1303{
1304public static void main(String[] args)
1305{
1306try
1307{
1308Socket s = new Socket("localhost",5555);
1309BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
1310DataOutputStream dout = new DataOutputStream(s.getOutputStream());
1311DataInputStream din = new DataInputStream(s.getInputStream());
1312System.out.println("Enter the logical address: ");
1313String str = b.readLine();
1314dout.writeBytes(str + "\n");
1315String str1 = din.readLine();
1316System.out.println("Physical Address of str: " + str1);
1317s.close();
1318}
1319catch (Exception e)
1320{
1321}
1322}}
1323
1324SERVER:
1325
1326import java.io.*;
1327import java.util.*;
1328import java.net.*;
1329
1330public class q8server
1331{
1332public static void main(String[] args)
1333{
1334try
1335{
1336ServerSocket ss = new ServerSocket(5555);
1337Socket s = ss.accept();
1338BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
1339DataOutputStream dout = new DataOutputStream(s.getOutputStream());
1340DataInputStream din = new DataInputStream(s.getInputStream());
1341String str = din.readLine();
1342String logical[] = {"172.16.27.34","195.24.54.204"};
1343String physical[] = {"8E:AE:08:AA","0A:78:6C:AD"};
1344for(int i=0;i<logical.length;i++)
1345{
1346if (str.equals(logical[i]))
1347{
1348dout.writeBytes(physical[i] + "\n");
1349break;
1350}
1351}
1352s.close();
1353}
1354catch (Exception e)
1355{
1356}
1357}
1358}
1359
1360
1361OUTPUT:
1362
1363
1364=====================================================
1365
1366
1367
1368
1369Q9.Find the logical address of a host when its physical address is known (RARP protocol) using TCP/IP.
1370
1371CLIENT:
1372import java.io.*;
1373import java.net.*;
1374class TCPLogClient {
1375
1376 public static void main(String argv[]) throws Exception
1377 {
1378 String logicAdd;
1379 String phyAdd;
1380
1381 BufferedReader inFromUser =
1382 new BufferedReader(new InputStreamReader(System.in));
1383
1384 Socket clientSocket = new Socket("localhost", 6789);
1385
1386 DataOutputStream outToServer =
1387 new DataOutputStream(clientSocket.getOutputStream());
1388
1389 BufferedReader inFromServer =
1390 new BufferedReader(new
1391 InputStreamReader(clientSocket.getInputStream()));
1392
1393 System.out.println("Enter Physical address of host");
1394 phyAdd = inFromUser.readLine();
1395
1396 outToServer.writeBytes(phyAdd + '\n');
1397
1398 logicAdd = inFromServer.readLine();
1399
1400 System.out.println("FROM SERVER: Logical Address " + logicAdd);
1401
1402 clientSocket.close();
1403
1404 }
1405}
1406
1407SERVER:
1408import java.io.*;
1409import java.net.*;
1410
1411class TCPLogServer {
1412
1413 public static void main(String argv[]) throws Exception
1414 {
1415 String phyAdd;
1416
1417
1418 ServerSocket welcomeSocket = new ServerSocket(6789);
1419
1420 while(true) {
1421
1422 Socket connectionSocket = welcomeSocket.accept();
1423
1424 BufferedReader inFromClient =
1425 new BufferedReader(new
1426 InputStreamReader(connectionSocket.getInputStream()));
1427
1428
1429 String logical[] = {"172.16.27.34","195.24.54.204", "10.10.137.1"};
1430 String physical[] = {"8E:AE:08:AA","0A:78:6C:AD", "d4:6d:50:84:db:c8"};
1431
1432 DataOutputStream outToClient =
1433 new DataOutputStream(connectionSocket.getOutputStream());
1434
1435 phyAdd = inFromClient.readLine();
1436 for(int i = 0; i < physical.length; i++)
1437 {
1438 if (phyAdd.equals(physical[i]))
1439 {
1440 outToClient.writeBytes(logical[i] + "\n");
1441 connectionSocket.close();
1442 }
1443 }
1444
1445
1446 }
1447 }
1448}
1449
1450=======================================
1451
1452
145310.Implement Domain Name System (DNS) using TCP/IP
1454
1455SERVER:
1456import java.io.*;
1457import java.net.*;
1458class TCPLoServer {
1459 public static void main(String argv[]) throws Exception
1460 {
1461 String D;
1462 ServerSocket welcomeSocket = new ServerSocket(6789);
1463 while(true) {
1464 Socket connectionSocket = welcomeSocket.accept();
1465BufferedReader inFromClient =
1466 new BufferedReader(new
1467 InputStreamReader(connectionSocket.getInputStream()));
1468String hostaddr[] = {"172.16.27.34","195.24.54.204", "10.10.137.1"};
1469 String DNS[] = {"www.google.com","www.facebook.com", "www.vit.ac.in"};
1470 DataOutputStream outToClient =
1471 new DataOutputStream(connectionSocket.getOutputStream());
1472 D = inFromClient.readLine();
1473for(int i = 0; i < hostaddr.length; i++)
1474 {
1475 if (D.equals(hostaddr[i]))
1476 {
1477 outToClient.writeBytes(DNS[i] + "\n");
1478 connectionSocket.close();
1479 }
1480 }
1481
1482
1483 }
1484 }
1485}
1486
1487
1488
1489CLIENT:
1490import java.io.*;
1491import java.net.*;
1492class TCPLoClient {
1493
1494 public static void main(String argv[]) throws Exception
1495 {
1496 String hostaddr;
1497 String DNS;
1498
1499 BufferedReader inFromUser =
1500 new BufferedReader(new InputStreamReader(System.in));
1501
1502 Socket clientSocket = new Socket("localhost", 6789);
1503
1504 DataOutputStream outToServer =
1505 new DataOutputStream(clientSocket.getOutputStream());
1506
1507 BufferedReader inFromServer =
1508 new BufferedReader(new
1509 InputStreamReader(clientSocket.getInputStream()));
1510
1511 System.out.println("Enter IP address of host");
1512 DNS = inFromUser.readLine();
1513
1514 outToServer.writeBytes(DNS + '\n');
1515
1516 hostaddr = inFromServer.readLine();
1517
1518 System.out.println("FROM SERVER: Logical Address " + hostaddr);
1519
1520 clientSocket.close();
1521
1522 }
1523}
1524
1525
1526
1527*************************************************
1528
152911.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.
1530
1531CLIENT:
1532import java.io.*;
1533import java.net.*;
1534class client {
1535 public static void main(String argv[]) throws Exception
1536 {
1537 String sentence;
1538 String modifiedSentence;
1539 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
1540 Socket clientSocket = new Socket("localhost", 2222);
1541 DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
1542 BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
1543 System.out.println("Enter a number - ");
1544 sentence = inFromUser.readLine();
1545 outToServer.writeBytes(sentence + '\n');
1546 modifiedSentence = inFromServer.readLine();
1547 System.out.println ("Factorial: " + modifiedSentence );
1548 clientSocket.close();
1549 }
1550}
1551SREVER:
1552
1553import java.io.*;
1554import java.net.*;
1555class serv {
1556 public static void main(String argv[]) throws Exception
1557 {
1558 String clientSentence;
1559 String capitalizedSentence;
1560 ServerSocket welcomeSocket = new ServerSocket(2222);
1561 Socket connectionSocket = welcomeSocket.accept();
1562 BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
1563 DataOutputStream outToClient = new DataOutputStream (connectionSocket.getOutputStream());
1564 clientSentence = inFromClient.readLine();
1565 int num = Integer.parseInt(clientSentence);
1566 int fact=1;
1567 for(int i=1;i<=num;i++)
1568 fact=fact*i;
1569 System.out.println("Factorial : "+fact);
1570 capitalizedSentence = String.valueOf(fact);
1571 //capitalizedSentence = clientSentence.toUpperCase() + '\n';
1572 outToClient.writeBytes(capitalizedSentence);
1573 }
1574}
1575
1576******************************************************
1577
1578Ques12.Find the class of the IP address using TCP/IP.
1579import java.io.*;
1580import java.net.*;
1581
1582class TCPIpclassServer {
1583
1584 public static void main(String argv[]) throws Exception
1585 {
1586 String ip;
1587 int fbyte;
1588 String ipclass = "Invalid";
1589
1590
1591 ServerSocket welcomeSocket = new ServerSocket(6789);
1592
1593 while(true) {
1594
1595 Socket connectionSocket = welcomeSocket.accept();
1596
1597 BufferedReader inFromClient =
1598 new BufferedReader(new
1599 InputStreamReader(connectionSocket.getInputStream()));
1600
1601
1602 DataOutputStream outToClient =
1603 new DataOutputStream(connectionSocket.getOutputStream());
1604
1605 ip = inFromClient.readLine();
1606 int index;
1607 index = ip.indexOf(".");
1608 ip = ip.substring(0, index);
1609
1610
1611 fbyte = Integer.parseInt(ip);
1612 if (fbyte >= 0 && fbyte <= 127)
1613 ipclass = "Class A";
1614 else if (fbyte >= 128 && fbyte <= 191)
1615 ipclass = "Class B";
1616 else if (fbyte >= 192 && fbyte <= 223)
1617 ipclass = "Class C";
1618 else if (fbyte >= 224 && fbyte <= 239)
1619 ipclass = "Class D";
1620 else if (fbyte >= 240 && fbyte <= 255)
1621 ipclass = "Class E";
1622
1623 outToClient.writeBytes(ipclass + "\n");
1624 connectionSocket.close();
1625
1626 }
1627 }
1628}
1629
1630//client
1631
1632import java.io.*;
1633import java.net.*;
1634class TCPIpclassClient {
1635
1636 public static void main(String argv[]) throws Exception
1637 {
1638 String ip;
1639 String ipclass;
1640
1641 BufferedReader inFromUser =
1642 new BufferedReader(new InputStreamReader(System.in));
1643
1644 Socket clientSocket = new Socket("localhost", 6789);
1645
1646 DataOutputStream outToServer =
1647 new DataOutputStream(clientSocket.getOutputStream());
1648
1649 BufferedReader inFromServer =
1650 new BufferedReader(new
1651 InputStreamReader(clientSocket.getInputStream()));
1652
1653 System.out.println("Enter an IP address: ");
1654 ip = inFromUser.readLine();
1655
1656 outToServer.writeBytes(ip + '\n');
1657
1658 ipclass = inFromServer.readLine();
1659
1660 System.out.println("FROM SERVER: Class for IP: "+ ip + " is : " + ipclass);
1661
1662 clientSocket.close();
1663
1664 }
1665}
1666
1667CYCLESHEET 3
1668
16691. Implement echo server and client in java using UDP sockets.
1670
16712. Write a program to implement a text based message transfer from client to server process using UDP.
1672
16733. Implement a chat server and client in java using UDP sockets.
1674
16754. Implement a DNS server and client in java using UDP sockets.
1676
16775. Find the logical address of a host when its physical address is known (RARP protocol) using UDP.
1678
16796. Find the physical address of a host when its logical address is known (ARP protocol) using UDP.
1680
16817. Implement Client - Server communication to access Date using UDP in Java.
1682
1683Solutions :
1684
16851. Implement echo server and client in java using UDP sockets.
1686Code:
1687Server:
1688import java.io.*;
1689import java.net.*;
1690class UDPServer {
1691public static void main(String args[]) throws Exception
1692{
1693DatagramSocket serverSocket = new DatagramSocket(9876);
1694byte[] receiveData = new byte[1024];
1695byte[] sendData = new byte[1024];
1696while(true)
1697{
1698DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
1699serverSocket.receive(receivePacket);
1700String sentence = new String(receivePacket.getData());
1701InetAddress IPAddress = receivePacket.getAddress();
1702int port = receivePacket.getPort();
1703String capitalizedSentence = sentence.toUpperCase();
1704sendData = capitalizedSentence.getBytes();
1705DatagramPacket sendPacket =new DatagramPacket(sendData, sendData.length, IPAddress,port);
1706serverSocket.send(sendPacket);
1707}
1708}
1709}
1710
1711Client
1712import java.io.*;
1713import java.net.*;
1714
1715class UDPClient {
1716public static void main(String args[]) throws Exception
1717{
1718BufferedReader inFromUser =
1719new BufferedReader(new InputStreamReader(System.in));
1720DatagramSocket clientSocket = new DatagramSocket();
1721InetAddress IPAddress = InetAddress.getByName("");
1722byte[] sendData = new byte[1024];
1723byte[] receiveData = new byte[1024];
1724String sentence = inFromUser.readLine();
1725sendData = sentence.getBytes();
1726DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
1727clientSocket.send(sendPacket);
1728DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
1729clientSocket.receive(receivePacket);
1730String modifiedSentence = new String(receivePacket.getData());
1731System.out.println("FROM SERVER:" + modifiedSentence);
1732clientSocket.close();
1733}
1734}
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760Q. Write a program to implement a text based message transfer from client to server process using UDP.
1761
1762Code:
1763Server:
1764import java.net.DatagramPacket;
1765import java.net.DatagramSocket;
1766public class UDPaServer
1767{
1768 public static void main(String args[])
1769 {
1770 int server_port = 1111;
1771 System.out.println("UDP Server Listening in " + server_port);
1772 try
1773 {
1774 // DatagramSocket created and listening in Port 1111
1775 DatagramSocket socket = new DatagramSocket(server_port);
1776 byte[] msgBuffer = new byte[1024];
1777
1778 // DatagramPacket for receiving the incoming data from UDP Client
1779 DatagramPacket packet = new DatagramPacket(msgBuffer, msgBuffer.length);
1780
1781 while (true)
1782 {
1783 socket.receive(packet);
1784 String message = new String(msgBuffer, 0, packet.getLength());
1785 System.out.println("UDPServer: Message received = " + message);
1786 packet.setLength(msgBuffer.length);
1787 }
1788 }
1789 catch (Exception e)
1790 {
1791 e.printStackTrace();
1792 System.out.println("Error in getting the Data from UDP Client");
1793 }
1794 }
1795}
1796
1797Client:
1798import java.net.DatagramPacket;
1799import java.net.DatagramSocket;
1800import java.net.InetAddress;
1801import java.io.*;
1802import java.net.*;
1803
1804public class UDPaClient
1805{
1806 public static void main(String args[])
1807 {
1808 try
1809 {
1810 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
1811 String server_address = "localhost";
1812 int server_port = 1111;
1813 String message = inFromUser.readLine();
1814 InetAddress address = InetAddress.getByName(server_address);
1815 DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, address, server_port);
1816 DatagramSocket socket = new DatagramSocket();
1817 socket.send(packet);
1818
1819 System.out.println("UDPClient: Sent data to Server ; Message = " + message);
1820 socket.close();
1821 }
1822 catch (Exception e)
1823 {
1824 e.printStackTrace();
1825 System.out.println("Error in sending the Data to UDP Server");
1826 }
1827 }
1828}
1829
1830
1831**********************************************
1832
18333.Implement a chat server and client in java using UDP sockets.
1834
1835//server
1836import java.io.*;
1837import java.net.*;
1838
1839public class UDPChatServer {
1840 public static void main(String args[]) throws Exception
1841 {
1842 DatagramSocket serverSocket = new DatagramSocket(6789);
1843
1844 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
1845 String reply;
1846 while(true)
1847 {
1848 byte[] receiveData = new byte[1024];
1849 byte[] sendData = new byte[1024];
1850 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
1851 serverSocket.receive(receivePacket);
1852
1853 String msg = new String(receivePacket.getData());
1854 System.out.println("Message Received: " + msg);
1855
1856 InetAddress IPAddress = receivePacket.getAddress();
1857 int port = receivePacket.getPort();
1858
1859 System.out.printf("Enter reply: ");
1860 reply = inFromUser.readLine();
1861 if (reply.equals("bye"))
1862 {
1863 System.out.printf("Exiting Chat!");
1864 serverSocket.close();
1865 break;
1866 }
1867 sendData = reply.getBytes();
1868 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
1869 serverSocket.send(sendPacket);
1870 }
1871
1872 }
1873}
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884//client
1885import java.io.*;
1886import java.net.*;
1887
1888public class UDPChatClient {
1889 public static void main(String args[]) throws Exception
1890 {
1891 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
1892
1893 InetAddress IPAddress = InetAddress.getByName("localhost");
1894
1895 String msg = "";
1896 while(true)
1897 {
1898 byte[] sendData = new byte[1024];
1899 byte[] receiveData = new byte[1024];
1900 DatagramSocket clientSocket = new DatagramSocket();
1901 System.out.printf("Send a Message: ");
1902 msg = inFromUser.readLine();
1903 if (msg.equals("bye"))
1904 {
1905 System.out.printf("Exiting Chat!");
1906 clientSocket.close();
1907 break;
1908 }
1909 sendData = msg.getBytes();
1910
1911 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 6789);
1912 clientSocket.send(sendPacket);
1913
1914 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
1915 clientSocket.receive(receivePacket);
1916
1917 String reply = new String(receivePacket.getData());
1918 System.out.println("Reply: " + reply);
1919 clientSocket.close();
1920 }
1921 }
1922}
1923
1924
1925****************************************
1926
1927
1928
19294. Implement a DNS server and client in java using UDP sockets.
1930
1931//server
1932import java.io.*;
1933import java.net.*;
1934import java.util.*;
1935class Serverdns12
1936{
1937
1938 public static void main(String args[])
1939 {
1940 try
1941 {
1942 DatagramSocket server=new DatagramSocket(1309);
1943 while(true)
1944 {
1945 byte[] sendbyte=new byte[1024];
1946 byte[] receivebyte=new byte[1024];
1947 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
1948 server.receive(receiver);
1949 String str=new String(receiver.getData());
1950 String s=str.trim();
1951 //System.out.println(s);
1952 InetAddress addr=receiver.getAddress();
1953 int port=receiver.getPort();
1954 String ip[]={"165.165.80.80","165.165.79.1"};
1955 String name[]={"www.aptitudeguru.com","www.downloadcyclone.blogspot.com"};
1956 for(int i=0;i<ip.length;i++)
1957 {
1958 if(s.equals(ip[i]))
1959 {
1960 sendbyte=name[i].getBytes();
1961 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
1962 server.send(sender);
1963 break;
1964 }
1965 else if(s.equals(name[i]))
1966 {
1967 sendbyte=ip[i].getBytes();
1968 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
1969 server.send(sender);
1970 break;
1971 }
1972 }
1973 break;
1974 }
1975 }
1976 catch(Exception e)
1977 {
1978 System.out.println(e);
1979 }
1980 }
1981}
1982
1983
1984
1985
1986//client
1987
1988import java.io.*;
1989import java.net.*;
1990import java.util.*;
1991class Clientdns12
1992{
1993 public static void main(String args[])
1994 {
1995 try
1996 {
1997 DatagramSocket client=new DatagramSocket();
1998 InetAddress addr=InetAddress.getByName("127.0.0.1");
1999
2000 byte[] sendbyte=new byte[1024];
2001 byte[] receivebyte=new byte[1024];
2002
2003 BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
2004 System.out.println("Enter the DOMAIN NAME or IP adress:");
2005 String str=in.readLine();
2006 sendbyte=str.getBytes();
2007 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,1309);
2008 client.send(sender);
2009 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
2010 client.receive(receiver);
2011 String s=new String(receiver.getData());
2012 System.out.println("IP address or DOMAIN NAME: "+s.trim());
2013 client.close();
2014 }
2015 catch(Exception e)
2016 {
2017 System.out.println(e);
2018 }
2019 }
2020}
2021
2022***************************
2023
2024
2025
2026
2027
20285. Find the logical address of a host when its physical address is known (RARP protocol) using UDP.
2029
2030//SERVER
2031import java.io.*;
2032import java.net.*;
2033
2034public class UDPRARPServer {
2035 public static void main(String args[]) throws Exception
2036 {
2037 DatagramSocket serverSocket = new DatagramSocket(6789);
2038 byte[] receiveData = new byte[1024];
2039 byte[] sendData = new byte[1024];
2040
2041 String logical[] = {"172.16.27.34","195.24.54.204", "10.10.137.1"};
2042 String physical[] = {"8E:AE:08:AA","0A:78:6C:AD", "d4:6d:50:84:db:c8"};
2043 String reply = "";
2044
2045 while(true)
2046 {
2047 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
2048 serverSocket.receive(receivePacket);
2049
2050 String phyaddr = new String(receivePacket.getData());
2051 System.out.println("Physical Address received: " + phyaddr);
2052 phyaddr = phyaddr.trim();
2053 InetAddress IPAddress = receivePacket.getAddress();
2054 int port = receivePacket.getPort();
2055
2056 for(int i = 0; i < physical.length; i++)
2057 {
2058 if (phyaddr.equals(physical[i]))
2059 {
2060 reply = logical[i];
2061 sendData = reply.getBytes();
2062 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
2063 serverSocket.send(sendPacket);
2064 }
2065 }
2066
2067 }
2068 }
2069}
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080//CLIENT
2081import java.io.*;
2082import java.net.*;
2083
2084public class UDPRARPClient {
2085 public static void main(String args[]) throws Exception
2086 {
2087 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
2088 DatagramSocket clientSocket = new DatagramSocket();
2089 InetAddress IPAddress = InetAddress.getByName("localhost");
2090 byte[] sendData = new byte[1024];
2091 byte[] receiveData = new byte[1024];
2092
2093 System.out.printf("Enter Physical address: ");
2094 String phyaddr = inFromUser.readLine();
2095 sendData = phyaddr.getBytes();
2096
2097 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 6789);
2098 clientSocket.send(sendPacket);
2099
2100 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
2101 clientSocket.receive(receivePacket);
2102
2103 String logaddr = new String(receivePacket.getData());
2104 System.out.println("Logical Address:" + logaddr);
2105 clientSocket.close();
2106 }
2107}
2108
2109
2110********************************
2111
2112
21136.Find the physical address of a host when its logical address is known (ARP protocol) using UDP.
2114
2115//server
2116import java.io.*;
2117import java.net.*;
2118import java.util.*;
2119class Serverarp12
2120{
2121 public static void main(String args[])
2122 {
2123 try
2124 {
2125 DatagramSocket server=new DatagramSocket(1309);
2126 while(true)
2127 {
2128 byte[] sendbyte=new byte[1024];
2129 byte[] receivebyte=new byte[1024];
2130 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
2131 server.receive(receiver);
2132 String str=new String(receiver.getData());
2133 String s=str.trim();
2134 //System.out.println(s);
2135 InetAddress addr=receiver.getAddress();
2136 int port=receiver.getPort();
2137 String ip[]={"165.165.80.80","165.165.79.1"};
2138 String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
2139 for(int i=0;i<ip.length;i++)
2140 {
2141 if(s.equals(ip[i]))
2142 {
2143 sendbyte=mac[i].getBytes();
2144 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
2145 server.send(sender);
2146 break;
2147 }
2148 }
2149 break;
2150
2151
2152 }
2153 }
2154 catch(Exception e)
2155 {
2156 System.out.println(e);
2157 }
2158 }
2159}
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173//client
2174import java.io.*;
2175import java.net.*;
2176import java.util.*;
2177class Clientarp12
2178{
2179 public static void main(String args[])
2180 {
2181 try
2182 {
2183 DatagramSocket client=new DatagramSocket();
2184 InetAddress addr=InetAddress.getByName("127.0.0.1");
2185
2186 byte[] sendbyte=new byte[1024];
2187 byte[] receivebyte=new byte[1024];
2188 BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
2189 System.out.println("Enter the logical address (IP):");
2190 String str=in.readLine();
2191 sendbyte=str.getBytes();
2192 DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,1309);
2193 client.send(sender);
2194 DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
2195 client.receive(receiver);
2196 String s=new String(receiver.getData());
2197 System.out.println("The Physical Address is(MAC): "+s.trim());
2198 client.close();
2199 }
2200 catch(Exception e)
2201 {
2202 System.out.println(e);
2203 }
2204 }
2205}
2206
2207
2208
2209*********************************
2210
2211
22127.Implement Client - Server communication to access Date using UDP in Java.
2213
2214
2215//server
2216import java.io.*;
2217import java.net.*;
2218import java.util.*;
2219
2220public class UDPDateServer {
2221 public static void main(String args[]) throws Exception
2222 {
2223 DatagramSocket serverSocket = new DatagramSocket(6789);
2224 byte[] receiveData = new byte[1024];
2225 byte[] sendData = new byte[1024];
2226 String GetDate = "";
2227 while(true)
2228 {
2229 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
2230 serverSocket.receive(receivePacket);
2231
2232 String msg = new String(receivePacket.getData());
2233 System.out.println("Message: " + msg);
2234
2235 InetAddress IPAddress = receivePacket.getAddress();
2236 int port = receivePacket.getPort();
2237 msg = msg.trim();
2238 if (msg.equals("date"))
2239 {
2240 Date d = new Date();
2241 GetDate = d.toString();
2242 }
2243
2244 sendData = GetDate.getBytes();
2245 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
2246 serverSocket.send(sendPacket);
2247 }
2248 }
2249}
2250
2251
2252
2253
2254
2255//client
2256
2257import java.io.*;
2258import java.net.*;
2259
2260
2261public class UDPDateClient {
2262 public static void main(String args[]) throws Exception
2263 {
2264 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
2265 DatagramSocket clientSocket = new DatagramSocket();
2266 InetAddress IPAddress = InetAddress.getByName("localhost");
2267 byte[] sendData = new byte[1024];
2268 byte[] receiveData = new byte[1024];
2269
2270 System.out.printf("Enter Request: ");
2271 String msg = inFromUser.readLine();
2272 sendData = msg.getBytes();
2273
2274 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 6789);
2275 clientSocket.send(sendPacket);
2276
2277 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
2278 clientSocket.receive(receivePacket);
2279
2280 String reply = new String(receivePacket.getData());
2281 System.out.println("FROM SERVER:" + reply);
2282 clientSocket.close();
2283 }
2284}
2285
2286
2287==========================================
2288
2289This 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
2290Methods in java.net that return InetAddress
2291
2292 InetAddress
2293InterfaceAddress.getAddress()
2294 Returns an InetAddress for this address.
2295 InetAddress
2296InetSocketAddress.getAddress()
2297 Gets the InetAddress.
2298 InetAddress
2299DatagramPacket.getAddress()
2300 Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.
2301static InetAddress[]
2302InetAddress.getAllByName(String host)
2303 Given the name of a host, returns an array of its IP addresses, based on the configured name service on the system.
2304 InetAddress
2305InterfaceAddress.getBroadcast()
2306 Returns an InetAddress for the brodcast address for this InterfaceAddress.
2307static InetAddress
2308InetAddress.getByAddress(byte[] addr)
2309 Returns an InetAddress object given the raw IP address .
2310static InetAddress
2311InetAddress.getByAddress(String host, byte[] addr)
2312 Create an InetAddress based on the provided host name and IP address No name service is checked for the validity of the address.
2313static InetAddress
2314InetAddress.getByName(String host)
2315 Determines the IP address of a host, given the host's name.
2316protected InetAddress
2317URLStreamHandler.getHostAddress(URL u)
2318 Get the IP address of our host.
2319protected InetAddress
2320SocketImpl.getInetAddress()
2321 Returns the value of this socket's address field.
2322 InetAddress
2323Socket.getInetAddress()
2324 Returns the address to which the socket is connected.
2325 InetAddress
2326ServerSocket.getInetAddress()
2327 Returns the local address of this server socket.
2328 InetAddress
2329DatagramSocket.getInetAddress()
2330 Returns the address to which this socket is connected.
2331 InetAddress
2332MulticastSocket.getInterface()
2333 Retrieve the address of the network interface used for multicast packets.
2334 InetAddress
2335Socket.getLocalAddress()
2336 Gets the local address to which the socket is bound.
2337 InetAddress
2338DatagramSocket.getLocalAddress()
2339 Gets the local address to which the socket is bound.
2340static InetAddress
2341InetAddress.getLocalHost()
2342 Returns the local host.
2343protected InetAddress
2344Authenticator.getRequestingSite()
2345 Gets the InetAddress of the site requesting authorization, or null if not available.
2346
2347
2348\A Program That Prints the Address of 192.168.64.3\\
2349
2350import java.net.*;
2351public class Address {
2352public static void main (String[] args) {
2353try {
2354InetAddress address = inetAddress.getByName("192.168.64.3");
2355System.out.println(address);
2356}
2357catch (UnknownHostException e) {
2358System.out.println("Could not find 192.168.64.3 ");
2359}
2360}
2361}
2362
2363\\program find the all address of google\\
2364
2365import java.net.*;
2366public class AllAddressesOfgoogle {
2367public static void main (String[] args) {
2368try {
2369InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
2370for (int i = 0; i < addresses.length; i++) {
2371System.out.println(addresses[i]);
2372}
2373}
2374catch (UnknownHostException e) {
2375System.out.println("Could not find www.microsoft.com");
2376}
2377}
2378}
2379
2380
2381
2382\\prints the address of the machine it's run on.
2383
2384import java.net.*;
2385public class MyAddress {
2386public static void main (String[] args) {
2387try {
2388InetAddress address = InetAddress.getLocalHost( );
2389System.out.println(address);
2390}
2391catch (UnknownHostException e) {
2392System.out.println("Could not find this computer's address.");
2393}
2394}
2395}
2396
2397Given the Address, Find the Hostname
2398import java.net.*;
2399public class ReverseTest {
2400public static void main (String[] args) {
2401try {
2402InetAddress ia = InetAddress.getByName("192.168.64.3");
2403System.out.println(ia.getHostName( ));
2404}
2405catch (Exception e) {
2406System.err.println(e);
2407}
2408}
2409}
2410. Are www.oreilly.com and helio.ora.com the Same?
2411import java.net.*;
2412public class OReillyAliases {
2413public static void main (String args[]) {
2414try {
2415InetAddress oreilly = InetAddress.getByName("www.oreilly.com");
2416InetAddress helio = InetAddress.getByName("helio.ora.com");
2417if (oreilly.equals(helio)) {
2418System.out.println("www.oreilly.com is the same as helio.ora.com");
2419}
2420else {
2421System.out.println("www.oreilly.com is not the same as helio.ora.com");
2422}
2423}
2424catch (UnknownHostException e) {
2425System.out.println("Host lookup failed.");
2426}
2427}
2428}
2429
2430import java.net.*;
2431import java.io.*;
2432public class prog7
2433{
2434public static void main(String args[])
2435{
2436try
2437{
2438
2439BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
2440File f=new File("test.txt");
2441FileWriter fw=new FileWriter(f);
2442System.out.println("Enter the URL which u want to download");
2443String str=br.readLine();
2444URL u=new URL(str);
2445InputStream in=u.openStream();
2446BufferedReader br1=new BufferedReader(new InputStreamReader(in));
2447String str1;
2448while((str1=br1.readLine())!=null){
2449fw.write(str1+"\r\n");
2450}
2451System.out.println("the content of the url:"+str+" is download and saved in text .txt");
2452fw.close();
2453}
2454catch(Exception e)
2455{
2456System.out.println(e);
2457}
2458}
2459}
2460
2461
2462+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++11111111111111111111111111111111111111111111111111111111111111111111111111144444444444444444444444444444444444444444444444444444444444444444444444444444444444444bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiittttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111133333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333
2463
2464
2465
2466
2467question one
2468Implement echo server and client in java using UDP sockets.
2469
2470Client program ServerEcho.java
2471
2472import java.net.*;
2473import java.util.*;
2474
2475public class ServerEcho
2476{
2477 public static void main( String args[]) throws Exception
2478 {
2479 DatagramSocket dsock = new DatagramSocket(7);
2480 byte arr1[] = new byte[150];
2481 DatagramPacket dpack = new DatagramPacket(arr1, arr1.length );
2482
2483 while(true)
2484 {
2485 dsock.receive(dpack);
2486
2487 byte arr2[] = dpack.getData();
2488 int packSize = dpack.getLength();
2489 String s2 = new String(arr2, 0, packSize);
2490
2491 System.out.println( new Date( ) + " " + dpack.getAddress( ) + " : " + dpack.getPort( ) + " "+ s2);
2492 dsock.send(dpack);
2493 }
2494 }
2495}
2496
2497Client program ClientEcho.java
2498import java.net.*;
2499import java.util.*;
2500
2501public class ClientEcho
2502{
2503 public static void main( String args[] ) throws Exception
2504 {
2505 InetAddress add = InetAddress.getByName("snrao");
2506
2507 DatagramSocket dsock = new DatagramSocket( );
2508 String message1 = "This is client calling";
2509 byte arr[] = message1.getBytes( );
2510 DatagramPacket dpack = new DatagramPacket(arr, arr.length, add, 7);
2511 dsock.send(dpack); // send the packet
2512 Date sendTime = new Date(); // note the time of sending the message
2513
2514 dsock.receive(dpack); // receive the packet
2515 String message2 = new String(dpack.getData( ));
2516 Date receiveTime = new Date( ); // note the time of receiving the message
2517 System.out.println((receiveTime.getTime( ) - sendTime.getTime( )) + " milliseconds echo time for " + message2);
2518 }
2519}
2520
2521
2522 OR
2523
2524import java.net.*;
2525 import java.util.*;
2526 public class EchoServer
2527{
2528 public static void main( String args[]) throws Exception
2529 {
2530 DatagramSocket dsock = new DatagramSocket(7);
2531byte arr1[] = new byte[150];
2532DatagramPacket dpack = new DatagramPacket(arr1, arr1.length );
2533while(true)
2534{ dsock.receive(dpack);
2535byte arr2[] = dpack.getData();
2536 int packSize = dpack.getLength();
2537String s2 = new String(arr2, 0, packSize);
2538System.out.println( new Date( ) + " " + dpack.getAddress( ) + " : " + dpack.getPort( ) + " "+ s2);
2539dsock.send(dpack);
2540}
2541}
2542}----------------------------------
2543import java.net.*;
2544import java.util.*;
2545 public class EchoClient
2546{ public static void main( String args[] ) throws Exception {
2547InetAddress add = InetAddress.getByName("127.0.0.1");
2548DatagramSocket dsock = new DatagramSocket( );
2549 String message1 = "This is client calling";
2550 byte arr[] = message1.getBytes( );
2551 DatagramPacket dpack = new DatagramPacket(arr, arr.length, add, 7);
2552 dsock.send(dpack); // send the packet
2553Date sendTime = new Date( ); // note the time of sending the message
2554dsock.receive(dpack); // receive the packet
2555String message2 = new String(dpack.getData( ));
2556 Date receiveTime = new Date( ); // note the time of receiving the message
2557 System.out.println((receiveTime.getTime( ) - sendTime.getTime( )) + " milliseconds echo time for " + message2);
2558 }
2559 }
2560
2561
2562
2563
2564
2565
2566
2567
2568question 2
2569Implement a simple message transfer from client to server process using UDP.
2570import java.io.*;
2571import java.net.*;
2572class UDPServerss {
2573public static void main(String args[]) throws Exception {
2574 DatagramSocket serverSocket = new DatagramSocket(9876);
2575
2576 byte[] receiveData = new byte[1024];
2577 byte[] sendData = new byte[1024];
2578 while(true) {
2579
2580 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
2581 serverSocket.receive(receivePacket);
2582 String sentence = new String( receivePacket.getData());
2583 System.out.println("RECEIVED: " + sentence);
2584 InetAddress IPAddress = receivePacket.getAddress();
2585 int port = receivePacket.getPort();
2586 String capitalizedSentence = sentence.toUpperCase();
2587 sendData = capitalizedSentence.getBytes();
2588 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
2589 serverSocket.send(sendPacket);
2590 }
2591}
2592}
2593import java.io.*;
2594import java.net.*;
2595 class UDPClientssss {
2596 public static void main(String args[]) throws Exception {
2597 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
2598 DatagramSocket clientSocket = new DatagramSocket();
2599 InetAddress IPAddress = InetAddress.getByName("localhost");
2600 byte[] sendData = new byte[1024];
2601 byte[] receiveData = new byte[1024];
2602 String sentence = inFromUser.readLine();
2603 sendData = sentence.getBytes();
2604 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
2605 clientSocket.send(sendPacket);
2606 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
2607 clientSocket.receive(receivePacket);
2608 String modifiedSentence = new String(receivePacket.getData());
2609 System.out.println("FROM SERVER:" + modifiedSentence);
2610 clientSocket.close();
2611 }
2612 }
2613
2614
2615
2616
2617
2618
2619question 3
2620 Simple chat application in java using datagram socket and datagram packet
2621Algorithm
2622Start the UDP chat program
2623Import the package java.net.*;
2624Declare the datagramsocket,datagrampacket,BufferedReader,InetAddress.
2625Start the main function
2626In the main function using while loop it perform the loop until str.equals is STOP
2627There important while loop function are
2628clientsocket = new DatagramSocket(cport);
2629dp = new DatagramPacket(buf, buf.length);
2630dis = new BufferedReader(new
2631InputStreamReader(System.in));
2632ia = InetAddress.getLocalHost(); f it is stop then break the while loop
2633Terminate the UDP client program
2634source code java programming UDP Chat server
2635import java.io.*;
2636import java.net.*;
2637class UDPServer
2638{
2639public static DatagramSocket serversocket;
2640public static DatagramPacket dp;
2641public static BufferedReader dis;
2642public static InetAddress ia;
2643public static byte buf[] = new byte[1024];
2644public static int cport = 789,sport=790;
2645public static void main(String[] a) throws IOException
2646{
2647serversocket = new DatagramSocket(sport);
2648dp = new DatagramPacket(buf,buf.length);
2649dis = new BufferedReader
2650(new InputStreamReader(System.in));
2651ia = InetAddress.getLocalHost();
2652System.out.println("Server is Running...");
2653while(true)
2654{
2655serversocket.receive(dp);
2656String str = new String(dp.getData(), 0,
2657dp.getLength());
2658if(str.equals("STOP"))
2659{
2660System.out.println("Terminated...");
2661break;
2662}
2663System.out.println("Client: " + str);
2664String str1 = new String(dis.readLine());
2665buf = str1.getBytes();
2666serversocket.send(new
2667DatagramPacket(buf,str1.length(), ia, cport));
2668}
2669}
2670}
2671
2672Output:-
2673C:\IPLAB>javac UDPServer.java
2674C:\IPLAB>java UDPServer
2675Server is Running...
2676Client: Hello
2677Welcome
2678Terminated...
2679
2680source code java programming UDP Chat Client
2681import java.io.*;
2682import java.net.*;
2683class UDPClient
2684{
2685public static DatagramSocket clientsocket;
2686public static DatagramPacket dp;
2687public static BufferedReader dis;
2688public static InetAddress ia;
2689public static byte buf[] = new byte[1024];
2690public static int cport = 789, sport = 790;
2691public static void main(String[] a) throws IOException
2692{
2693clientsocket = new DatagramSocket(cport);
2694dp = new DatagramPacket(buf, buf.length);
2695dis = new BufferedReader(new
2696InputStreamReader(System.in));
2697ia = InetAddress.getLocalHost();
2698System.out.println("Client is Running... Type 'STOP'
2699to Quit");
2700while(true)
2701{
2702String str = new String(dis.readLine());
2703buf = str.getBytes();
2704if(str.equals("STOP"))
2705{
2706System.out.println("Terminated...");
2707clientsocket.send(new
2708DatagramPacket(buf,str.length(), ia,
2709sport));
2710break;
2711}
2712clientsocket.send(new DatagramPacket(buf,
2713str.length(), ia, sport));
2714clientsocket.receive(dp);
2715String str2 = new String(dp.getData(), 0,
2716dp.getLength());
2717System.out.println("Server: " + str2);
2718}
2719}
2720}
2721
2722Output UDP Chat Client
2723C:\IPLAB>javac UDPClient.java
2724C:\IPLAB>java UDPClient
2725Client is Running... Type STOP to Quit
2726Hello
2727Server: Welcome
2728STOP
2729Terminated...
2730BB / REC - 41
2731
2732
2733
2734 or
2735
2736
2737 Client interface:
2738
2739 import java.awt.*;
2740 import javax.swing.*;
2741 public class UDPClient extends JFrame
2742 {
2743 // Variables
2744 private JFrame frame;
2745 private JPanel panel;
2746 private JLabel label;
2747 private JButton sendbutton;
2748 private JTextField textfield;
2749 private JTextArea textarea;
2750 private JScrollPane scrollpane;
2751
2752 public static void main (String args[]) {
2753
2754 new UDPClient();
2755 }
2756
2757 // Constructor
2758 public UDPClient() {
2759
2760 frame = this;
2761 panel = new JPanel(new GridBagLayout());
2762 panel.setBackground(Color.cyan);
2763 frame.setTitle("Chat Applet Client");
2764 frame.getContentPane().add(panel, BorderLayout.NORTH);
2765 frame.setVisible(true);
2766 frame.setSize(430, 364);
2767 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
2768 //frame.setResizable(false);
2769 GridBagConstraints c = new GridBagConstraints();
2770 c.insets = new Insets(5, 5, 5, 5);
2771
2772 // Server address label
2773 label = new JLabel("Server:");
2774 c.fill = GridBagConstraints.HORIZONTAL;
2775 c.gridx = 0;
2776 c.gridy = 0;
2777 panel.add(label, c);
2778
2779 // Server address textfield
2780 textfield = new JTextField(20);
2781 c.fill = GridBagConstraints.HORIZONTAL;
2782 c.gridx = 1;
2783 c.gridy = 0;
2784 panel.add(textfield, c);
2785
2786 // 'Port#:' label
2787 label = new JLabel("Port# :");
2788 c.fill = GridBagConstraints.HORIZONTAL;
2789 c.gridx = 2;
2790 c.gridy = 0;
2791 panel.add(label, c);
2792
2793 // Port# textfield
2794 textfield = new JTextField(6);
2795 c.fill = GridBagConstraints.HORIZONTAL;
2796 c.gridx = 3;
2797 c.gridy = 0;
2798 panel.add(textfield, c);
2799
2800 // 'Conversation:' label
2801 label = new JLabel("Conversation:");
2802 c.fill = GridBagConstraints.HORIZONTAL;
2803 c.gridx = 0;
2804 c.gridy = 1;
2805 c.gridwidth = 4;
2806 panel.add(label, c);
2807
2808 // Conversation Window
2809 textarea = new JTextArea(10, 2);
2810 scrollpane = new JScrollPane(textarea);
2811 textarea.setLineWrap(true);
2812 textarea.setWrapStyleWord(true);
2813 textarea.setEditable(false);
2814 c.fill = GridBagConstraints.HORIZONTAL;
2815 c.gridx = 0;
2816 c.gridy = 2;
2817 c.gridwidth = 4;
2818 panel.add(scrollpane, c);
2819
2820 // 'Message:' label
2821 label = new JLabel("Message to Send:");
2822 c.fill = GridBagConstraints.HORIZONTAL;
2823 c.gridx = 0;
2824 c.gridy = 3;
2825 panel.add(label, c);
2826
2827 // Message Window
2828 textarea = new JTextArea(2, 2);
2829 scrollpane = new JScrollPane(textarea);
2830 textarea.setLineWrap(true);
2831 textarea.setWrapStyleWord(true);
2832 c.fill = GridBagConstraints.HORIZONTAL;
2833 c.gridx = 0;
2834 c.gridy = 4;
2835 c.gridwidth = 4;
2836 panel.add(scrollpane, c);
2837
2838 // 'Send' button
2839 sendbutton = new JButton("Send");
2840 c.fill = GridBagConstraints.HORIZONTAL;
2841 c.gridx = 0;
2842 c.gridy = 5;
2843 c.gridwidth = 4;
2844 panel.add(sendbutton, c);
2845 }
2846 }
2847
2848
2849
2850
2851
2852Server interface:
2853
2854 import java.awt.*;
2855 import javax.swing.*;
2856 public class UDPServer extends JFrame {
2857 // Variables
2858 private JFrame frame;
2859 private JPanel panel;
2860 private JLabel label;
2861 private JButton startbutton;
2862 private JButton stopbutton;
2863 private JButton sendbutton;
2864 private JTextField textfield;
2865 private JTextArea textarea;
2866 private JScrollPane scrollpane;
2867
2868 //http://www.youtube.com/watch?v=IkEz5tW5bok
2869 public static void main (String args[]) {
2870
2871 new UDPServer();
2872 }
2873
2874 // Constructor
2875 public UDPServer() {
2876
2877 frame = this;
2878 panel = new JPanel(new GridBagLayout());
2879 panel.setBackground(Color.darkGray);
2880 frame.setTitle("Chat Applet Server");
2881 frame.getContentPane().add(panel, BorderLayout.NORTH);
2882 frame.setVisible(true);
2883 //frame.pack();
2884
2885 frame.setSize(430, 364);
2886 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
2887 frame.setResizable(true);
2888 GridBagConstraints c = new GridBagConstraints();
2889 c.insets = new Insets(5, 5, 5, 5);
2890
2891 // 'Start Server' button
2892 startbutton = new JButton("Start Server");
2893 startbutton.setPreferredSize(new Dimension(130,20));
2894 c.fill = GridBagConstraints.HORIZONTAL;
2895 c.gridx = 0;
2896 c.gridy = 0;
2897 c.gridwidth = 1;
2898 panel.add(startbutton, c);
2899
2900 // 'Stop Server' button
2901 stopbutton = new JButton("Stop Server");
2902 stopbutton.setPreferredSize(new Dimension(130,20));
2903 c.fill = GridBagConstraints.HORIZONTAL;
2904 c.gridx = 1;
2905 c.gridy = 0;
2906 c.gridwidth = 1;
2907 panel.add(stopbutton, c);
2908
2909 // 'Port#:' label
2910 label = new JLabel("Port# :");
2911 label.setForeground(Color.white);
2912 c.fill = GridBagConstraints.HORIZONTAL;
2913 c.gridx = 2;
2914 c.gridy = 0;
2915 panel.add(label, c);
2916
2917 // Port# textfield
2918 textfield = new JTextField(6);
2919 c.fill = GridBagConstraints.HORIZONTAL;
2920 c.gridx = 3;
2921 c.gridy = 0;
2922 panel.add(textfield, c);
2923
2924 // 'Conversation:' label
2925 label = new JLabel("Conversation:");
2926 label.setForeground(Color.white);
2927 c.fill = GridBagConstraints.HORIZONTAL;
2928 c.gridx = 0;
2929 c.gridy = 1;
2930 c.gridwidth = 4;
2931 panel.add(label, c);
2932
2933 // Conversation Window
2934 textarea = new JTextArea("<Server not yet started!>", 10, 2);
2935 scrollpane = new JScrollPane(textarea);
2936 textarea.setLineWrap(true);
2937 textarea.setWrapStyleWord(true);
2938 textarea.setEditable(false);
2939 c.fill = GridBagConstraints.HORIZONTAL;
2940 c.gridx = 0;
2941 c.gridy = 2;
2942 c.gridwidth = 4;
2943 panel.add(scrollpane, c);
2944
2945 // 'Message:' label
2946 label = new JLabel("Message to Send:");
2947 label.setForeground(Color.white);
2948 c.fill = GridBagConstraints.HORIZONTAL;
2949 c.gridx = 0;
2950 c.gridy = 3;
2951 panel.add(label, c);
2952
2953 // Message Window
2954 textarea = new JTextArea(2, 2);
2955 scrollpane = new JScrollPane(textarea);
2956 textarea.setLineWrap(true);
2957 textarea.setWrapStyleWord(true);
2958 c.fill = GridBagConstraints.HORIZONTAL;
2959 c.gridx = 0;
2960 c.gridy = 4;
2961 c.gridwidth = 4;
2962 panel.add(scrollpane, c);
2963
2964 // 'Send' button
2965 sendbutton = new JButton("Send");
2966 c.fill = GridBagConstraints.HORIZONTAL;
2967 c.gridx = 0;
2968 c.gridy = 5;
2969 c.gridwidth = 4;
2970 panel.add(sendbutton, c);
2971 }
2972 }
2973
2974
2975
2976
2977
2978
2979question 4-----------------------------
2980UDP Program DNS CLIENT-SERVER
2981
2982UDP Program (DNS CLIENT-SERVER)
2983
2984AIM : To create a client server program to Domain Name System using the UDP protocol client server.
2985
2986ALGORITHM
2987
2988Server
2989
2990 Declare the necessary arrays and variables.
2991 Set server port address using socket().
2992 Get the current message.
2993 Connect to the client.
2994 Stop the process.
2995
2996Client
2997
2998 Set the client machine address.
2999 Connect to the server.
3000 Read from the server the current message.
3001 Display the current message.
3002 Close the connection.
3003
3004PROGRAM:
3005
3006UDPclient
3007
3008import java .io.*;
3009
3010import java.net.*;
3011
3012classUDPclient
3013
3014{
3015
3016public static DatagramSocket ds;
3017
3018public static intclientport=789,serverport=790;
3019
3020public static void main(String args[])throws Exception
3021
3022{
3023
3024byte buffer[]=new byte[1024];
3025
3026ds=new DatagramSocket(serverport);
3027
3028BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
3029
3030System.out.println(server waiting);
3031
3032InetAddressia=InetAddress.getLocalHost();
3033
3034while(true)
3035
3036{
3037
3038System.out.println(Client:);
3039
3040String str=dis.readLine();
3041
3042if(str.equals(end))
3043
3044break;
3045
3046buffer=str.getBytes();
3047
3048ds.send(new DatagramPacket(buffer,str.length(),ia,clientport));
3049
3050DatagramPacket p=new DatagramPacket(buffer,buffer.length);
3051
3052ds.receive(p);
3053
3054String psx=new String(p.getData(),0,p.getLength());
3055
3056System.out.println(Server: + psx);
3057
3058}
3059
3060}
3061
3062}
3063
3064UDP server
3065
3066import java.io.*;
3067
3068import java.net.*;
3069
3070classUDPserver
3071
3072{
3073
3074public static DatagramSocket ds;
3075
3076public static byte buffer[]=new byte[1024];
3077
3078public static intclientport=789,serverport=790;
3079
3080public static void main(String args[])throws Exception
3081
3082{
3083
3084ds=new DatagramSocket(clientport);
3085
3086System.out.println(press ctrl+c to quit the program);
3087
3088BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
3089
3090InetAddressia=InetAddress.getLocalHost();
3091
3092while(true)
3093
3094{
3095
3096DatagramPacket p=new DatagramPacket(buffer,buffer.length);
3097
3098ds.receive(p);
3099
3100String psx=new String(p.getData(),0,p.getLength());
3101
3102System.out.println(Client: + psx);
3103
3104InetAddressib=InetAddress.getByName(psx);
3105
3106System.out.println(Server output:+ib);
3107
3108String str=dis.readLine();
3109
3110if(str.equals(end))
3111
3112break;
3113
3114buffer=str.getBytes();
3115
3116ds.send(new DatagramPacket(buffer,str.length(),ia,serverport));
3117
3118}
3119
3120}
3121
3122}
3123
3124OUTPUT:
3125
3126UDPclient
3127
3128C:\Program Files\Java\jdk1.6.0\bin>javac UDPclient.java
3129
3130C:\Program Files\Java\jdk1.6.0\bin>java UDPclient
3131
3132Server waiting
3133
3134Client:www.yahoo.com
3135
3136UDPserver
3137
3138C:\Program Files\Java\jdk1.6.0\bin>javac UDPserver.java
3139
3140C:\Program Files\Java\jdk1.6.0\bin>java UDPserver
3141
3142Press ctrl+c to quit the program
3143
3144Client:www.yahoo.com
3145
3146Server output:www.yahoo.com/106.10.170.115
3147
3148RESULT:
3149
3150Thus client server program to Domain Name System using the UDP protocol client server has been executed and verified successfully.
3151
3152
3153
3154
3155
3156QUESTION 5------------------------------------------------
3157UDP DATE SERVER
3158
3159Server Program >>>>> Server.java
3160
3161
3162import java.net.*;
3163import java.io.*;
3164import java.util.*;
3165
3166public class Server {
3167
3168public static void main(String[] args) throws Exception{
3169
3170DatagramSocket ss=new DatagramSocket(1234);
3171
3172while(true){
3173
3174System.out.println("Server is up....");
3175
3176byte[] rd=new byte[100];
3177byte[] sd=new byte[100];
3178
3179DatagramPacket rp=new DatagramPacket(rd,rd.length);
3180
3181ss.receive(rp);
3182
3183InetAddress ip= rp.getAddress();
3184
3185int port=rp.getPort();
3186
3187Date d=new Date(); // getting system time
3188
3189String time= d + ""; // converting it to String
3190
3191sd=time.getBytes(); // converting that String to byte
3192
3193DatagramPacket sp=new DatagramPacket(sd,sd.length,ip,port);
3194
3195ss.send(sp);
3196
3197rp=null;
3198
3199System.out.println("Done !! ");
3200
3201}
3202
3203}
3204
3205}
3206
3207
3208Client program >>>>>>>>> Clientnew.java
3209import java.net.*;
3210import java.io.*;
3211
3212public class Clientnew {
3213
3214public static void main(String[] args) throws Exception{
3215
3216 System.out.println("Server Time >>>>");
3217
3218 DatagramSocket cs=new DatagramSocket();
3219
3220 InetAddress ip=InetAddress.getByName("localhost");
3221
3222 byte[] rd=new byte[100];
3223 byte[] sd=new byte[100];
3224
3225 DatagramPacket sp=new DatagramPacket(sd,sd.length,ip,1234);
3226
3227 DatagramPacket rp=new DatagramPacket(rd,rd.length);
3228
3229 cs.send(sp);
3230
3231 cs.receive(rp);
3232
3233 String time=new String(rp.getData());
3234
3235 System.out.println(time);
3236
3237 cs.close();
3238
3239}
3240
3241}
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
3252SIR UPLOADED MATERIAL
3253
3254
32551)Write a program to list all ports hosting a TCP server in a specified host.
3256
3257import java.net.*;
3258import java.io.*;
3259public class ports{
3260public static void main(String args[])
3261{
3262for(int i=1;i<1024;i++)
3263{
3264try{
3265Socket s=new Socket("127.0.0.1",i);
3266System.out.println("There is server on port"+i+"of 127.0.0.1");
3267}
3268catch(UnknownHostException e){
3269System.err.println(e);
3270break;
3271}
3272catch(IOException e){
3273//must not be server on this port
3274}
3275}
3276}
3277}
3278
32792)Write a program to display the servers date and time details at the client end.
3280
3281import java.io.IOException;
3282import java.io.PrintWriter;
3283import java.net.ServerSocket;
3284import java.net.Socket;
3285import java.util.Date;
3286
3287public class dateserver {
3288
3289 public static void main(String[] args) throws IOException {
3290 ServerSocket listener = new ServerSocket(9090);
3291 try {
3292 while (true) {
3293 Socket socket = listener.accept();
3294 try {
3295 PrintWriter out =
3296 new PrintWriter(socket.getOutputStream(), true);
3297 out.println(new Date().toString());
3298 } finally {
3299 socket.close();
3300 }
3301 }
3302 }
3303 finally {
3304 listener.close();
3305 }
3306 }
3307}
3308
3309------------------------------
3310import java.io.*;
3311import java.net.Socket;
3312
3313public class dateClient {
3314
3315 public static void main(String[] args) throws IOException {
3316 Socket s = new Socket("127.0.0.1", 9090);
3317 BufferedReader input =
3318 new BufferedReader(new InputStreamReader(s.getInputStream()));
3319 String answer = input.readLine();
3320 System.out.println("The date and time details are "+answer );
3321
3322 System.exit(0);
3323 }
3324}
3325
3326
33273)Write a program to display the clients address at the server end.
3328
3329
3330import java.io.*;
3331import java.net.*;
3332
3333public class ServerAddr
3334{
3335public static void main(String args[]) throws IOException
3336{
3337try
3338{
3339ServerSocket ss = new ServerSocket(6666);
3340System.out.println("Waiting for client.....");
3341
3342Socket s = ss.accept();
3343System.out.println("Connected to client....");
3344
3345DataInputStream in = new DataInputStream (s.getInputStream());
3346String line = null;
3347line = in.readUTF();
3348System.out.println("Client's IP adress: " + line);
3349}
3350catch (Exception e)
3351{
3352e.printStackTrace();
3353}
3354}
3355}
3356
3357--------------------------------
3358
3359import java.io.*;
3360import java.net.*;
3361
3362public class ClientAddr
3363{
3364public static void main(String args[]) throws IOException
3365{
3366try
3367{
3368InetAddress ipaddress = InetAddress.getByName("");
3369Socket s = new Socket(ipaddress,6666);
3370
3371System.out.println("Connected to the server...");
3372DataOutputStream out = new DataOutputStream(s.getOutputStream());
3373
3374String line = null;
3375System.out.println("Sending my IP Address to server...");
3376
3377line=ipaddress.getHostAddress();
3378
3379out.writeUTF(line);
3380out.flush();}
3381catch (Exception e)
3382{
3383e.printStackTrace();
3384}
3385}
3386}
3387
33884)Implement a simple message transfer from client to server process using TCP/IP.
3389
3390import java.io.*;
3391import java.net.*;
3392
3393public class Tcpserver
3394{
3395public static void main(String args[]) throws IOException
3396{
3397try
3398{
3399ServerSocket ss = new ServerSocket(6666);
3400System.out.println("Waiting for client.....");
3401
3402Socket s = ss.accept();
3403System.out.println("Connected to client....");
3404
3405DataInputStream in = new DataInputStream (s.getInputStream());
3406String line = null;
3407line = in.readUTF();
3408System.out.println("Mesage from Client:" + line);
3409}
3410catch (Exception e)
3411{
3412e.printStackTrace();
3413}
3414}
3415}
3416
3417--------------------------------------
3418import java.io.*;
3419import java.net.*;
3420
3421public class TCPClient
3422{
3423public static void main(String args[]) throws IOException
3424{
3425try
3426{
3427InetAddress ipaddress = InetAddress.getByName("");
3428Socket s = new Socket(ipaddress,6666);
3429DataInputStream read = new DataInputStream(System.in);
3430System.out.println("Connected to the server...");
3431DataOutputStream out = new DataOutputStream(s.getOutputStream());
3432
3433String line = null;
3434System.out.println("Write a message to the server..");
3435
3436line=read.readLine();
3437out.writeUTF(line);
3438out.flush();}
3439catch (Exception e)
3440{
3441e.printStackTrace();
3442}
3443}
3444}
3445
34465)Develop a TCP client/server application for transferring a text file from client to server
3447
3448
3449CLIENt:
3450import java.io.*;
3451 import java.net.*;
3452import java.util.*;
3453public class FTPClient {
3454public static void main(String args[]) throws Exception
3455
3456{
3457 Socket ss = new Socket("localhost",5000);
3458while(true)
3459{
3460
3461Scanner pbn = new Scanner(System.in);
3462System.out.println("Enter the path of the file ");
3463String path = pbn.nextLine();
3464System.out.println(path);
3465
3466File f = new File(path);
3467FileInputStream fis = new FileInputStream(f);
3468
3469BufferedInputStream bis = new BufferedInputStream(fis);
3470System.out.println("Sending file...");
3471
3472System.out.println("File sent");
3473
3474 }
3475
3476 }
3477}
3478server:
3479
3480//////////////////
3481import java.io.*;
3482import java.net.*;
3483import java.util.*;
3484public class FTPServer {
3485public static void main(String args[]) throws IOException
3486{ServerSocket ss = new ServerSocket(5000);
3487
3488 Scanner pbn = new Scanner(System.in);
3489 boolean flag = true;
3490 while(flag)
3491 {
3492 flag = false;
3493 try
3494 {System.out.println("waiting...");
3495Socket s = ss.accept();
3496System.out.println("Accepted connection "+s);
3497 System.out.println("Enter the path where you want to store the file");
3498 String path1 = pbn.nextLine();
3499 FileOutputStream fos = new FileOutputStream(path1);
3500 BufferedOutputStream bos = new BufferedOutputStream(fos);
3501 InputStream is = s.getInputStream();
3502 byte[] b = new byte[600000];
3503 int n = 0;
3504 int o = 0;
3505 while((n=is.read(b,o,b.length-o))>=0)
3506 {
3507 o+=n;
3508 }
3509 bos.write(b,0,o);
3510
3511 bos.flush();
3512 System.out.println("File Received");
3513 }
3514
3515 catch(FileNotFoundException f)
3516 {
3517 flag = true;
3518 String msg = f.getMessage();
3519 System.out.println("Error Message:"+msg);
3520 System.out.println("Please Enter a correct file path");
3521 }
3522 }
3523
3524 }
3525}
3526
3527
35286. Implement a TCP based server program to authenticate the clients 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.
3529
3530import java.io.*;
3531import java.net.*;
3532
3533public class AuthServer
3534{
3535 public static void main(String args[]) throws IOException
3536 {
3537 try
3538 {
3539 ServerSocket ss = new ServerSocket(6666);
3540 System.out.println("Waiting for client.....");
3541 Socket s = ss.accept();
3542 System.out.println("Connected to client....");
3543
3544 DataInputStream in = new DataInputStream (s.getInputStream());
3545 DataOutputStream out = new DataOutputStream (s.getOutputStream());
3546
3547 String line = null;
3548 String line1 = null;
3549 String sendline = null;
3550
3551
3552line = in.readUTF();
3553line1 = in.readUTF();
3554 if((line.equals("aid")|| line.equals("bid"))&&((line1.equals("apass")|| line1.equals("bpass"))))
3555 {
3556 sendline ="Valid user id and password.Successfully logged in !!!!";
3557 out.writeUTF(sendline);
3558 out.flush();
3559
3560 }
3561 else
3562
3563 {
3564 sendline ="Invalid details";
3565 out.writeUTF(sendline);
3566 out.flush();
3567 }
3568
3569 }
3570 catch (Exception e)
3571 {
3572 e.printStackTrace();
3573 }
3574 }
3575}
3576
3577import java.io.*;
3578import java.net.*;
3579
3580public class AuthClient
3581{
3582 public static void main(String args[]) throws IOException
3583 {
3584 try
3585 {
3586 InetAddress ipaddress = InetAddress.getByName("127.0.0.1");
3587 Socket s = new Socket(ipaddress,6666);
3588
3589 System.out.println("Connected to the server...");
3590
3591 DataInputStream read = new DataInputStream(System.in);
3592
3593 DataInputStream in = new DataInputStream(s.getInputStream());
3594 DataOutputStream out = new DataOutputStream(s.getOutputStream());
3595
3596 String line = null;
3597 String line1 = null;
3598 String receiveline = null;
3599
3600 System.out.println("Enter User id ");
3601 line = read.readLine();
3602 out.writeUTF(line);
3603 out.flush();
3604
3605System.out.println("Enter Password ");
3606line1 = read.readLine();
3607out.writeUTF(line1);
3608out.flush();
3609
3610
3611 receiveline = in.readUTF();
3612 System.out.println("SERVER: " + receiveline);
3613
3614
3615 }
3616 catch (Exception e)
3617 {
3618 e.printStackTrace();
3619 }
3620 }
3621}
3622
36237. Write a program to develop a simple (text based) Chat application using TCP/IP.
3624//chat
3625import java.io.*;
3626import java.net.*;
3627
3628public class TCPserver
3629{
3630 public static void main(String args[]) throws IOException
3631 {
3632 try
3633 {
3634 ServerSocket ss = new ServerSocket(6666);
3635 System.out.println("Waiting for client.....");
3636DataInputStream read = new DataInputStream(System.in);
3637 Socket s = ss.accept();
3638 System.out.println("Connected to client....");
3639
3640 DataInputStream in = new DataInputStream (s.getInputStream());
3641 DataOutputStream out = new DataOutputStream (s.getOutputStream());
3642
3643 String line = null;
3644
3645
3646 do
3647 {
3648 line = in.readUTF();
3649 System.out.println("CLIENT: " + line);
3650 line = read.readLine();
3651 out.writeUTF(line);
3652 out.flush();
3653
3654 System.out.println("Waiting for the next line.....");
3655 }while(!line.equals("bye"));
3656 }
3657 catch (Exception e)
3658 {
3659 e.printStackTrace();
3660 }
3661 }
3662}
3663
3664
3665//chat
3666import java.io.*;
3667import java.net.*;
3668
3669public class TCPClient
3670{
3671 public static void main(String args[]) throws IOException
3672 {
3673 try
3674 {
3675 InetAddress ipaddress = InetAddress.getByName("127.0.0.1");
3676 Socket s = new Socket(ipaddress,6666);
3677
3678 System.out.println("Connected to the server...");
3679
3680 DataInputStream read = new DataInputStream(System.in);
3681
3682 DataInputStream in = new DataInputStream(s.getInputStream());
3683 DataOutputStream out = new DataOutputStream(s.getOutputStream());
3684
3685 String line = null;
3686 String receiveline = null;
3687
3688 System.out.println("Enter data to send to the server: ");
3689
3690 do
3691 {
3692 System.out.print("CLIENT: ");
3693 line = read.readLine();
3694 out.writeUTF(line);
3695 out.flush();
3696
3697 receiveline = in.readUTF();
3698 System.out.println("SERVER: " + receiveline);
3699
3700 }while(!line.equals("bye"));
3701 }
3702 catch (Exception e)
3703 {
3704 e.printStackTrace();
3705 }
3706 }
3707}
3708
37098. Implement a simple message transfer from client to server process using UDP.
3710import java.io.*;
3711import java.net.*;
3712class UDPServerss {
3713public static void main(String args[]) throws Exception {
3714 DatagramSocket serverSocket = new DatagramSocket(9876);
3715
3716 byte[] receiveData = new byte[1024];
3717 byte[] sendData = new byte[1024];
3718 while(true) {
3719
3720 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
3721 serverSocket.receive(receivePacket);
3722 String sentence = new String( receivePacket.getData());
3723 System.out.println("RECEIVED: " + sentence);
3724 InetAddress IPAddress = receivePacket.getAddress();
3725 int port = receivePacket.getPort();
3726 String capitalizedSentence = sentence.toUpperCase();
3727 sendData = capitalizedSentence.getBytes();
3728 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
3729 serverSocket.send(sendPacket);
3730 }
3731}
3732}
3733import java.io.*;
3734import java.net.*;
3735 class UDPClientssss {
3736 public static void main(String args[]) throws Exception {
3737 BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
3738 DatagramSocket clientSocket = new DatagramSocket();
3739 InetAddress IPAddress = InetAddress.getByName("localhost");
3740 byte[] sendData = new byte[1024];
3741 byte[] receiveData = new byte[1024];
3742 String sentence = inFromUser.readLine();
3743 sendData = sentence.getBytes();
3744 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
3745 clientSocket.send(sendPacket);
3746 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
3747 clientSocket.receive(receivePacket);
3748 String modifiedSentence = new String(receivePacket.getData());
3749 System.out.println("FROM SERVER:" + modifiedSentence);
3750 clientSocket.close();
3751 }
3752 }
3753
37549. Write a program to implement an Echo UDP server. Test the working of the server by writing a client application.
3755import java.net.*;
3756 import java.util.*;
3757 public class EchoServer
3758{
3759 public static void main( String args[]) throws Exception
3760 {
3761 DatagramSocket dsock = new DatagramSocket(7);
3762byte arr1[] = new byte[150];
3763DatagramPacket dpack = new DatagramPacket(arr1, arr1.length );
3764while(true)
3765{ dsock.receive(dpack);
3766byte arr2[] = dpack.getData();
3767 int packSize = dpack.getLength();
3768String s2 = new String(arr2, 0, packSize);
3769System.out.println( new Date( ) + " " + dpack.getAddress( ) + " : " + dpack.getPort( ) + " "+ s2);
3770dsock.send(dpack);
3771}
3772}
3773}----------------------------------
3774import java.net.*;
3775import java.util.*;
3776 public class EchoClient
3777{ public static void main( String args[] ) throws Exception {
3778InetAddress add = InetAddress.getByName("127.0.0.1");
3779DatagramSocket dsock = new DatagramSocket( );
3780 String message1 = "This is client calling";
3781 byte arr[] = message1.getBytes( );
3782 DatagramPacket dpack = new DatagramPacket(arr, arr.length, add, 7);
3783 dsock.send(dpack); // send the packet
3784Date sendTime = new Date( ); // note the time of sending the message
3785dsock.receive(dpack); // receive the packet
3786String message2 = new String(dpack.getData( ));
3787 Date receiveTime = new Date( ); // note the time of receiving the message
3788 System.out.println((receiveTime.getTime( ) - sendTime.getTime( )) + " milliseconds echo time for " + message2);
3789 }
3790 }
3791
379210. 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.
3793import java.io.*;
3794import java.net.*;
3795public class UDPdiscardServer {
3796 public final static int DEFAULT_PORT=9;
3797 public final static int MAX_PACKET_SIZE=65507;
3798public static void main(String args[])
3799{
3800 int port=DEFAULT_PORT;
3801 byte[] buffer=new byte[MAX_PACKET_SIZE];
3802
3803 try{
3804 port=9;
3805 }
3806catch(Exception ex)
3807{}
3808 try{
3809 DatagramSocket server=new DatagramSocket(port);
3810DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
3811
3812while(true)
3813{
3814 try{
3815 server.receive(packet);
3816 String s=new String(packet.getData(),0,packet.getLength(),"UTF-8");
3817 System.out.println(packet.getAddress()+" at port "+packet.getPort()+" says "+s);
3818 packet.setLength(buffer.length);
3819 }
3820 catch(IOException ex){ System.err.println(ex);}
3821}
3822
3823 }
3824 catch(SocketException ex)
3825 {System.err.println(ex);}
3826}
3827}
3828import java.io.*;
3829import java.net.*;
3830public class UDPdiscardClient {
3831 public final static int DEFAULT_PORT=9;
3832
3833public static void main(String args[])
3834{String hostname="localhost";
3835 int port=DEFAULT_PORT;
3836
3837
3838 try{
3839 InetAddress server=InetAddress.getByName(hostname);
3840 BufferedReader userInput=new BufferedReader(new InputStreamReader(System.in));
3841 DatagramSocket theSocket=new DatagramSocket();
3842
3843 while(true)
3844 {
3845 String theLine=userInput.readLine();
3846 if(theLine.equals(".")) break;
3847 byte[] data=theLine.getBytes("UTF-8");
3848 DatagramPacket theOutput=new DatagramPacket(data,data.length,server,port);
3849 theSocket.send(theOutput);
3850 }
3851 }
3852 catch(UnknownHostException ex)
3853 {System.err.println(ex);}
3854 catch(SocketException ex)
3855 {System.err.println(ex);}
3856 catch(IOException ioex)
3857 {System.err.println(ioex);}
3858}
3859}
3860Find the physical address of a host when its logical address is known (ARP protocol) using TCP/IP.
3861
3862import java.net.InetAddress;
3863import java.net.NetworkInterface;
3864import java.net.SocketException;
3865import java.net.UnknownHostException;
3866import java.util.Scanner;
3867
3868public class MacAddress {
3869 public static void main(String[] args)
3870 {
3871 try
3872 {
3873 Scanner console = new Scanner(System.in);
3874 System.out.println("Enter System Name: ");
3875 String ipaddr = console.nextLine();
3876 InetAddress address = InetAddress.getByName(ipaddr);
3877 System.out.println("address = "+address);
3878 NetworkInterface ni = NetworkInterface.getByInetAddress(address);
3879 if (ni!=null)
3880 {
3881 byte[] mac = ni.getHardwareAddress();
3882 if (mac != null)
3883 {
3884 System.out.print("MAC Address : ");
3885 for (int i=0; i<mac.length; i++)
3886 {
3887 System.out.format("%02X%s", mac[i], (i<mac.length - 1) ? "-" :"");
3888 }
3889 }
3890 else
3891 {
3892 System.out.println("Address doesn't exist or is not accessible/");
3893
3894 }
3895 }
3896 else
3897 {
3898 System.out.println("Network Interface for the specified address is not found");
3899 }
3900 }
3901 catch(UnknownHostException he)
3902 {
3903 }
3904 catch(SocketException e)
3905 {
3906 }
3907 }
3908}
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
3920basics
3921Basic network commands
3922ping
3923The ping command (named after the sound of an active sonar system) sends echo requests to the host
3924specified on the command line, and lists the responses received.
3925$ ping ipAddress or hostname
3926e.g
3927$ ping www.vit.ac.in
3928 ping - sends an ICMP ECHO_REQUEST packet to the specified host. If the host responds, an
3929ICMP packet is received.
3930 One can ping an IP address to see if a machine is alive.
3931 It provides a very quick way to see if a machine is up and connected to the network.
3932netstat
3933 It works with the LINUX Network Subsystem, it will tell you what the status of ports are ie. open,
3934closed, waiting connections. It is used to display the TCP/IP network protocol statistics and
3935information.
3936tcpdump
3937This is a sniffer, a program that captures packets off a network interface and interprets them.
3938hostname
3939Tells the user the host name of the computer they are logged into.
3940traceroute
3941traceroute will show the route of a packet. It attempts to list the series of hosts through which your
3942packets travel on their way to a given destination.
3943Command syntax:
3944traceroute machine_name_or_ip
3945e.g traceroute www.vit.ac.in
3946Each host will be displayed, along with the response times at each host.
3947finger
3948Retrieves information about the specified user.
3949e.g finger bit50001
3950ifconfig ( In Windows use ipconfig )
3951This command is used to configure network interfaces, or to display their current configuration.
3952dig
3953The "domain information groper" tool. If you give a hostname as an argument to output information
3954about that host, including it's IP address, hostname and various other information.
3955e.g dig vitlinux
3956telnet
3957telnet allows you to log in to a computer, just as if you were sitting at the terminal. Once your
3958username and password are verified, you are given a shell prompt. From here, you can do anything
3959requiring a text console.
3960ftp
3961To connect to an FTP server use
3962ftp ipaddress
3963netstat
3964Displays contents of /proc/net files. It works with the LINUX Network Subsystem, it will tell
3965you what the status of ports are ie. open, closed, waiting, masquerade connections. It will also
3966display various other things. It has many different options.
3967tcpdump
3968This is a sniffer, a program that captures packets off a network interface and interprets them
3969for you. It understands all basic internet protocols, and can be used to save entire packets for
3970later inspection.
3971ping
3972The ping command (named after the sound of an active sonar system) sends echo requests to
3973the host you specify on the command line, and lists the responses received their round trip
3974time.
3975You simply use ping as:
3976ping ip_or_host_name
3977hostname
3978Tells the user the host name of the computer they are logged into. Note: may be called host.
3979traceroute
3980traceroute will show the route of a packet. It attempts to list the series of hosts through which
3981your packets travel on their way to a given destination. Also have a look at xtraceroute (one
3982of several graphical equivalents of this program).
3983Command syntax:
3984traceroute machine_name_or_ip
3985tracepath
3986tracepath performs a very simlar function to traceroute the main difference is that tracepath
3987doesn't take complicated options.
3988Command syntax:
3989tracepath machine_name_or_ip
3990findsmb
3991findsmb is used to list info about machines that respond to SMB name queries (for example
3992windows based machines sharing their hard disk's).
3993Command syntax:
3994Findsmb
3995This would find all machines possible, you may need to specify a particular subnet to query
3996those machines only...
3997nmap
3998 network exploration tool and security scanner. nmap is a very advanced network tool used
3999to query machines (local or remote) as to whether they are up and what ports are open on
4000these machines.
4001A simple usage example:
4002nmap machine_name
4003This would query your own machine as to what ports it keeps open. nmap is a very powerful
4004tool, documentation is available on the nmap site as well as the information in the manual
4005page.
4006telnet
4007Someone once stated that telnet(1) was the coolest thing he had ever seen on computers. The ability
4008to remotely log in and do stuff on another computer is what separates Unix and Unix-like operating
4009systems from other operating systems.
4010telnet allows you to log in to a computer, just as if you were sitting at the terminal. Once your
4011username and password are verified, you are given a shell prompt. From here, you can do anything
4012requiring a text console. Compose email, read newsgroups, move files around, and so on. If you are
4013running X and you telnet to another machine, you can run X programs on the remote computer and
4014display them on yours.
4015To login to a remote machine, use this syntax:
4016% telnet <hostname>
4017If the host responds, you will receive a login prompt. Give it your username and password. That's it.
4018You are now at a shell. To quit your telnet session, use either the exit command or the logout
4019command.
4020telnet does not encrypt the information it sends. Everything is sent in plain text, even passwords.
4021It is not advisable to use telnet over the Internet. Instead, consider the Secure Shell. It encrypts
4022all traffic and is available for free.
4023The other use of telnet
4024Now that we have convinced you not to use the telnet protocol anymore to log into a remote machine,
4025we'll show you a couple of useful ways to use telnet.
4026You can also use the telnet command to connect to a host on a certain port.
4027% telnet <hostname> [port]
4028This can be quite handy when you quickly need to test a certain service, and you need full control
4029over the commands, and you need to see what exactly is going on. You can interactively test or use
4030an SMTP server, a POP3 server, an HTTP server, etc. this way.
4031In the next figure you'll see how you can telnet to a HTTP server on port 80, and get some basic
4032information from it.
4033Figure 13-1. Telnetting to a webserver
4034% telnet store.slackware.com 80
4035Trying 69.50.233.153...
4036Connected to store.slackware.com.
4037Escape character is '^]'.
4038HEAD / HTTP/1.0
4039HTTP/1.1 200 OK
4040Date: Mon, 25 Apr 2005 20:47:01 GMT
4041Server: Apache/1.3.33 (Unix) mod_ssl/2.8.22 OpenSSL/0.9.7d
4042Last-Modified: Fri, 18 Apr 2003 10:58:54 GMT
4043ETag: "193424-c0-3e9fda6e"
4044Accept-Ranges: bytes
4045Content-Length: 192
4046Connection: close
4047Content-Type: text/html
4048Connection closed by foreign host.
4049%
40501-)arp :
4051When we need an Ethernet (MAC) address we can use arp(address resolution protocol).
4052In other words it shows the physical address of an host.
4053Example:
4054C:\Documents and Settings\sysadm>arp -a
4055Interface: 169.254.195.199 --- 0x2
4056Internet Address Physical Address Type
4057216.109.127.60 00-53-45-00-00-00 static
40582-)nslookup:
4059Displays information from Domain Name System (DNS) name servers.
4060Example:
4061C:\Documents and Settings\sysadm>nslookup itu.dk
4062Server: ns3.inet.tele.dk
4063Address: 193.162.153.164
4064Non-authoritative answer:
4065Name: itu.dk
4066Address: 130.226.133.2
4067NOTE :If you write the command as above it shows as default your pc's server name firstly.
4068C:\Documents and Settings\sysadm>nslookup mail.yahoo.com itu.dk
4069Server: superman.itu.dk
4070Address: 130.226.133.2
4071Non-authoritative answer:
4072Name: login.yahoo.akadns.net
4073Address: 216.109.127.60
4074Aliases: mail.yahoo.com, login.yahoo.com
4075NOTE:Remark that in the second example we do not see the default server name.
4076There are many nslookup with optional commands.To read them type nslookup and enter
4077then type help and enter.
40783-)finger:
4079Displays the information about a user on the system.
4080Example:
4081NOTE :I could not find out the name of the server that we log on (windows) at the school.
4082Sysadmin does not know that either:o)
4083But as an example I tried it on the our unix server.
4084[hilmiolgun@ssh hilmiolgun]$ finger
4085Login Name Tty Idle Login Time Office Office Phone
4086adel Adel Abu-Sharkh pts/1 7 Sep 10 00:11 (cpe.atm2-0-
40871091080.0x50a0bcb2.albnxx13.customer.tele.dk)
4088adel Adel Abu-Sharkh pts/2 9 Sep 9 23:56 (cpe.atm2-0-
40891091080.0x50a0bcb2.albnxx13.customer.tele.dk)
4090hilmiolgun Hilmi Olgun pts/9 Sep 10 00:20 (0x3ef3e2fe.albnxx8.adsl.tele.dk)
4091hm Hanne Munkholm pts/6 1:56 Sep 8 21:27 (off180.palombia.dk)
4092jcg Jens Christian Godsk pts/4 1d Sep 8 10:28 (toscana.itu.dk)
4093kaj Kenneth Ahn Jensen pts/7 Sep 10 00:11 (cpe.atm2-0-
409454493.0x50a4ad32.boanxx12.customer.tele.dk)
4095root root pts/8 1 Sep 10 00:12 (sysadm2.itu.dk)
4096troels Troels Arvin pts/5 3:49 Sep 9 20:31 (62.79.119.132.adsl.vbr.worldonline.dk)
4097webclaus Claus Bech Rasmussen pts/0 6 Sep 10 00:11 (port967.ds1-khk.adsl.cybercity.dk)
4098NOTE :What I did is :I first check the online users,and get a list of them(above).
4099Then i just choosed one user to get information about him(below)
4100[hilmiolgun@ssh hilmiolgun]$ finger hm
4101Login: hm Name: Hanne Munkholm
4102Directory: /import/home/hm Shell: /bin/bash
4103On since Mon Sep 8 21:27 (CEST) on pts/6 from off180.palombia.dk
41041 hour 56 minutes idle
4105Last login Tue Sep 9 11:05 (CEST) on pts/12 from stud127.itu.dk
4106New mail received Mon Nov 11 23:01 2002 (CET)
4107Unread since Sat Oct 5 00:00 2002 (CEST)
4108Plan:
4109World Domination... fast.
4110[hilmiolgun@ssh hilmiolgun]$
41114-)ping:
4112Simpy shows if the remote machine is available or not....
4113Example:
4114C:\Documents and Settings\sysadm>ping webmail.itu.dk
4115Pinging tarzan.itu.dk [130.226.133.3] with 32 bytes of data:
4116Reply from 130.226.133.3: bytes=32 time=29ms TTL=55
4117Reply from 130.226.133.3: bytes=32 time=30ms TTL=55
4118Reply from 130.226.133.3: bytes=32 time=30ms TTL=55
4119Reply from 130.226.133.3: bytes=32 time=30ms TTL=55
4120Ping statistics for 130.226.133.3:
4121Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
4122Approximate round trip times in milli-seconds:
4123Minimum = 29ms, Maximum = 30ms, Average = 29ms
4124NOTE :Remark that the remote machine is replying.Otherwise the output will be "Request time out"
4125which means the
4126remote machine is not working well.(Not answering)
41275-)tracert:
4128It simply shows the path between source and destination address.
4129Example:
4130C:\Documents and Settings\sysadm>tracert webmail.itu.dk
4131Tracing route to tarzan.itu.dk [130.226.133.3]
4132over a maximum of 30 hops:
41331 * * * Request timed out.
41342 29 ms 19 ms 29 ms ge-0-2-1-2.1000M.albnxu1.ip.tele.dk [195.249.1.2 9]
41353 29 ms 29 ms 19 ms pos1-0.622M.lynxg1.ip.tele.dk [195.249.2.46]
41364 29 ms 19 ms 29 ms herman.fsknet.lyngby.forskningsnettet.dk [192.38 .7.1]
41375 29 ms 29 ms 19 ms 130.225.244.214
41386 29 ms 29 ms 29 ms 1.ku.forskningsnettet.dk [130.225.245.90]
41397 29 ms 29 ms 29 ms rk.itu.forskningsnettet.dk [130.226.249.30]
41408 29 ms 29 ms 29 ms 130.225.245.86
41419 29 ms 29 ms 29 ms tarzan.itu.dk [130.226.133.3]
4142Trace complete.
41436-)ftp:
4144For file transferring..(File transfer protocol)
4145Example:Lets you dont have an ftp software and you want to get a file from your school harddisk.
4146So to do that:
4147C:\Documents and Settings\sysadm>ftp
4148ftp> open
4149To ftp.itu.dk
4150Connected to ssh.itu.dk.
4151220 ProFTPD 1.2.8rc2 Server (ProFTPD Default Installation) [ssh.it-c.dk]
4152NOTE:What am I doing is simply:typing them one-by-one(after each typing remember to enter)
4153ftp,open,ftp.itu.dk
4154User (ssh.itu.dk:(none)): hilmiolgun
4155331 Password required for hilmiolgun.
4156Password:
4157230 User hilmiolgun logged in.
4158NOTE:The server will require username and password..
4159ftp> help
4160Commands may be abbreviated. Commands are:
4161! delete literal prompt send
4162? debug ls put status
4163append dir mdelete pwd trace
4164ascii disconnect mdir quit type
4165bell get mget quote user
4166binary glob mkdir recv verbose
4167bye hash mls remotehelp
4168cd help mput rename
4169close lcd open rmdir
4170ftp> help dir
4171dir List contents of remote directory
4172NOTE: If it is your first time to those commands just type help and get the commands.If you dont
4173know how to use
4174them type help commandname..
4175ftp> dir
4176200 PORT command successful
4177150 Opening ASCII mode data connection for file list
4178drwx------ 4 hilmiolgun hilmiolgun 155 Jul 1 14:02 Desktop
4179drwx------ 2 hilmiolgun hilmiolgun 4096 May 30 10:21 Mail
4180drwxr-xr-x 5 hilmiolgun hilmiolgun 90 Sep 2 02:59 MobilePositionSDK
4181drwx------ 7 hilmiolgun hilmiolgun 4096 Aug 8 2002 NTnetscape
4182drwxr--r-- 13 hilmiolgun hilmiolgun 4096 Sep 4 01:56 New Folder
4183-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 TTI409B
4184drwx------ 2 hilmiolgun hilmiolgun 6 Jan 21 2002 cgi-bin
4185-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 geu
4186-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 hilmiolgun
4187drwxr-xr-x 6 hilmiolgun hilmiolgun 4096 Aug 14 15:59 image
4188drwxr-xr-x 3 hilmiolgun hilmiolgun 4096 Jul 29 16:03 jmf20-apidocs
4189drwxr-xr-x 4 hilmiolgun hilmiolgun 4096 Sep 9 14:10 NOTEsieee
4190drwx------ 2 hilmiolgun hilmiolgun 6 Feb 21 2002 nsmail
4191drwx------ 3 hilmiolgun hilmiolgun 103 Feb 21 2002 office52
4192drwx------ 2 hilmiolgun hilmiolgun 6 Jan 21 2002 private
4193drwxr--rwx 2 hilmiolgun hilmiolgun 4096 Aug 23 12:02 public_html
4194drwxr-xr-x 5 hilmiolgun hilmiolgun 4096 Sep 6 03:30 speech
4195-rw-rw-r-- 1 hilmiolgun hilmiolgun 2630 Sep 9 13:58 test.txt
4196-rw-rw-r-- 1 hilmiolgun hilmiolgun 148 Sep 9 14:03 testing.txt
4197226 Transfer complete.
4198ftp: 1318 bytes received in 0,24Seconds 5,49Kbytes/sec.
4199ftp> get testing.txt
4200200 PORT command successful
4201150 Opening ASCII mode data connection for testing.txt (148 bytes)
4202226 Transfer complete.
4203ftp: 161 bytes received in 0,02Seconds 8,05Kbytes/sec.
4204NOTE :After taking a look to the school harddisk ,I copied a file "testing.txt" to my local harddisk....
4205ftp> !dir
4206Volume in drive C has no label.
4207Volume Serial Number is 0868-D52D
4208Directory of C:\Documents and Settings\sysadm
420910-09-2003 00:21 <DIR> .
421010-09-2003 00:21 <DIR> ..
421131-08-2003 07:28 <DIR> .java
421225-04-2003 12:18 <DIR> .javaws
421323-04-2003 15:26 <DIR> .jpi_cache
421426-08-2003 04:59 <DIR> .Nokia
421507-09-2003 01:46 12.546 .plugin140_03.trace
421607-09-2003 04:46 693 .plugin141_02.trace
421707-09-2003 01:20 164 .saves-3824-IBMR31IMAGE
421807-09-2003 01:20 <DIR> Desktop
421907-09-2003 08:05 <DIR> Favorites
422006-09-2003 05:29 80.140 love.wav
422109-09-2003 23:45 <DIR> mindterm
422209-09-2003 11:02 <DIR> My Documents
422310-09-2003 00:21 2.903 plugin131_08.trace
422425-04-2003 11:44 <DIR> Start Menu
422506-09-2003 21:21 <DIR> studio5se_user
422606-09-2003 05:32 18 test.txt
422706-09-2003 05:20 70 testing
422810-09-2003 00:37 161 testing.txt
422926-08-2003 03:46 <DIR> WINDOWS
42308 File(s) 96.695 bytes
423113 Dir(s) 3.842.056.192 bytes free
4232ftp> send love.wav
4233200 PORT command successful
4234150 Opening ASCII mode data connection for love.wav
4235226 Transfer complete.
4236ftp: 80140 bytes sent in 3,97Seconds 20,21Kbytes/sec.
4237ftp> dir
4238200 PORT command successful
4239150 Opening ASCII mode data connection for file list
4240drwx------ 4 hilmiolgun hilmiolgun 155 Jul 1 14:02 Desktop
4241drwx------ 2 hilmiolgun hilmiolgun 4096 May 30 10:21 Mail
4242drwxr-xr-x 5 hilmiolgun hilmiolgun 90 Sep 2 02:59 MobilePositionSDK
4243drwx------ 7 hilmiolgun hilmiolgun 4096 Aug 8 2002 NTnetscape
4244drwxr--r-- 13 hilmiolgun hilmiolgun 4096 Sep 4 01:56 New Folder
4245-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 TTI409B
4246drwx------ 2 hilmiolgun hilmiolgun 6 Jan 21 2002 cgi-bin
4247-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 geu
4248-rw-rw-r-- 1 hilmiolgun hilmiolgun 74 Sep 9 12:56 hilmiolgun
4249drwxr-xr-x 6 hilmiolgun hilmiolgun 4096 Aug 14 15:59 image
4250drwxr-xr-x 3 hilmiolgun hilmiolgun 4096 Jul 29 16:03 jmf20-apidocs
4251-rw-rw-r-- 1 hilmiolgun hilmiolgun 80137 Sep 9 22:36 love.wav
4252drwxr-xr-x 4 hilmiolgun hilmiolgun 4096 Sep 9 14:10 NOTEsieee
4253drwx------ 2 hilmiolgun hilmiolgun 6 Feb 21 2002 nsmail
4254drwx------ 3 hilmiolgun hilmiolgun 103 Feb 21 2002 office52
4255drwx------ 2 hilmiolgun hilmiolgun 6 Jan 21 2002 private
4256drwxr--rwx 2 hilmiolgun hilmiolgun 4096 Aug 23 12:02 public_html
4257drwxr-xr-x 5 hilmiolgun hilmiolgun 4096 Sep 6 03:30 speech
4258-rw-rw-r-- 1 hilmiolgun hilmiolgun 2630 Sep 9 13:58 test.txt
4259-rw-rw-r-- 1 hilmiolgun hilmiolgun 148 Sep 9 14:03 testing.txt
4260226 Transfer complete.
4261ftp: 1387 bytes received in 0,07Seconds 19,81Kbytes/sec.
4262ftp>
4263NOTE:At the end first looking at the local working directory and sending a file "love.wav" to the
4264school harddisk.
42657-)net:
4266It has many options,which are for checking/starting/stopping nt
4267services,users,messaging,configuration and so on...
4268Some of those options require administration privileges..
4269Example:
4270NOTE: To have an overview of commands options....
4271C:\Documents and Settings\sysadm>net
4272The syntax of this command is:
4273NET COMMANDS
4274NET [ ACCOUNTS | COMPUTER | CONFIG | CONTINUE | FILE | GROUP | HELP |
4275HELPMSG | LOCALGROUP | NAME | PAUSE | PRINT | SEND | SESSION |
4276SHARE | START | STATISTICS | STOP | TIME | USE | USER | VIEW ]
4277NOTE: And furthermore to get an overview of a specific option ...
4278C:\Documents and Settings\sysadm>net help print
4279The syntax of this command is:
4280NET PRINT
4281\\computername\sharename
4282[\\computername] job# [/HOLD | /RELEASE | /DELETE]
4283NET PRINT displays print jobs and shared queues.
4284For each queue, the display lists jobs, showing the size
4285and status of each job, and the status of the queue.
4286\\computername Is the name of the computer sharing the printer
4287queue(s).
4288sharename Is the name of the shared printer queue.
4289job# Is the identification number assigned to a print
4290job. A computer with one or more printer queues
4291assigns each print job a unique number.
4292/HOLD Prevents a job in a queue from printing.
4293The job stays in the printer queue, and other
4294jobs bypass it until it is released.
4295/RELEASE Reactivates a job that is held.
4296/DELETE Removes a job from a queue.
4297NET HELP command | MORE displays Help one screen at a time.
4298Finally in addition to above there are also those commands: hostname ,lpq, lpr ,rsh ,tftp ,nbstat
4299,netstat.
4300To get familiar with those commands simply type commandname /? at the command line.
4301C:\>net
4302The syntax of this command is:
4303NET [ ACCOUNTS | COMPUTER | CONFIG | CONTINUE | FILE | GROUP | HELP |
4304HELPMSG | LOCALGROUP | NAME | PAUSE | PRINT | SEND | SESSION |
4305SHARE | START | STATISTICS | STOP | TIME | USE | USER | VIEW ]
4306C:\>net use
4307New connections will not be remembered.
4308Status Local Remote Network
4309-------------------------------------------------------------------------------
4310OK F: \\cse-sec\fac Microsoft Windows Network
4311C:\>net user
4312User accounts for \\CSE-DEPT-05
4313-------------------------------------------------------------------------------
4314Administrator Guest
4315C:\>net statistics
4316Statistics are available for the following running services:
4317Server
4318Workstation
4319Displays protocol statistics and current TCP/IP network connections.
4320NETSTAT [-a] [-e] [-n] [-s] [-p proto] [-r] [interval]
4321-a Displays all connections and listening ports.
4322-e Displays Ethernet statistics. This may be combined with the
4323-s option.
4324-n Displays addresses and port numbers in numerical form.
4325-p proto Shows connections for the protocol specified by proto; proto
4326may be TCP or UDP. If used with the -s option to display
4327per-protocol statistics, proto may be TCP, UDP, or IP.
4328-r Displays the routing table.
4329-s Displays per-protocol statistics. By default, statistics
4330are shown for TCP, UDP and IP; the -p option may be used
4331to specify a subset of the default.
4332interval Redisplays selected statistics, pausing interval seconds
4333between each display. Press CTRL+C to stop redisplaying
4334statistics. If omitted, netstat will print the current
4335configuration information once.
4336C:\>net name
4337Name
4338-------------------------------------------------------------------------------
4339CSE-DEPT-05
4340C:\>net session
4341Computer User name Client Type Opens Idle time
4342-------------------------------------------------------------------------------
4343\\ENGLISH-03 Windows NT 1381 0 00:10:47
4344\\ENGLISHBDC Windows NT 1381 0 00:02:01
4345C:\>net accounts
4346Force user logoff how long after time expires?: Never
4347Minimum password age (days): 0
4348Maximum password age (days): 42
4349Minimum password length: 0
4350Length of password history maintained: None
4351Lockout threshold: Never
4352Lockout duration (minutes): 30
4353Lockout observation window (minutes): 30
4354Computer role: WORKSTATION
4355C:\>net localgroup
4356Aliases for \\CSE-DEPT-05
4357-------------------------------------------------------------------------------
4358*Administrators *Backup Operators *Guests
4359*Power Users *Replicator *Users
4360C:\>net config server
4361Server Name \\CSE-DEPT-05
4362Server Comment
4363Software version Windows NT 4.0
4364Server is active on NetBT_DLKRTS1 (0050ba8b326b) NetBT_DLKRTS1
4365(0050ba8b326b) NwlnkIpx (0050ba8b326b) NwlnkNb (0050ba8b326b) Nbf_DLKRTS1 (0050
4366ba8b326b)
4367Server hidden No
4368Maximum Logged On Users 10
4369Maximum open files per session 2048
4370Idle session time (min) 15
4371C:\>net config workstation
4372Computer name \\CSE-DEPT-05
4373User name Administrator
4374Workstation active on NwlnkNb (0050BA8B326B) NetBT_DLKRTS1 (0050B
4375A8B326B) Nbf_DLKRTS1 (0050BA8B326B)
4376Software version Windows NT 4.0
4377Workstation domain WORKGROUP
4378Logon domain CSE-DEPT-05
4379COM Open Timeout (sec) 3600
4380COM Send Count (byte) 16
4381COM Send Timeout (msec) 250
4382C:\>net share
4383Share name Resource Remark
4384-------------------------------------------------------------------------------
4385D$ D:\ Default share
4386IPC$ Remote IPC
4387C$ C:\ Default share
4388ADMIN$ C:\WINNT Remote Admin
4389E$ E:\ Default share
4390abishek E:\abishek
4391akshu E:\akshu
4392HARSHINI D:\ HARSHINI
4393DHARSHINI E:\ DHARSHINI
4394C:\>net stop messenger
4395The Messenger service is stopping.
4396The Messenger service was stopped successfully.
4397C:\>net start messenger
4398The Messenger service is starting...
4399The Messenger service was started successfully.
4400Network Configuration commands
4401ifconfig
4402This command is used to configure network interfaces, or to display their current
4403configuration. In addition to activating and deactivating interfaces with the up and down
4404settings, this command is necessary for setting an interface's address information if you don't
4405have the ifcfg script.
4406Use ifconfig as either:
4407ifconfig
4408This will simply list all information on all network devices currently up.
4409ifconfig eth0 down
4410This will take eth0 (assuming the device exists) down, it won't be able to receive or send
4411anything until you put the device back up again.
4412Clearly there are a lot more options for this tool, you will need to read the manual/info page to
4413learn more about them.
4414ifup
4415Use ifup device-name to bring an interface up by following a script (which will contain your
4416default networking settings). Simply type ifup and you will get help on using the script.
4417For example typing:
4418ifup eth0
4419Will bring eth0 up if it is currently down.
4420ifdown
4421Use ifdown device-name to bring an interface down using a script (which will contain your
4422default network settings). Simply type ifdown and you will get help on using the script.
4423For example typing:
4424ifdown eth0
4425Will bring eth0 down if it is currently up.
4426ifcfg
4427Use ifcfg to configure a particular interface. Simply type ifcfg to get help on using this script.
4428For example, to change eth0 from 192.168.0.1 to 192.168.0.2 you could do:
4429ifcfg eth0 del 192.168.0.1
4430ifcfg eth0 add 192.168.0.2
4431The first command takes eth0 down and removes that stored IP address and the second one
4432brings it back up with the new address.
4433route
4434The route command is the tool used to display or modify the routing table. To add a gateway
4435as the default you would type:
4436route add default gw some_computer
4437INTERNET SPECIFIC COMMANDS
4438host
4439Performs a simple lookup of an internet address (using the Domain Name System, DNS).
4440Simply type:
4441host ip_address
4442or
4443host domain_name
4444dig
4445The "domain information groper" tool. More advanced then host... If you give a hostname as
4446an argument to output information about that host, including it's IP address, hostname and
4447various other information.
4448For example, to look up information about www.amazon.com type:
4449dig www.amazon.com
4450To find the host name for a given IP address (ie a reverse lookup), use dig with the `-x' option.
4451dig -x 100.42.30.95
4452This will look up the address (which may or may not exist) and returns the address of the
4453host, for example if that was the address of http://slashdot.org then it would return
4454http://slashdot.org.
4455dig takes a huge number of options (at the point of being too many), refer to the manual page
4456for more information.
4457whois
4458(now BW whois) is used to look up the contact information from the whois databases, the
4459servers are only likely to hold major sites. Note that contact information is likely to be hidden
4460or restricted as it is often abused by crackers and others looking for a way to cause malicious
4461damage to organisation's.
4462wget
4463(GNU Web get) used to download files from the World Wide Web.
4464To archive a single web-site, use the -m or --mirror (mirror) option.
4465Use the -nc (no clobber) option to stop wget from overwriting a file if you already have it.
4466Use the -c or --continue option to continue a file that was unfinished by wget or another
4467program.
4468Simple usage example:
4469wget url_for_file
4470This would simply get a file from a site.
4471wget can also retrieve multiple files using standard wildcards, the same as the type used in
4472bash, like *, [ ], ?. Simply use wget as per normal but use single quotation marks (' ') on the
4473URL to prevent bash from expanding the wildcards. There are complications if you are
4474retrieving from a http site (see below...).
4475Advanced usage example, (used from wget manual page):
4476wget --spider --force-html -i bookmarks.html
4477This will parse the file bookmarks.html and check that all the links exist.
4478Advanced usage: this is how you can download multiple files using http (using a wildcard...).
4479Notes: http doesn't support downloading using standard wildcards, ftp does so you may use
4480wildcards with ftp and it will work fine. A work-around for this http limitation is shown
4481below:
4482wget -r -l1 --no-parent -A.gif http://www.website.com[1]
4483This will download (recursively), to a depth of one, in other words in the current directory and
4484not below that. This command will ignore references to the parent directory, and downloads
4485anything that ends in .gif. If you wanted to download say, anything that ends with .pdf as
4486well than add a -A.pdf before the website address. Simply change the website address and the
4487type of file being downloaded to download something else. Note that doing -A.gif is the same
4488as doing -A *.gif (double quotes only, single quotes will not work).
4489wget has many more options refer to the examples section of the manual page, this tool is very
4490well documented.
4491Alternative website downloaders: You may like to try alternatives like httrack. A full GUI
4492website downloader written in python and available for GNU/Linux
4493curl
4494curl is another remote downloader. This remote downloader is designed to work without user
4495interaction and supports a variety of protocols, can upload/download and has a large number
4496of tricks/work-arounds for various things. It can access dictionary servers (dict), ldap servers,
4497ftp, http, gopher, see the manual page for full details.
4498To access the full manual (which is huge) for this command type:
4499curl -M
4500For general usage you can use it like wget. You can also login using a user name by using the
4501-u option and typing your username and password like this:
4502curl -u username:password http://www.placetodownload/file
4503To upload using ftp you the -T option:
4504curl -T file_name ftp://ftp.uploadsite.com
4505To continue a file use the -C option:
4506curl -C - -o file http://www.site.com
4507View and modify network interfaces
4508ifconfig -a Show information about all network interfaces
4509ifconfig eth0 Show information only about the interface eth0
4510ifconfig eth0 up Bring up the interface eth0
4511ifconfig eth0 down Take down the interface eth0
4512Simple network diagnostic commands
4513ping hostname Send ICMP echo requests to the host hostname
4514traceroute hostname Trace the network path to hostname
4515View open network connections
4516netstat -a Show information about all open network connections
4517netstat -a | grep LISTEN Show information about all open network ports
4518Set/view routing information
4519netstat -r View system routing tables
4520route View system routing tables
4521The command route can also be used to add or delete routes. Examples:
4522route add -host 192.168.3.4 gw 192.168.3.1 netmask 255.255.0.0
4523route del -host 192.168.3.4
4524NETSTAT.exe TCP/IP Network Statistics
4525Displays protocol statistics and current TCP/IP network connections.
4526NETSTAT [-a] [-e] [-n] [-s] [-p proto] [-r] [interval]
4527-a Displays all connections and listening ports.
4528-e Displays Ethernet statistics. This may be combined with the -s option.
4529-n Displays addresses and port numbers in numerical form.
4530-p proto Shows connections for the protocol specified by proto; proto may be TCP or UDP.
4531If used with the -s option to display per-protocol statistics, proto may be TCP, UDP,
4532or IP.
4533-r Displays the routing table.
4534-s Displays per-protocol statistics. By default, statistics are shown for TCP, UDP and IP;
4535the -p option may be used to specify a subset of the default.
4536interval Redisplays selected statistics, pausing interval seconds between each display. Press
4537CTRL+C to stop redisplaying statistics. If omitted, netstat will print the current
4538configuration information once.
4539C:\WINDOWS>netstat -a
4540Active Connections
4541Proto Local Address Foreign Address State
4542TCP My_Comp:ftp localhost:0 LISTENING
4543TCP My_Comp:80 localhost:0 LISTENING
4544Or with the "-an" parameters:
4545C:\WINDOWS>netstat -an
4546Active Connections
4547Proto Local Address Foreign Address State
4548TCP 0.0.0.0:21 0.0.0.0:0 LISTENING
4549TCP 0.0.0.0:80 0.0.0.0:0 LISTENING
4550By simply opening a browser connection to both the HTTP (port 80) and FTP (port 21) servers
4551(while still offline!), I saw the following:
4552C:\WINDOWS>netstat -a
4553Active Connections
4554Proto Local Address Foreign Address State
4555TCP My_Comp:ftp localhost:0 LISTENING
4556TCP My_Comp:80 localhost:0 LISTENING
4557TCP My_Comp:1104 localhost:0 LISTENING
4558TCP My_Comp:ftp localhost:1104 ESTABLISHED
4559TCP My_Comp:1102 localhost:0 LISTENING
4560TCP My_Comp:1103 localhost:0 LISTENING
4561TCP My_Comp:80 localhost:1111 TIME_WAIT
4562TCP My_Comp:1104 localhost:ftp ESTABLISHED
4563TCP My_Comp:1107 localhost:0 LISTENING
4564TCP My_Comp:1112 localhost:80 TIME_WAIT
4565UDP My_Comp:1102 *:*
4566UDP My_Comp:1103 *:*
4567UDP My_Comp:1107 *:*
4568This may be a bit confusing to some people, but remember I'm running BOTH the servers and clients
4569on the same machine in these examples. A little later (using both 'a' and 'n') I got this:
4570C:\WINDOWS>netstat -an
4571Active Connections
4572Proto Local Address Foreign Address State
4573TCP 0.0.0.0:21 0.0.0.0:0 LISTENING
4574TCP 0.0.0.0:80 0.0.0.0:0 LISTENING
4575TCP 0.0.0.0:1104 0.0.0.0:0 LISTENING
4576TCP 127.0.0.1:21 127.0.0.1:1104 FIN_WAIT_2
4577TCP 127.0.0.1:1102 0.0.0.0:0 LISTENING
4578TCP 127.0.0.1:1103 0.0.0.0:0 LISTENING
4579TCP 127.0.0.1:1104 127.0.0.1:21 CLOSE_WAIT
4580TCP 127.0.0.1:1107 0.0.0.0:0 LISTENING
4581UDP 127.0.0.1:1102 *:*
4582UDP 127.0.0.1:1103 *:*
4583UDP 127.0.0.1:1107 *:*
4584After turning off my server, I ended up with this for a while:
4585C:\WINDOWS>netstat -an
4586Active Connections
4587Proto Local Address Foreign Address State
4588TCP 127.0.0.1:80 127.0.0.1:1150 TIME_WAIT
4589TCP 127.0.0.1:80 127.0.0.1:1151 TIME_WAIT
4590PING.exe
4591Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
4592[-r count] [-s count] [[-j host-list] | [-k host-list]]
4593[-w timeout] destination-list
4594Options:
4595-t Ping the specifed host until interrupted.
4596-a Resolve addresses to hostnames.
4597-n count Number of echo requests to send.
4598-l size Send buffer size.
4599-f Set "Don't Fragment" flag in packet.
4600-i TTL Time To Live.
4601-v TOS Type Of Service.
4602-r count Record route for count hops.
4603-s count Timestamp for count hops.
4604-j host-list Loose source route along host-list.
4605-k host-list Strict source route along host-list.
4606-w timeout Timeout in milliseconds to wait for each reply.
4607There's one special IP number everyone should know about:
4608127.0.0.1 - localhost (or loopback).
4609This is used to connect ( through a browser, for example) to a Web server on your own computer.
4610(127 being reserved for this purpose.) You can use this IP number at all times. It doesn't matter if
4611you're connected to the Internet or not.
4612It's also called the loopback address because you can ping it and get returns even when you're
4613offline (not connected to any network). If you don't get any valid replies, then there's a problem with
4614the computer's Network settings. Here's a typical response to the 'ping' command:
4615Here's another recent example using the name of my computer which I have tied to the IP number
4616127.0.0.1 in my C:\WINDOWS\HOSTS file:
4617C:\WINDOWS>ping My_Comp
4618Pinging My_Comp [127.0.0.1] with 32 bytes of data:
4619Reply from 127.0.0.1: bytes=32 time=1ms TTL=128
4620Reply from 127.0.0.1: bytes=32 time=1ms TTL=128
4621Reply from 127.0.0.1: bytes=32 time<10ms TTL=128
4622Reply from 127.0.0.1: bytes=32 time=1ms TTL=128
4623Ping statistics for 127.0.0.1:
4624Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
4625Approximate round trip times in milli-seconds:
4626Minimum = 0ms, Maximum = 1ms, Average = 0ms
4627TRACERT.exe Trace Route
4628Usage:
4629tracert [-d] [-h maximum_hops] [-j host-list] [-w timeout] target_name
4630Options:
4631-d Do not resolve addresses to hostnames.
4632-h maximum_hops Maximum number of hops to search for target.
4633-j host-list Loose source route along host-list.
4634-w timeout Wait timeout milliseconds for each reply.
4635Here's an example which traces the route from some ISP in Los Angeles to the main server at UCLA
4636in California ( note how two computers relatively close to each other may be routed way round
4637about! ):
4638C:\WINDOWS>tracert www.ucla.edu
4639Tracing route to www.ucla.edu [169.232.33.129]
4640over a maximum of 30 hops:
46411 141 ms 132 ms 140 ms wla-ca-pm6.icg.net [165.236.29.85]
46422 134 ms 131 ms 139 ms whv-ca-gw1.icg.net [165.236.29.65]
46433 157 ms 132 ms 143 ms f3-1-0.lai-ca-gw1.icg.net [165.236.24.89]
46444 194 ms 193 ms 188 ms a0-0-0-1.dai-tx-gw1.icg.net [163.179.235.61]
46455 300 ms 211 ms 214 ms a1-1-0-1.ati-ga-gw1.icg.net [163.179.235.186]
46466 236 ms 237 ms 247 ms a5-0-0-1.was-dc-gw1.icg.net [163.179.235.129]
46477 258 ms 236 ms 244 ms 163.179.243.205
46488 231 ms 233 ms 230 ms wdc-brdr-03.inet.qwest.net [205.171.4.153]
46499 240 ms 230 ms 236 ms wdc-core-03.inet.qwest.net [205.171.24.69]
465010 262 ms 264 ms 263 ms hou-core-01.inet.qwest.net [205.171.5.187]
465111 281 ms 263 ms 259 ms hou-core-03.inet.qwest.net [205.171.23.9]
465212 272 ms 229 ms 222 ms lax-core-02.inet.qwest.net [205.171.5.163]
465313 230 ms 217 ms 230 ms lax-edge-07.inet.qwest.net [205.171.19.58]
465414 228 ms 219 ms 220 ms 63-145-160-42.cust.qwest.net [63.145.160.42]
465515 218 ms 222 ms 218 ms ISI-7507--ISI.POS.calren2.net [198.32.248.21]
465616 232 ms 222 ms 214 ms UCLA--ISI.POS.calren2.net [198.32.248.30]
465717 234 ms 226 ms 226 ms cbn5-gsr.calren2.ucla.edu [169.232.1.18]
465818 245 ms 227 ms 235 ms www.ucla.edu [169.232.33.129]
4659Trace complete.
4660Net Bios Stats
4661NBTSTAT.exe
4662Displays protocol statistics and current TCP/IP connections using NBT
4663(NetBIOS over TCP/IP).
4664NBTSTAT [-a RemoteName] [-A IP address] [-c] [-n] [-r] [-R] [-s] [S] [interval]
4665-a (adapter status) Lists the remote machine's name table given its name.
4666-A (Adapter status) Lists the remote machine's name table given its IP address.
4667-c (cache) Lists the remote name cache including the IP addresses.
4668-n (names) Lists local NetBIOS names.
4669-r (resolved) Lists names resolved by broadcast and via WINS
4670-R (Reload) Purges and reloads the remote cache name table
4671-S (Sessions) Lists sessions table with the destination IP addresses.
4672-s (sessions) Lists sessions table converting destination IP addresses to host names via the
4673hosts file.
4674RemoteName Remote host machine name.
4675IP address Dotted decimal representation of the IP address.
4676interval Redisplays selected statistics, pausing interval seconds between each display. Press
4677Ctrl+C to stop redisplaying statistics.
4678ROUTE.exe
4679Manipulates network routing tables.
4680ROUTE [-f] [command [destination] [MASK netmask] [gateway]]
4681-f Clears the routing tables of all gateway entries. If this is used in conjunction
4682with one of the commands, the tables are cleared prior to running the command.
4683command Specifies one of four commands
4684PRINT Prints a route
4685ADD Adds a route
4686DELETE Deletes a route
4687CHANGE Modifies an existing route
4688destination Specifies the host to send command.
4689MASK If the MASK keyword is present, the next parameter is interpreted as the
4690netmask parameter.
4691netmask If provided, specifies a sub-net mask value to be associated with this route entry.
4692If not specified, if defaults to 255.255.255.255.
4693gateway Specifies gateway.
4694All symbolic names used for destination or gateway are looked up in the network and host
4695name database files NETWORKS and HOSTS, respectively.
4696If the command is print or delete, wildcards may be used for the destination and gateway, or
4697the gateway argument may be omitted.
4698ARP.exe Address Resolution Protocol
4699ARP -s inet_addr eth_addr [if_addr]
4700ARP -d inet_addr [if_addr]
4701ARP -a [inet_addr] [-N if_addr]
4702-a Displays current ARP entries by interrogating the current protocol data. If inet_addr
4703is specified, the IP and Physical addresses for only the specified computer are
4704displayed. If more than one network interface uses ARP, entries for each ARP
4705table are displayed.
4706-g (Same as -a)
4707inet_addr Specifies an internet address.
4708-N if_addr Displays the ARP entries for the network interface specified by if_addr.
4709-d Deletes the host specified by inet_addr.
4710-s Adds the host and associates the Internet address inet_addr with the Physical address
4711eth_addr. The Physical address is given as 6 hexadecimal bytes separated by hyphens.
4712The entry is permanent.
4713eth_addr Specifies a physical address.
4714if_addr If present, this specifies the Internet address of the interface
4715whose address translation table should be modified. If not present, the first
4716applicable interface will be used.