Sie sind auf Seite 1von 34

LAB MANUAL:BCSL-056

Network Programming and Administrative Lab


Name: Rahul Kumar
Enrolment No: 170217591

APRIL 12, 2019


IGNOU
Study Centre: VICE (29019)
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Session-I
Unix Basics
Exercise 1: Run the following commands & write the use of each command.
Ans:
IPCONFIG: - Displays all current TCP/IP network configuration values and
refreshes Dynamic Host Configuration Protocol (DHCP) and Domain Name
System (DNS) settings. This command is most useful on computers that are
configured to obtain an IP address automatically. This enables users to
determine which TCP/IP configuration values have been configured by DHCP,
Automatic Private IP Addressing (APIPA), or an alternate configuration.

PING: - Verifies IP-level connectivity to another TCP/IP computer by sending


Internet Control Message Protocol (ICMP) Echo Request messages. The receipt
of corresponding Echo Reply messages are displayed, along with round-trip
times. Ping is the primary TCP/IP command used to troubleshoot connectivity,
reachability, and name resolution.

TELNET:-This command is used to communicate with another host using the


TELNET protocol. If telnet is invoked without the host argument, it enters
command mode, indicated by its prompt. In this mode, it accepts and executes
the commands listed below. If it is invoked with arguments, it performs an open
command with those arguments.

DISKPERF:-This command is used to know that the disk performance counters


are enabled on the local or specified computer and identifies the counters
enabled (physical drives, logical drives, or both):

NETDIAG:-this command will allow you to test and isolate network connectivity
problems on all types of client computers. Once launched, Netdiag perform a
series of tests to determine the operational status of communication between
your network and client computers.

NETSTAT :-Displays active TCP connections, ports on which the computer is


listening, Ethernet statistics, the IP routing table, IPv4 statistics (for the IP,
ICMP, TCP, and UDP protocols), and IPv6 statistics (for the IPv6, ICMPv6, TCP
over IPv6, and UDP over IPv6 protocols)

PATHPING:-Pathping is used to find network latency and network loss.

P a g e 1 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

FTP:-FTP is the user interface to the ARPANET standard File Transfer Protocol.
This command allows a user to transfer files to and from a remote network.

SFC:-SFC stands forSystem File Checker, is used to verify and replace important
Windows system files.
NBTSTAT:-Displays NetBIOS over TCP/IP (NetBT) protocol statistics,

LPR:- This command is used to print a file

TRACERT:-Determines the path taken to a destination by sending Internet


Control Message Protocol (ICMP) Echo Request messages to the destination
with incrementally increasing Time to Live (TTL) field values. The path displayed
is the list of near-side router interfaces of the routers in the path between a
source host and a destination. The near-side interface is the interface of the
router that is closest to the sending host in the path. Used without parameters,
tracert displays help.
This diagnostic tool determines the path taken to a destination by sending ICMP
Echo Request messages with varying Time to Live (TTL) values to the
destination. Each router along the path is required to decrement the TTL in an
IP packet by at least 1 before forwarding it.

NSLOOKUP:-Nslookup (Name Server lookup) is a UNIX shell command to query


Internet domain name servers.

ROUTE:- used to view and manipulate the TCP/IP routing table

LPQ:-This command is examine the printer spooling queue

NETTIME:-This command allows view the time on a remote server or synchronize the
time on the local server with the time on the remote server.

RSH:-This command is used to execute commands on a remote machine. The RSH


command executes the command or a program in another host from current working
machine without having to login into that remote machineby entering a password.
You can run any unix command, or a shell script of a remote host.

CHKDSK:-The chkdsk command is a Recovery Console command used to check a


specified disk and repair or recover data on the drive if necessary.

HOSTNAME:-Display the hostname of the system The basic functionality of


the hostname command is to display the name of the system on the terminal.
Just type the hostname on the unix terminal and press enter to print the
hostname.

P a g e 2 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Exercise 2: Find your Ethernet physical address. Configure the IPv6 address in
your interface and update the DNS server according your addresses.
Ans:
To find the Ethernet Address for Windows computers

1. Click Start, then Run, type CMD in the text box and click OK

2. Type in ipconfig/all in the Command Prompt window and press the


Return key

3. In the Command Prompt window, locate Ethernet adapter Local Area


Connection
The 12 digit Physical Address (a.k.a. Ethernet Address) will be visible
directly below the Ethernet adapter Local Area Connection.

