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