IPv6 Introduction
Internet Protocol version 6 (IPv6) is the successor to the well-known IPv4
protocol, commonly known as IP. Your Ubuntu system comes with all you will
need to use IPv6. This section focuses on getting IPv6 properly configured and
running.

In the early 1990s, growth of the Internet led to various problems with IPv4,
including:

 Running out of subnets. This was deferred by conversion to Classless


Inter-Domain Routing (CIDR), currently described by RFC4632
 Running out of addresses. This was deferred by using RFC1918 private
address space (10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16) hiding
behind Network Address Translation (NAT) devices, in which a single
public IPv4 address can be shared by multiple computers, e.g. all the
users connected through a DSL/Cable modem. But NAT has its own
problems. Besides NAT, in some cases during the transition to IPv6,
multiple internet connections will share IPv4 addresses via dual-stack-
lite. And as of 2011, a growing number of nodes on the Internet only
speak ipv6 since unassigned IPv4 addresses started to run out.
 Routing table was getting too large. This is still a concern today.

Configure your Ubuntu box as a IPv6 router


1. Edit /etc/sysctl.conf

P a g e 3 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Uncomment the line which contains net.ipv6.conf.default.forwarding=1. This is


a common step to enable IPv6 routing.

You can learn how to install and enable DHCPv6 on your network here.

Alternatively, if you want to use radvd which will advertise your prefix and let
the network's systems select their own IP address:

2. Install radvd

sudo aptitude install radvd


3. Edit /etc/radvd.conf (see following sample)

Note: If the computer is only routing IPv6, then only uncomment


net.ipv6.conf.default.forwarding=1 and leave the IPv4 stuff unchanged.

Note: /etc/radvd.conf: This file does not exist after a fresh install. You can look
at the sample configuration files in usr/share/doc/radvd/examples/ for further
studies.

Sample /etc/radvd.conf:

interface eth0
{
AdvSendAdvert on;
prefix 2001:xxxx:xxxx::/64
{
AdvOnLink on;
AdvAutonomous on;
};
};
eth0 is the interface which is used for the Router Advertising messages (RAs). If
you are not sure about the interface, check with <tt>ipaddr</tt> on the
command line.

The prefix you have to take from the information given by SixXS or Hurricane
Electric.

Restart the router advertising daemon to propagate your IPv6 address space

sudo /etc/init.d/radvd restart


Now router should automatically send "Router Advertising Messages" to your
network and your IPv6 clients should auto configure them self.

P a g e 4 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Exercise 3: Write the command to remove read permission for Group and
Other on the file 'green'.
Ans: Permissions can be set in the octal mode (with digits), or with letters.
In this article, we will change the file and folder access rights in the human
readable representation with chmod.

In Linux and Unix systems, the file and folder permission permissions are:

 read permissions: r
 write permissions: w
 execution permissions : x
Structured in u g o format:
 u = user
 g = group
 o = others
The user is the owner of the file or directory, the group is the group that owns
the fileor directory and the users that do not belong to the owner group are the
others.
The generically tool for displaying the permissions is ls -l .
The red characters represent the permissions for the user, the green
characters represent the access rights for the group and the blue ones for the
others.

Exercise 4: Write the command to add search permission for everyone for
your home directory (~/).

Ans. Ownership and Permissions


As a regular user, try to enter root's home directory by entering the
command cd /root/. Note the error message:
-bash: cd: /root/: Permission denied

That was one demonstration of Linux's security features. Linux, like UNIX, is a
multi-user system and file permissions are one way the system protects against
malicious tampering.

One way to gain entry when you are denied permission is to enter the
command su -. This is because whoever knows the root password has complete
access.

P a g e 5 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

However, switching to the superuser is not always convenient or


recommended, since it is easy to make mistakes and alter important
configuration files as the superuser.

Exercise 5: Find all files in your directory starting at ~ that were modified or
accessed within the last 2 days.
Ans: You can search for files whose time stamps are within a certain age range,
or compare them to other time stamps.
You can use -mtime option. It returns list of file if the file was last accessed N*24
hours ago. For example to find file in last 2 months (60 days) you need to use -
mtime +60 option.
 -mtime +60 means you are looking for a file modified 60 days ago.
 -mtime -60 means less than 60 days.
 -mtime 60 If you skip + or - it means exactly 60 days.
So to find text files that were last modified 60 days ago, use
$ find /home/you -iname "*.txt" -mtime -60 -print
Display content of file on screen that were last modified 60 days ago, use
$ find /home/you -iname "*.txt" -mtime -60 -exec cat {} \;

P a g e 6 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Count total number of files using wc command


$ find /home/you -iname "*.txt" -mtime -60 | wc -l
You can also use access time to find out pdf files. Following command will
print the list of all pdf file that were accessed in last 60 days:
$ find /home/you -iname "*.pdf" -atime -60 -type -f
List all mp3s that were accessed exactly 10 days ago:
$ find /home/you -iname "*.mp3" -atime 10 -type -f
There is also an option called -daystart. It measure times from the beginning
of today rather than from 24 hours ago. So, to list the all mp3s in your home
directory that were accessed yesterday, type the command
$ find /home/you -iname "*.mp3" -daystart -type f -mtime 1
Where,
-type f - Only search for files and not directories
-daystart option
The -daystart option is used to measure time from the beginning of the
current day instead of 24 hours ago. Find out all perl (*.pl) file modified
yesterday, enter:
find /nas/projects/mgmt/scripts/perl -mtime 1 -daystart -iname "*.pl"
You can also list perl files that were modified 8-10 days ago, enter:
To list all of the files in your home directory tree that were modified from two
to four days ago, type:
find /nas/projects/mgmt/scripts/perl -mtime 8 -mtime -10 -daystart -iname
"*.pl"

Exercise 6: Find and print all files in your file space whose size is less than 50
bytes.
Ans. CIT 370 Lab Exercise 10
Topic: The Linux File System
Read the notes on the Linux File System before starting this lab. Start VMware
and boot your CentOS virtual machine. Log in as yourself and open two

P a g e 7 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

terminal windows. In one, open vi to answer questions. In the other, you will
do various commands. As usual, questions are placed in italics and commands
in bold courier font.

1. Exploring the file system


a. The df command reports the disk file space usage. Enter df and look over
the results. What do the results mean? Hint: recall the partitioning steps
from the Linux installation.
b. The various parts of the file system are made available by mounting
them. You can see what is mounted at boot time by looking at the
/etc/fstab file, and what is currently mounted by looking at the
/etc/mtab file. Look at these. Compare them line by line and see if you
can make sense of how they appear. NOTE: rw, in mtab means that the
file space is readable and writable, ro would be read only. The command
mount will mount a partition to the filespace while umount will unmount
a partition. If a partition is unmounted, it is no longer accessible (until it
is mounted again). To mount all of the file systems in /etc/fstab, use
mount –a. Type cat /etc/fstabagain and examine the contents. How do
the lines of this file relate to what you saw when you did df? Type umount
/var. What happened?su to root and repeat this. What happened?
Obviously, you cannot umount a file system that is currently busy, and
the system uses /var all the time. You would also not be able to umount
/home since you have a file open. Two partitions that are not busy at
the moment are sys and tmpfs. Umounttmpfs. What instruction did you
enter? To remount a partition, you type mount device location, as in
mount /dev/sda5 /home (if /home were stored at /dev/sda5). For
tmpfs, the device is /dev/shm. Mount tmpfs again. What instruction did
you type in? Note: if this does not work you can also remount it by doing
mount –a. Do dfagain to make sure that tmpfs is mounted again. Now

P a g e 8 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

unmount /sys and then try to remount it. How were you able to do
these? Exit as root.
c. The du instruction can be useful for a system administrator who needs
to determine if a user is using more than their fair share of disk space.
The du instruction tells you the amount of disk usage that a particular
directory is using. Switch to root so that you can access all of the various
directories in spite of permissions. Now cd to your own directory and
type du. You will see all of your subdirectories listed before you see the
final number. Type du –s to limit the output to just the size of the
directory. What was the result? Now do du /home/zappaf. What was
output? Now dodu /etc and compare the result to du –s /etc. What is
the size of etc? Exit from root and retry the last command. What
happened and why?
d. cd to /dev and look at the files. Everything in the Linux file system is a
file, including devices. The idea is the same as redirecting your output
to a file or redirecting a file to input, but in these cases the file is really
some type of device. If you do an ls –l, the first entry in the permission
list describes the type of file (we are used to seeing – for files, d for
directories, or l for symbolic links). Type the commandls -l /dev/s*The
“b” for the file type indicates block storage. What types of devices are
these? Type ls –l /dev/console. This is the system console. What is the
file type? (See Table 4-3 on page 176). What type is associated with the
letter “s”? Name a file that is of this type.
e. Explore the programs in /bin, /usr/bin, /sbin and /usr/sbin. How do
these programs differ in terms of the types of programs and their
uses?That is, why are these executable programs separated into three
groupings like they are?
f. The PATH variable stores directories to automatically check when you
issue a command. The which command will search all directories in

P a g e 9 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

PATH along with the current directory for a file. Explore the which
command and find out where each of these files is located: yum, sed,
useradd. What did you find out from each of your which commands?
Why did you get the result you did for useradd? Another way to find the
location of a file is through find, which you will explore next.
2. Find Thefind command allows you to search the some portion of the file
system for files. Read about the command on page 178. To list the .txt files
starting in your home directory, you would enter find ~ -name “*.txt” –print
| less where ~ means your home directory, -name *.txt means to search for
anything named “*.txt”, and –print means to output the results to the
screen. Note: if you want to search starting at / (the root of the file space),
you should be root because you, as a normal user, will not have access to
many directories. You can also use –ls instead of –print.
a. Use the find command to locate myfoo.txt. What was the output of the
command?
b. Type which brl_nbchords. Notice that the file isn’t in one of the locations
in your path. So now, use find to locate brl_nbchords. Where did you
find it?
You can use the find command to find files based on various parameter
values instead of name, such as the last modification time (date), last access
time (date), file size, file permission and whether a file is empty. For
modification and access time, use –mtime and –atime followed by +# or -#
where # is an integer value like 10 (for 10 days). To combine multiple
conditions, place the mtime and atime statements within \( and \) and
separate each item with –o for or, and –a for and. The command find ~ \( -
mtime +10 –o –atime +10 \) –lswill find files that were last modified more
than 10 days ago or accessed more than 10 days ago. The –perm option
allows you to compare permissions. You follow –perm by the 3 digit value
of a permission, so for instance to find all files whose permissions are 744

P a g e 10 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

use –perm 744. The –size option allows you to specify a size where the size
is a numeric value, a + (more than) or – (less than) and a unit such as ‘c’ for
bytes, k for kilobytes, M for megabytes and G for gigabytes. For instance,
find ~ -size +10000c –print finds all files in your home directory greater than
10000 bytes. Return to your own account to do steps c-f.

c. Find all files in your directory starting at ~ that were modified or accessed
within the last 2 days (use – instead of +). Which ones were listed?
d. Enter a find command to locate all ordinary files in your directory space
with rw-rw-r-- permission. Try again with r-xr-xr--. What commands did
you come up with?
e. Find and print all files in your file space whose size is less than 50 bytes.
What command did you enter? How many files were found?
f. The –empty parameter will find any file or directory that is empty. Find
all empty files in your home directory. What files did you find? What
command did you enter?
Email your answers file to your instructor, shutdown your VM, exit out of
VMware and log off.

P a g e 11 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Session II
Socket Setup & Data Transfer

Exercise 3: Write the client and server programs in C language for establishing
termination of connection between client and server using TCP. Assumethe
server can handle only one client.

Ans.
WSADATA WsaDat;
SOCKET Socket, HandleSock;
SOCKADDR_IN SockAddr;
SOCKADDR_IN Addr;
hostent* localHost;
char* localIP;
int z = sizeof(Addr);
if(WSAStartup(MAKEWORD(1, 1), &WsaDat) != 0) // Initialize
WinSock 1.1
{
printf("WSA Error: %d",WSAGetLastError());
return -1;
}
Socket = socket(AF_INET, SOCK_STREAM, 0); // Obtain a socket from the OS
if(Socket==INVALID_SOCKET)
{
printf("Socket Error: %d",WSAGetLastError());
return -1;
}
SockAddr.sin_port = htons(PORT_NUMBER);
SockAddr.sin_family = AF_INET;
localHost = gethostbyname("");
localIP = inet_ntoa(*(structin_addr *)*localHost->h_addr_list);
SockAddr.sin_addr.s_addr = inet_addr(localIP);
if(bind(Socket, (SOCKADDR *)(&SockAddr),
sizeof(SockAddr))==SOCKET_ERROR)
{
printf("Binding Error: %d",WSAGetLastError());

P a g e 12 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

return -1;
}
listen(Socket, 1);
while(1)
{
HandleSock = accept(Socket, (SOCKADDR*)&Addr, &z);
}

Exercise 5: Write the Echo client and server programs in C language using
UDP. The Echo clients should verify whether the text string they received from
the server is the same text string that they sent or not. Also use the shutdown
system call to improve the performance programs.

Ans.
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#define BUFFSIZE 255
void Die(char *mess) { perror(mess); exit(1); }
int main(intargc, char *argv[]) {
int sock;
structsockaddr_inechoserver;
structsockaddr_inechoclient;
char buffer[BUFFSIZE];
unsignedintecholen, clientlen;
int received = 0;
if (argc != 4) {
fprintf(stderr, "USAGE: %s <server_ip><word><port>\n", argv[0]);
exit(1);
}
A contrast with the Python code comes up already here. For this C client,
you must use a dotted-quad IP address. In Python, all the socket module
functions handle name resolution behind the scenes. If you wanted to do a

P a g e 13 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

lookup in the C client, you would need to program a DNS function--such as the
one presented in the first part of this tutorial.

In fact, it would not be a terrible idea to check that the IP address passed in as
the server IP address really looks like a dotted-quad address. If you forgetfully
pass in a named address, you will probably receive the somewhat misleading
error: "Mismatch in number of sent bytes: No route to host" (see below for
where this message is produced). Any named address amounts to the same
thing as an unused or reserved IP address (which a simple pattern check could
not rule out, of course).

#!/usr/bin/env python
from socket import *
import sys, time
from thread import start_new_thread, get_ident
start = time.time()
threads = {}
sock = socket(AF_INET, SOCK_DGRAM)
def request(n):
sock.sendto("%s [%d]" % (sys.argv[2],n),
(sys.argv[1], int(sys.argv[3])))
messin, server = sock.recvfrom(255)
print "Received:", messin
del threads[get_ident()]
for n in range(20):
id = start_new_thread(request, (n,))
threads[id] = None
#print id,
while threads: time.sleep(.1)
sock.close()
print "%.2f seconds" % (time.time()-start)

P a g e 14 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Session III
Basic Linux Administration

Exercise 1: Create a new user guest1 in the Guest Group using GUI tool in
Linux. Now add another new user in a different group than the group of guest.
Assume both users wants to write on a same text file “my file”, create optimal
file permission for this text file.
Ans.LINUX COMMANDS & UNIX Commands

To understand the working of the command and possible options use (man
command)
Using the GNU Info System (info, info command)
Listing a Description of a Program (whatis command)
Many tools have a long−style option, `−−help', that outputs usage information
about the tool, including the options and arguments the tool takes.
Ex: whoami –help

Pipes
An important early development in Unix was the invention of "pipes," a way
to pass the output of one tool to the input of another.
eg. $ who | wc−l
By combining these two tools, giving the wc command the output of who, you
can build a new command to list the number of users currently on the system
chown Change owner.
Ex: chown<owner1><filename> : Change ownership of a file to owner1.
chgrp Change group.
Ex: chgrp<group1><filename> : Change group of a file to group1.
cp Copy a file from one location to another.
Ex: cp file1 file2 : Copy file1 to file2
Ex: cp –R dir1 dir2 : Copy dir1 to dir2
md5sum Prints the MD5 Checksum

P a g e 15 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Linux File Management and Viewing


ls List contents of a directory.
Ex: ls, ls –l ,ls –al, ls –ld, ls –R
(-rwxrwxr-x 1 juanjuan 0 Sep 26 12:25 foo )
|more will list page wise
mkdir Make a directory.
Ex: mkdir <directory name> : Makes a directory
Ex mkdir –p /www/chache/var/log will create all the directories starting from
www.
mv Move or rename a file or directory.
Ex: mv <source><destination>
find Find files (find <start directory> -name <file name> -print)
Ex: find /home –name readme -print
(Search for readme starting at home and output full path.)

Exercise 3: Write a command to enable authentication for single-user mode


on Linux.
Ans.
Enable Authentication for Single-User Mode
Single-User mode is used for a system recovery. However, by default, no
authentication is used if single-user mode is selected. This can be used to
bypassing security on the server and gaining root access. To enable
authentication for single-user mode, open the /etc/inittab, file:

# vi /etc/inittab

Add the following line to the file:


~~:S:wait:/sbin/sulogin
Save and close the file.

P a g e 16 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Exercise 4:-Write a command to disable Interactive Hotkey Startup at Boot in


Linux.
Ans.
Disable Interactive Hotkey Startup at Boot in Linux
A few Linux distribution like Fedora, CentOS or RHEL allows the console user
to perform an interactive system startup by pressing [I] key. Using interactive
boot, attacker can disable the firewall and other system services.
Open /etc/sysconfig/init file:

# vi /etc/sysconfig/init

P a g e 17 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Session V
Flow & Error Control
Exercise 2: Write programs in C language for implementing the sliding window
protocol of window size 5.
Ans.
##include <Sys/Type.h>
#define SIZE 4
main()
{
intstd, lfd, len, i, j, status, sport;
charstr[20]]
temp[20], ack[20];
structsockaddr_insaddr, caddr;
printf("Enter the port address");
scanf("%d",frame[20]&sport);
std = socket(AF_INET, SOCK_STREAM, 0);
if(std<0)
perror("Error");
bzero(&saddr, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr =htonl(INADDR_ANY);
saddr.sin_port = htons(sport);
lfd = bind(std, (structsockaddr *)&saddr,sizeof(saddr));
if(lfd)
perror("Bind Error");
listen(std, 5);
len = sizeof(&caddr);
lfdaccept(std, (structsockaddr *)&caddr, &len);

P a g e 18 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

printf("Enter the text:");


scanf("%s",str);
i = 0;
while(i<strlen(str))
{
memset(frame, 0, 20);
strncpy(frame, str+i, SIZE);
}

P a g e 19 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Session VI
Routing

Exercise 1: Write the client and server programs in C language for


implementing the broadcasting in the local network.
Ans.
#define LINELEN 128
int main(intargc, char *argv[ ])
{
char *host = "localhost"; /* host to use if none
supplied */
char *service = "daytime"; /* default service
port */
switch (argc)
{
case 1:
host = "localhost";
break;
case 3:
service = argv[2];
case 2:
host = argv[1];
break;
default:
fprintf(stderr, "usage: TCPdaytime [host [port]]\n");
exit(1);
}
TCPdaytime(host, service);
exit(0);

P a g e 20 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

}
voidTCPdaytime(const char *host, const char *service)
{
charbuf[LINELEN+1]; /* buffer for one line of
text */
int s, n; /* socket, read count */

s = connectTCP(host, service);
while((n = read(s, buf, LINELEN)) > 0)
{ /* ensure null-terminated
*/
buf[n] = '\0';
(void) fputs(buf, stdout);
}
}

P a g e 21 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Session VII
Utility Development

Exercise 1: Write the program in C language for implementing the utility


similar to “Ping”.
Ans.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <linux/ip.h>
#include <linux/icmp.h>
#include <string.h>
#include <unistd.h>
chardst_addr[20];
charsrc_addr[20];
unsigned short in_cksum(unsigned short *, int);
voidparse_argvs(char**, char*, char* );
void usage();
char* getip();
char* toip(char*);
int main(intargc, char* argv[])
{
structiphdr* ip;
structiphdr* ip_reply;
structicmphdr* icmp;
structsockaddr_in connection;
char* packet;
char* buffer;
intsockfd;
intoptval;
intaddrlen;
intsiz;
if (getuid() != 0)
{
fprintf(stderr, "%s: root privelidges needed\n", *(argv + 0));
exit(EXIT_FAILURE);

P a g e 22 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

}
parse_argvs(argv, dst_addr, src_addr);
strncpy(dst_addr, toip(dst_addr), 20);
strncpy(src_addr, toip(src_addr), 20);
printf("Source address: %s\n", src_addr);
printf("Destination address: %s\n", dst_addr);
packet = malloc(sizeof(structiphdr) + sizeof(structicmphdr));
buffer = malloc(sizeof(structiphdr) + sizeof(structicmphdr));
ip = (structiphdr*) packet;
icmp = (structicmphdr*) (packet + sizeof(structiphdr));
ip->ihl= 5;
ip->version= 4;
ip->tos= 0;
ip->tot_len= sizeof(structiphdr) + sizeof(structicmphdr);
ip->id= htons(0);
ip->frag_off= 0;
ip->ttl= 64;
ip->protocol= IPPROTO_ICMP;
ip->saddr= inet_addr(src_addr);
ip->daddr= inet_addr(dst_addr);
ip->check= in_cksum((unsigned short *)ip, sizeof(structiphdr));
if ((sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) == -1)
{
perror("socket");
exit(EXIT_FAILURE);
}
setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL, &optval, sizeof(int));
icmp->type= ICMP_ECHO;
icmp->code= 0;
icmp->un.echo.id = random();
icmp->un.echo.sequence= 0;
icmp-> checksum= in_cksum((unsigned short *)icmp, sizeof(structicmphdr));
connection.sin_family = AF_INET;
connection.sin_addr.s_addr = inet_addr(dst_addr);
sendto(sockfd, packet, ip->tot_len, 0, (structsockaddr *)&connection,
sizeof(structsockaddr));
printf("Sent %d byte packet to %s\n", ip->tot_len, dst_addr);
addrlen = sizeof(connection);
if (( siz = recvfrom(sockfd, buffer, sizeof(structiphdr) + sizeof(structicmphdr), 0,
(structsockaddr *)&connection, &addrlen)) == -1)
{
perror("recv");
}

P a g e 23 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

else
{
printf("Received %d byte reply from %s:\n", siz , dst_addr);
ip_reply = (structiphdr*) buffer;
printf("ID: %d\n", ntohs(ip_reply->id));
printf("TTL: %d\n", ip_reply->ttl);
}
free(packet);
free(buffer);
close(sockfd);
return 0;
}
voidparse_argvs(char** argv, char* dst, char* src)
{
int i;
if(!(*(argv + 1)))
{
usage();
exit(EXIT_FAILURE);
}
if (*(argv + 1) && (!(*(argv + 2))))
{
strncpy(dst, *(argv + 1), 15);
strncpy(src, getip(), 15);
return;
}
else if ((*(argv + 1) && (*(argv + 2))))
{
strncpy(dst, *(argv + 1), 15);
i = 2;
while(*(argv + i + 1))
{
if (strncmp(*(argv + i), "-s", 2) == 0)
{
strncpy(src, *(argv + i + 1), 15);
break;
}
i++;
}
}
}
void usage()
{

P a g e 24 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

fprintf(stderr, "\nUsage: pinger [destination] <-s [source]>\n");


fprintf(stderr, "Destination must be provided\n");
fprintf(stderr, "Source is optional\n\n");
}
char* getip()
{
char buffer[256];
structhostent* h;
gethostname(buffer, 256);
h = gethostbyname(buffer);
returninet_ntoa(*(structin_addr *)h->h_addr);
}
char* toip(char* address)
{
structhostent* h;
h = gethostbyname(address);
returninet_ntoa(*(structin_addr *)h->h_addr);
}
unsigned short in_cksum(unsigned short *addr, intlen)
{
registerint sum = 0;
u_short answer = 0;
registeru_short *w = addr;
registerintnleft = len;
while (nleft> 1)
{
sum += *w++;
nleft -= 2;
}
if (nleft == 1)
{
*(u_char *) (&answer) = *(u_char *) w;
sum += answer;
}
sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
sum += (sum >> 16); /* add carry */
answer = ~sum; /* truncate to 16 bits */
return (answer);
}

P a g e 25 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Session VIII
Advance Linux Administration

Exercise 1: Configure and launch an FTP server than install and test an FTP
client in Linux.
Ans.Any Linux system can operate as an FTP server. It has to run only the server
software—an FTP daemon with the appropriate configuration. Transfers are
made between user accounts on client and server systems. A user on the
remote system has to log in to an account on a server and can then transfer
files to and from that account's directories only.
A special kind of user account, named ftp, allows any user to log in to it with
the username “anonymous.” This account has its own set of directories and
files that are considered public, available to anyone on the network who wants
to download them.
The numerous FTP sites on the Internet are FTP servers supporting FTP user
accounts with anonymous login. Any Linux system can be configured to support
anonymous FTP access, turning them into network FTP sites. Such sites can
work on an intranet or on the Internet.
Configuring the ftp Server
The vsftpd RPM package is required to configure a Red Hat Enterprise Linux
system as an ftp server. If it is not already installed, install it
with rpm commands as described in our pervious article. After it is installed,
start the service as root with the command service vsftpd start. The system is
now an ftp server and can accept connections. To configure the server to
automatically start the service at boot time, execute the
command chkconfigvsftpd on as root. To stop the server, execute the
command service vsftpd stop. To verify that the server is running, use the
command service vsftpd status.
Configure vsftpd server

P a g e 26 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

In this example we will configure a vsftpd server and will transfer files from
client side.
For this example we are using three systems one linux server one linux clients
and one windowsxp clients.

Network configuration in Linux

~ A linux server with ip address 192.168.0.254 and hostname Server

~ A linux client with ip address 192.168.0.1 and hostname Client1

~ A window client with ip address 192.168.0.2 and hostname Client2

~ Updated /etc/hosts file on both linux system

~ Running portmap and xinetd services

~ Firewall should be off on server

Three rpm are required to configure ssh server. vsftpd, portmap,


xinetd check them if not found then install

Now check vsftpd, portmap, xinetd service in system service it should be on


#setup
Select System service from list
[*]portmap
[*]xinetd
[*]vsftpd

P a g e 27 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Now restart xinetd and portmap and vsftpd service

To keep on these services after reboot on then via chkconfig command

After reboot verify their status. It must be in running condition

Exercise 2: Configure a remote server and transfer a Directory to Remote


Server.

Ans.FTP, or "File Transfer Protocol" is a popular method of transferring files


between two
remotesystems.SFTP, which stands for SSH File Transfer Protocol, or Secure File
Transfer Protocol, is a separate protocol packaged with SSH that works in a
similar way over a secure connection. The advantage is the ability to leverage a
secure connection to transfer files and traverse the file system on both the local
and remotesystem.In almost all cases, SFTP is preferable to FTP because of its
underlying security features and ability to piggy-back on an SSH connection. FTP
is an insecure protocol that should only be used in limited cases or on networks

P a g e 28 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

you trust.Although SFTP is integrated into many graphical tools, this guide will
demonstrate how to use it through its interactive command line interface.

How to Connect with SFTP

By default, SFTP uses the SSH protocol to authenticate and establish a secure
connection. Because of this, the same authentication methods are available
that are present in SSH.
Although passwords are easy to use and set up by default, we recommend you
create SSH keys and transfer your public key to any system that you need to
access. This is much more secure and can save you time in the long run.

Test SSH access with the following command:

Bye Quit sftp


cd path Change remote directory to 'path'
chgrpgrp path Change group of file 'path' to 'grp'
chmod mode path Change permissions of file 'path' to 'mode'
chown own path Change owner of file 'path' to 'own'
df[-hi] [path] Display statistics for current directory /filesystem
containing 'path'
exit Quit sftp
get [-Ppr] Download file
help Display this help text
lcd path Change local directory to 'path'

Navigating with SFTP


We can navigate through the remote system's file hierarchy using a number of
commands that function similarly to their shell counterparts.
First, let's orient ourselves by finding out which directory we are in currently

P a g e 29 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

on the remote system. Just like in a typical shell session, we can type the
following to get the current directory:
pwd
Remote working directory: /home/demouser
We can view the contents of the current directory of the remote system with
another familiar command:
ls
Summary.txt info.html temp.txt testDirectory
Note that the commands within the SFTP interface are not the normal shell
commands and are not as feature-rich, but they do implement some of the
more important optional flags:
ls -la

To get to another directory, we can issue this command:


cdtestDirectory
We can now traverse the remote file system, but what if we need to access
our local file system? We can direct commands towards the local file system
by preceding them with an "l" for local.

All of the commands discussed so far have local equivalents. We can print the
local working directory:
lpwd
Local working directory: /Users/demouser
We can list the contents of the current directory on the local machine:
lls
Desktop local.txt test.html
Documents analysis.rtf zebra.html
We can also change the directory we wish to interact with on the local system:

P a g e 30 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Session IX
Mail Transfer

Exercise 1: Write the program in C language for implementing the client for
Simple mail transfer protocol.
Ans.
#include <stdio.h> /* fprintf */
#include <errno.h> /* errno */
#include <stdlib.h> /* malloc, free, exit */
#include <string.h> /* strerror */
externinterrno;
int main(void)
{
char*ptr=malloc( 2000000000UL );
if(ptr== NULL ){
puts("malloc failed");
puts(strerror(errno));
}
else
{
free(ptr);
}
exit(EXIT_SUCCESS);/* exiting program */
}

Exercise 2: Write the program in C language for implementing the server for
Simple Mail Transfer Protocol. Where Server can handle maximum 5 clients
concurrently.
Ans.

P a g e 31 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

#include <stdlib.h> /* for exit */


int main(void)
{
int dividend =50;
int divisor =0;
int quotient;
if(divisor ==0){
fprintf(stderr,"Division by zero! Aborting...\n");
exit(EXIT_FAILURE);/* indicate failure.*/
}
quotient= dividend / divisor;
exit(EXIT_SUCCESS);
}

P a g e 32 | 33
Lab Manual:BCSL-056 | Rahul Kumar (170217591)

Session X
Client/Server Computing
Exercise 1: Write the client and server programs in C language, where client
will send a file containing a C-Program, server will compile and executes the
file given by the client and if error occurs during compilation or execution
server will send back the appropriate message to the client otherwise server
will send the executable file to the client.
Ans.
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
staticvoidcatch_function(int signal){
puts("Interactive attention signal caught.");
}
int main(void){
if(signal(SIGINT,catch_function)== SIG_ERR){
fputs("An error occurred while setting a signal handler.\n",stderr);
return EXIT_FAILURE;
}
puts("Raising the interactive attention signal.");
if(raise(SIGINT)!=0){
fputs("Error raising the signal.\n",stderr);
return EXIT_FAILURE;
}
puts("Exiting.");
return0;
}

P a g e 33 | 33

Das könnte Ihnen auch gefallen