You are on page 1of 39



Unix Network Programming & Simulation Lab


Submitted by Submitted to

Name: Chirag Jain Mr. Amit Mithal

Roll No.: 14EJCCS711 (Assistant Professor CSE)


S.No. Experiment Name Date of Signature


AIM - Distribution of units like DSD and POSIX

The Portable Operating System Interface (POSIX)[1] is a family of standards specified by the
IEEE Computer Society for maintaining compatibility between operating systems. POSIX
defines the application programming interface (API), along with command line shells and
utility interfaces, for software compatibility with variants of Unix and other operating

Originally, the name "POSIX" referred to IEEE Std 1003.1-1988, released in 1988. The
family of POSIX standards is formally designated as IEEE 1003 and the international
standard name is ISO/IEC 9945.

The standards emerged from a project that began circa 1985. Richard Stallman suggested the
name POSIX to the IEEE instead of former IEEE-IX. The committee found it more easily
pronounceable and memorable, and thus adopted it.

Unix was selected as the basis for a standard system interface partly because it was
"manufacturer-neutral". However, several major versions of Unix existed—so there was a
need to develop a common denominator system. The POSIX specifications for Unix-like
operating systems originally consisted of a single document for the core programming
interface, but eventually grew to 19 separate documents (POSIX.1, POSIX.2, etc.).[5] The
standardized user command line and scripting interface were based on the UNIX System V
shell.[6] Many user-level programs, services, and utilities (including awk, echo, ed) were also
standardized, along with required program-level services (including basic I/O: file, terminal,
and network). POSIX also defines a standard threading library API which is supported by
most modern operating systems. In 2008, most parts of POSIX were combined into a single
standard (IEEE Std 1003.1-2008, also known as POSIX.1-2008).

As of 2014, POSIX documentation is divided in two parts:

POSIX.1, 2013 Edition: POSIX Base Definitions, System Interfaces, and Commands and
Utilities (which include POSIX.1, extensions for POSIX.1, Real-time Services, Threads
Interface, Real-time Extensions, Security Interface, Network File Access and Network
Process-to-Process Communications, User Portability Extensions, Corrections and
Extensions, Protection and Control Utilities and Batch System Utilities. This is POSIX
1003.1-2008 with Technical Corrigendum 1.)
POSIX Conformance Testing: A test suite for POSIX accompanies the standard: VSX-PCTS
or the VSX POSIX Conformance Test Suite.
The development of the POSIX standard takes place in the Austin Group (a joint working
group linking the IEEE, The Open Group and the ISO/IEC JTC 1 organizations).
POSIX mandates 512-byte default block sizes for the df and du utilities, reflecting the typical
size of blocks on disks. When Richard Stallman and the GNU team were implementing
POSIX for the GNU operating system, they objected to this on the grounds that most people
think in terms of 1024 byte (or 1 KiB) blocks. The environment variable
POSIXLY_CORRECT was introduced to allow the user to force the standards-compliant
behaviour.This variable is now also used for a number of other behaviour quirks, where
"POSIX and common sense disagree".

POSIX is based on UNIX System V and Berkeley UNIX, but it is not itself an operating
Instead, POSIX defines the interface between applications and their libraries. POSIX does not
talk about "system calls" or make any distinction between the kernel and the user.
Vendors can adapt any UNIX variant, or even another operating system, to provide POSIX
interfaces. Applications can be moved from one system to another because they see only the
POSIX interface and have no idea what system is under the interface.

An implementation consists of both a set of libraries and an operating system. The POSIX
standard defines only the interface between the application and the library.

POSIX defines how the application talks to the library and how the library and underlying
operating system behave in response. Each implementation can have its own way of dividing
the work between the library and the operating system.

AIM: Introductions of Socket Programming

1.Man Socket

NAME: Socket – create an endpoint for communication.




int socket(int domain,int type,int protocol);


 Socket creates an endpoint for communication and returns a descriptor.

 The domain parameter specifies a common domain this selects the protocol family which will
be used for communication.
 These families are defined in <sys/socket.h>.



PF_UNIX,PF_LOCAL Local Communication.

PF_INET IPV4 Internet Protocols.

PF_IPX IPX-Novell Protocols.


 The socket has the indicated type, which specifies the communication semantics.


 Provides sequenced, reliable, two-way, connection based byte streams.

 An out-of-band data transmission mechanism, may be supported.


 Supports datagram (connectionless, unreliable messages of a fixed maximum length).


 Provides a sequenced , reliable, two-way connection based data transmission path for
datagrams of fixed maximum length.


 Provides raw network protocol access.


 Provides a reliable datagram layer that doesn’t guarantee ordering.


 Obsolete and shouldn’t be used in new programs. connect:

NAME: connect – initiate a connection on a socket.




int connect(int sockfd,const (struct sockaddr*)serv_addr,socklen_t addrlen);


 The file descriptor sockfd must refer to a socket.

 If the socket is of type SOCK_DGRAM then the serv_addr address is the address to which
datagrams are sent by default and the only addr from which datagrams are received.
 If the socket is of type SOCK_STREAM or SOCK_SEQPACKET , this call attempts to make
a connection to another socket.

 If the connection or binding succeeds, zero is returned.

 On error , -1 is returned , and error number is set appropriately.


EBADF Not a valid Index.

EFAULT The socket structure address is outside the user’s

address space.

ENOTSOCK Not associated with a socket.

EISCONN Socket is already connected.

ECONNREFUSED No one listening on the remote address.

3.Man Accept

NAME: accept/reject job is sent to a destination.


accept destination(s)

reject[-t] [-h server] [-r reason] destination(s)


 accept instructs the printing system to accept print jobs to the specified destination.
 The –r option sets the reason for rejecting print jobs.
 The –e option forces encryption when connecting to the server.

4.Man Send


send, sendto, sendmsg - send a message from a socket.




ssize_t send(int s, const void *buf, size_t len, int flags);

ssize_t sendto(int s, const void *buf, size_t len, int flags, const struct sock_addr*to, socklen_t
tolen); ssize_t sendmsg(int s, const struct msghdr *msg, int flags);


 The system calls send, sendto and sendmsg are used to transmit a message to another socket.

 The send call may be used only when the socket is in a connected state.
 The only difference between send and write is the presence of flags.
 The parameter is the file descriptor of the sending socket.

5.Man Recv

NAME: recv, recvfrom, recvmsg – receive a message from a socket.




ssize_t recv(int s, void *buf, size_t len, int flags);

ssize_t recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t* from
len); ssize_t recvmsg(int s, struct msghdr *msg, int flags);


 The recvfrom and recvmsg calls are used to receive messages from a socket, and may be used
to recv data on a socket whether or not it is connection oriented.
 If from is not NULL, and the underlying protocol provides the src addr , this src addr is filled
 The recv call is normally used only on a connection socket and is identical to recvfrom with a
NULL from parameter.

6.Man Read

NAME: read, readonly, return

7.Man Write

NAME: write- send a message to another user.


write user[ttyname]


 write allows you to communicate with other users, by copying lines from terminal to

 When you run the write and the user you are writing to get a message of the form:
Message from yourname @yourhost on yourtty at hh:mm:…

 Any further lines you enter will be copied to the specified user’s terminal.
 If the other user wants to reply they must run write as well.

7. Ifconfig

NAME: ifconfig- configure a network interface.



ifconfig interface[aftype] options | address……


 ifconfig is used to configure the kernel resident network interfaces.

 It is used at boot time to setup interfaces as necessary.

 After that, it is usually only needed when debugging or when system tuning is needed.
 If no arguments are given, ifconfig displays the status of the currently active interfaces.

8. Man Bind


bind[-m keymap] [-lp sv psv]

9. Man htons/ Man htonl

NAME: htonl, htons, ntohl, ntohs - convert values between host and network byte order.



uint32_t htonl(uint32_t
hostlong); uint16_t
htons(uint32_t hostshort);
uint32_t ntohl(uint32_t
netlong); uint16_t
ntohs(uint16_t netshort);


 The htonl() function converts the unsigned integer hostlong from host byte order to network
byte order.
 The htons() converts the unsigned short integer hostshort from host byte order to network
byte order.

 The ntohl() converts the unsigned integer netlong from network byte order to host byte order.

10. Man gethostname

NAME: gethostname, sethostname- get/set host name.


int gethostname(char *name,size_t len);

int sethostname(const char *name,size_t len);


 These functions are used to access or to change the host name of the current processor.

 The gethostname() returns a NULL terminated hostname(set earlier by sethostname()) in the

array name that has a length of len bytes.
 In case the NULL terminated then hostname does not fit ,no error is returned, but the
hostname is truncated.

 It is unspecified whether the truncated hostname will be NULL terminated.

11. Man gethostbyname

NAME: gethostbyname, gethostbyaddr, sethostent, endhostent, herror, hstr – error – get network host


h> extern int

struct hostent *gethostbyname(const char

*name); #include<sys/socket.h>

struct hostent *gethostbyaddr(const char *addr)int len, int

type); struct hostent *gethostbyname2(const char *name,int


 The gethostbyname() returns a structure of type hostent for the given hostname.

 Name->hostname or IPV4/IPV6 with dot notation.

 gethostbyaddr()- struct of type hostent / host address length
 Address types- AF_INET, AF_INET6.
 sethostent() – stay open is true(1).
 TCP socket connection should be open during queries.
 Server queries for UDP datagrams.
 endhostent()- ends the use of TCP connection.
 Members of hostent structure:
a) h_name
b) h_aliases

c) h_addrtype
d) h_length
e) h_addr-list
f) h_addr.


Thus the basic functions used for Socket Programming was studied successfully.
Experiment No: 3(A)

AIM - IPV4 and IPV6 Interoperability Issues.

IPv6 and IPv4 are two completely separate protocols. IPv6 is not backwards compatible
with IPv4, and IPv4 hosts and routers will not be able to deal directly with IPv6 traffic (and
vice versa).

Unfortunately, it is a fact of life both that there will be extreme difficulties with address
allocation and routing if the Internet is to continue be run indefinitely using IPv4 and it is
impossible to switch the entire Internet over to IPv6 overnight

Therefore for a long period of time we are going to be dealing with a network in which the
two protocols will be operating side by side. A common estimate of the length of time
involved is 10 years ö in terms of the history of the Internet, a very long time indeed, but
probably a realistic figure in terms of the amount of installed IPv4 software and
infrastructure, all of which will need to be replaced or upgraded.

During the transition period, IPv6 nodes are going to need to communicate with IPv4 nodes,
and isolated 'islands' of IPv6 installations are going to need to use the wider IPv4 network to
connect to each other.

Dual IP stacks have been proposed to solve the first problem, and tunneling to solve the

Dual IP Stacks

Dual IP Stacks Nodes with dual IP stacks will have both and IPv4 protocol stack and an
IPv6 one. When communicating with IPv6 nodes, they use IPv6 and when communicating
with IPv4 nodes, they revert to IPv4. These nodes have what are called IPv4 compatible
IPv6 addresses - these are addresses where the first 96 bits of the address are zeroes and the
last 32 forms a valid IPv4 address. Every current IPv4 address can be transformed to an
IPv6 address in this way.

Unfortunately, this requires all dual-stack nodes to have IPv4 addresses. This may not be
feasible considering that one of the major reasons for transitioning to IPv6 is that the
available address space is set to run out.

It is also burdensome for routers. Consider a LAN where all hosts are IPv6 enabled, but are
running dual IP stacks to communicate with the outside world. All the network
infrastructure, i.e. routers and bridges etc will need to be able to deal with both protocols,
maintain double routing tables, etc. Simplicity of routing is supposed to be a strength of
IPv6, if this sort of transition mechanism were used it would become a weakness.
To get around these two problems, the following three more advanced transition
mechanisms have been developed. These can be used in situations where a network has
been completely converted to IPv6, but which still needs to communicate with the outside
IPv4 world. They all rely on various servers or devices that sit between the IPv6 and IPv4
networks doing some form of translation.

Dual Stack Application Level Gateway (Dual Stack ALG)

Dual-stack servers are used as proxies to perform protocol translation with one proxy server
per application (http, ftp, smtp, etc). This has the advantage that very few IPv4 addresses are
required (they are only needed for the proxies), and the protocol translation step may not be
such a large price to pay in situations where firewalls and proxy server already exist, which
is the case in many LANs.

Network Address Translator - Protocol Translator (NAT-PT)

Dedicated hardware devices are placed at thr boundary of the IPv6 network and perform
protocol translation at a low level. To do this, they also store session information. With
NAT-PT, no dual stacks would be needed.

Dual Stack Transition Mechanism, or DSTM

All hosts have dual stacks, but they do not have permanent IPv4 addresses. IPv4 addresses
are temporarily assigned whenever a host contacts or is contacted by and IPv4 host. The
host encapsulates all its IPv4 packets within IPv6 headers to tunnel them over the local IPv6
network. When the DSTM router at the edge of the network sees these packets, they are

This would find natural uses on networks where IPv4 addresses are already allocated

IPv6 over IPv4 tunneling

Tunnelling Tunneling is a mechanism to allow IPv6 domains that are connected via IPv4
networks to communicate with each other, or to allow isolated IPv6 hosts that are not
directly connected to an IPv6 router but only to IPv4 machines to reach the wider IPv6
network. Naturally, to use tunneling a host must have a dual IP stack in order to send and
receive IPv4 datagrams. In most cases, however, this won't apply to large numbers of
machines - just some routers and isolated IPv6 machines on IPv4 networks.

AIM - Lock() in System Call


flock - apply or remove an advisory lock on an open file


#include <sys/file.h>

int flock(int fd, int operation);


Apply or remove an advisory lock on the open file specified by fd. The parameter operation
is one of the following:

Tag Description

LOCK_SH Place a shared lock. More than one process may hold a shared lock for a given
file at a given time.

LOCK_EX Place an exclusive lock. Only one process may hold an exclusive lock for a
given file at a given time.

LOCK_UN Remove an existing lock held by this process.

A call to flock() may block if an incompatible lock is held by another process. To make a
non-blocking request, include LOCK_NB (by ORing) with any of the above operations.

A single file may not simultaneously have both shared and exclusive locks.

Locks created by flock() are associated with an open file table entry. This means that
duplicate file descriptors (created by, for example, fork(2) or dup(2)) refer to the same lock,
and this lock may be modified or released using any of these descriptors. Furthermore, the
lock is released either by an explicit LOCK_UN operation on any of these duplicate
descriptors, or when all such descriptors have been closed.
If a process uses open(2) (or similar) to obtain more than one descriptor for the same file,
these descriptors are treated independently by flock(). An attempt to lock the file using one
of these file descriptors may be denied by a lock that the calling process has already placed
via another descriptor.

A process may only hold one type of lock (shared or exclusive) on a file. Subsequent flock()
calls on an already locked file will convert an existing lock to the new lock mode.

Locks created by flock() are preserved across an execve(2).

A shared or exclusive lock can be placed on a file regardless of the mode in which the file
was opened.


On success, zero is returned. On error, -1 is returned, and errno is set appropriately.


Error Code Description

EBADF fd is not a not an open file descriptor.

EINTR While waiting to acquire a lock, the call was interrupted by delivery of a
signal caught by a handler.

EINVAL operation is invalid.

ENOLCK The kernel ran out of memory for allocating lock records.

EWOULDBLOCK The file is locked and the LOCK_NB flag was selected.


4.4BSD (the flock(2) call first appeared in 4.2BSD). A version of flock(2), possibly
implemented in terms of fcntl(2), appears on most Unices.

AIM - Network Simulator NS2

Ns is a discrete event simulator targeted at networking research. Ns provides substantial

support for simulation of TCP, routing, and multicast protocols over wired and wireless
(local and satellite) networks.

Ns began as a variant of the REAL network simulator in 1989 and has evolved substantially
over the past few years. In 1995 ns development was supported by DARPA through the
VINT project at LBL, Xerox PARC, UCB, and USC/ISI. Currently ns development is
support through DARPA with SAMAN and through NSF with CONSER, both in
collaboration with other researchers including ACIRI. Ns has always included substantal
contributions from other researchers, including wireless code from the UCB Daedelus and
CMU Monarch projects and Sun Microsystems.

While we have considerable confidence in ns, ns is not a polished and finished product, but
the result of an on-going effort of research and development. In particular, bugs in the
software are still being discovered and corrected. Users of ns are responsible for verifying
for themselves that their simulations are not invalidated by bugs. We are working to help the
user with this by significantly expanding and automating the validation tests and demos.

Similarly, users are responsible for verifying for themselves that their simulations are not
invalidated because the model implemented in the simulator is not the model that they were

Mweigle - Provide fixes to the Tmix traffic generator, mainly to the one-way TCP
implementation, but some changes to the Full-TCP version as well. Tmix with one-way
TCP now performs comparably to Tmix with Full-TCP (albeit with longer running times
and higher memory consumption). Includes contributions from David Hayes and DongXia
Xu at Swinburne and relevant updates to the documentation and tests.

Tomh - Add Marcello Caleffi's Multi-path Dynamic Address RouTing (M-DART)

protocol. Add Sidney Doria's Datagram Congestion Control Protocol (DCCP)
implementation.Added the SYN_immediate_ack flag so that a DelAckSink agent will
immediately ACK the first (SYN) packet sent by a TcpAgent. The patch contains changes to
tcp-sink.{cc,h}, ns-default.tcl, and affected validation tests. All validation tests that use the
syn_ in TcpAgent were set to SYN_immediate_ack = false except for the delayed test in
test-suite-simple.tcl. Patch from Michele Weigle.Protocol for Unified Multicasting Through
Announcements (PUMA) has been added. PUMA is a distributed, receiver initiated, mesh
based multicast routing protocol. It is documented in the "Mobile Networking in ns" chapter
in the ns-2 manual. From Sidney Doria.

AIM – VI Editor Commands

What is vi?

The default editor that comes with the UNIX operating system is called vi (visual editor).
[Alternate editors for UNIX environments include pico and emacs, a product of GNU.]

The UNIX vi editor is a full screen editor and has two modes of operation:

1. Command mode commands which cause action to be taken on the file, and

2. Insert mode in which entered text is inserted into the file.

In the command mode, every character typed is a command that does something to the text
file being edited; a character typed in the command mode may even cause the vi editor to
enter the insert mode. In the insert mode, every character typed is added to the text in the
file; pressing the <Esc> (Escape) key turns off the Insert mode.

While there are a number of vi commands, just a handful of these is usually sufficient for
beginning vi users. To assist such users, this Web page contains a sampling of
basic vi commands. The most basic and useful commands are marked with an asterisk (* or
star) in the tables below. With practice, these commands should become automatic.

NOTE: Both UNIX and vi are case-sensitive. Be sure not to use a capital letter in place of a
lowercase letter; the results will not be what you expect.

To Get Into and Out Of vi

To Start vi

To use vi on a file, type in vi filename. If the file named filename exists, then the first page
(or screen) of the file will be displayed; if the file does not exist, then an empty file and
screen are created into which you may enter text.

* vi filename edit filename starting at line 1

vi -r filename recover filename that was being edited when system crashed

To Exit vi

Usually the new or modified file is saved when you leave vi. However, it is also possible to
quit vi without saving the file.
Note: The cursor moves to bottom of screen whenever a colon (:) is typed. This type of
command is completed by hitting the <Return> (or <Enter>) key.

* :x<Return> quit vi, writing out modified file to file named in original invocation

:wq<Return> quit vi, writing out modified file to file named in original invocation

:q<Return> quit (or exit) vi

* :q!<Return> quit vi even though latest changes have not been saved for this vi call

Moving the Cursor

Unlike many of the PC and MacIntosh editors, the mouse does not move the cursor within
the vi editor screen (or window). You must use the the key commands listed below. On
some UNIX platforms, the arrow keys may be used as well; however, since vi was designed
with the Qwerty keyboard (containing no arrow keys) in mind, the arrow keys sometimes
produce strange effects in vi and should be avoided.

If you go back and forth between a PC environment and a UNIX environment, you may find
that this dissimilarity in methods for cursor movement is the most frustrating difference
between the two.

In the table below, the symbol ^ before a letter means that the <Ctrl> key should be held
down while the letter key is pressed.

j or <Return>
* move cursor down one line
[or down-arrow]

* k [or up-arrow] move cursor up one line

h or <Backspace>
* move cursor left one character
[or left-arrow]

l or <Space>
* move cursor right one character
[or right-arrow]

* 0 (zero) move cursor to start of current line (the one with the cursor)

* $ move cursor to end of current line

w move cursor to beginning of next word

b move cursor back to beginning of preceding word

:0<Return> or 1G move cursor to first line in file

:n<Return> or nG move cursor to line n

:$<Return> or G move cursor to last line in file

Screen Manipulation

The following commands allow the vi editor screen (or window) to move up or down
several lines and to be refreshed.

^f move forward one screen

^b move backward one screen

^d move down (forward) one half screen

^u move up (back) one half screen

^l redraws the screen

^r redraws the screen, removing deleted lines

Adding, Changing, and Deleting Text

Unlike PC editors, you cannot replace or delete text by highlighting it with the mouse.
Instead use the commands in the following tables.

Perhaps the most important command is the one that allows you to back up and undo your
last action. Unfortunately, this command acts like a toggle, undoing and redoing your most
recent action. You cannot go back more than one step.

* u UNDO WHATEVER YOU JUST DID; a simple toggle

The main purpose of an editor is to create, add, or modify text for a file.

Inserting or Adding Text

The following commands allow you to insert and add text. Each of these commands puts
the vi editor into insert mode; thus, the <Esc> key must be pressed to terminate the entry of
text and to put the vi editor back into command mode.

* i insert text before cursor, until <Esc> hit

I insert text at beginning of current line, until <Esc> hit

* a append text after cursor, until <Esc> hit

A append text to end of current line, until <Esc> hit

* o open and put text in a new line below current line, until <Esc> hit

* O open and put text in a new line above current line, until <Esc> hit

Changing Text

The following commands allow you to modify text.

* r replace single character under cursor (no <Esc> needed)

R replace characters, starting with current cursor position, until <Esc> hit

change the current word with new text,

starting with the character under cursor, until <Esc> hit

change N words beginning with character under cursor, until <Esc> hit;
e.g., c5w changes 5 words

C change (replace) the characters in the current line, until <Esc> hit

cc change (replace) the entire current line, stopping when <Esc> is hit

change (replace) the next N lines, starting with the current line,
Ncc or cNc
stopping when <Esc> is hit

Deleting Text

The following commands allow you to delete text.

* X delete single character under cursor

Nx delete N characters, starting with character under cursor

Dw delete the single word beginning with character under cursor

delete N words beginning with character under cursor;

e.g., d5w deletes 5 words

D delete the remainder of the line, starting with current cursor position

* Dd delete entire current line

delete N lines, beginning with the current line;

Ndd or dNd
e.g., 5dd deletes 5 lines

Cutting and Pasting Text

The following commands allow you to copy and paste text.

yy copy (yank, cut) the current line into the buffer

Nyy or yNy copy (yank, cut) the next N lines, including the current line, into the buffer

p put (paste) the line(s) in the buffer into the text after the current line

Other Commands

Searching Text

A common occurrence in text editing is to replace one word or phase by another. To locate
instances of particular sets of characters (or strings), use the following commands.

/string search forward for occurrence of string in text

?string search backward for occurrence of string in text

N move to next occurrence of search string

N move to next occurrence of search string in opposite direction

Determining Line Numbers

Being able to determine the line number of the current line or the total number of lines in the
file being edited is sometimes useful.

:.= returns line number of current line at bottom of screen

:= returns the total number of lines at bottom of screen

provides the current line number, along with the total number of lines,
in the file at the bottom of the screen

Saving and Reading Files

These commands permit you to input and output files other than the named file with which
you are currently working.

read file named filename and insert after current line

:r filename<Return>
(the line with cursor)

:w<Return> write current contents to file named in original vi call

:w newfile<Return> write current contents to a new file named newfile

write the contents of the lines numbered 12 through 35 to a

:12,35w smallfile<Return>
new file named smallfile

AIM - Program for TCP Connection of Client and Server on Single System

Server Side






int main(int asrgc,char*argv[])


struct sockaddr_in
cliaddr,servaddr; socklen_t
clilen; clilen=sizeof(cliaddr);

/*Socket address structure*/

_ANY); servaddr.sin_port=htons(1999);

/*TCP socket is created, an Internet socket address structure is filled with

wildcard address & server’s well known port*/

/*Bind function assigns a local protocol address to the
socket*/ bd=bind(sd,(struct

/*Listen function specifies the maximum number of connections that kernel

should queue for this socket*/


printf("Server is running….\n");

/*The server to return the next completed connection from the

front of the completed connection Queue calls it*/

sockaddr*)&cliaddr,&clilen); while(1)


/*Receiving the request message from the

client*/ recv(ad,buff,sizeof(buff),0);

printf("Message received is %s\n",buff);

Client Side








int main(int argc,char * argv[])



struct sockaddr_in cliaddr,servaddr;

struct hostent *h;

/*This function looks up a hostname and it returns a pointer to

a hostent structure that contains all the IPV4 address*/


/*Socket address structure*/ servaddr.sin_family=AF_INET;

memcpy((char *)&servaddr.sin_addr.s_addr,h->h_addr_list[0],h-
>h_length); servaddr.sin_port = htons(1999);

/*Creating a socket, assigning IP address and port number for

that socket*/ sd = socket(AF_INET,SOCK_STREAM,0);
/*Connect establishes connection with the server using server IP
address*/ cd=connect(sd,(struct


{ printf("Enter the message: \n");

/*Reads the message from standard

input*/ fgets(buff,100,stdin);

/*Send function is used on client side to send data given by

user on client side to the server*/

+1,0); printf("\n Data
Sent ");
)+1,0); printf("%s",buff);


AIM - Program for UDP Connection for Client Server on Single System

Server Side









int main(int argc,char *argv[])

int sd;

char buff[1024];

struct sockaddr_in cliaddr,servaddr; socklen_t clilen; clilen=sizeof(cliaddr);

/*UDP socket is created, an Internet socket address structure is filled with wildcard

address & server’s well known port*/


if (sd<0)

perror ("Cannot open Socket");



/*Socket address structure*/




/*Bind function assigns a local protocol address to the socket*/

if(bind(sd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0)

perror("error in binding the port");


printf("%s","Server is Running…\n");



/*Read the message from the client*/ if(recvfrom(sd,buff,sizeof(buff),0,(struct


perror("Cannot rec data"); exit(1);

printf("Message is received \n",buff);

/*Sendto function is used to echo the message from server to client side*/
if(sendto(sd,buff,sizeof(buff),0,(struct sockadddr*)&cliaddr,clilen)<0)

perror("Cannot send data to client"); exit(1);

printf("Send data to UDP Client: %s",buff);

close(sd); return 0;

Client Side








int main(int argc,char*argv[])

int sd;

char buff[1024];

struct sockaddr_in servaddr; socklen_t len; len=sizeof(servaddr);

/*UDP socket is created, an Internet socket address structure is filled with wildcard
address & server’s well known port*/

sd = socket(AF_INET,SOCK_DGRAM,0); if(sd<0)

perror("Cannot open socket"); exit(1);


/*Socket address structure*/ servaddr.sin_family=AF_INET;

servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(5669);


printf("Enter Input data : \n"); bzero(buff,sizeof(buff));

/*Reads the message from standard input*/ fgets(buff,sizeof (buff),stdin);

/*sendto is used to transmit the request message to the server*/ if(sendto (sd,buff,sizeof
(buff),0,(struct sockaddr*)&servaddr,len)<0)

perror("Cannot send data"); exit(1);

printf("Data sent to UDP Server:%s",buff); bzero(buff,sizeof(buff));

/*Receiving the echoed message from server*/

if(recvfrom (sd,buff,sizeof(buff),0,(struct sockaddr*)&servaddr,&len)<0)

perror("Cannot receive data"); exit(1);

printf("Received Data from server: %s",buff);

close(sd); return 0;


AIM - Program for TCP Connection of Client Server on two system

Server Side



public class MyServer1

ServerSocket ss;

Socket s;

DataInputStream dis;

DataOutputStream dos;

public MyServer1()


System.out.println("Server Started");

ss=new ServerSocket(10);



System.out.println("CLIENT CONNECTED");

dis= new DataInputStream(s.getInputStream());

dos= new DataOutputStream(s.getOutputStream());


catch(Exception e)


public static void main (String as[])

new MyServer1();

public void ServerChat() throws IOException

String str, s1;



System.out.println("Client Message:"+str);

BufferedReader br=new BufferedReader(new InputStreamReader(;





Client Side



public class MyClient1

Socket s;

DataInputStream din;

DataOutputStream dout;

public MyClient1()


//s=new Socket(",10");

s=new Socket("localhost",10);


din= new DataInputStream(s.getInputStream());

dout= new DataOutputStream(s.getOutputStream());


catch(Exception e)


public void ClientChat() throws IOException

BufferedReader br= new BufferedReader(new InputStreamReader(;

String s1;





System.out.println("Server Message:"+din.readUTF());


public static void main(String as[])

new MyClient1();


AIM - Program for UDP Connection of Client Server on two system

Server Side

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <stdio.h>

#include <unistd.h>

#include <errno.h>

#include <string.h>

#include <stdlib.h>

int main()

int sock;

int IPlength, TotalByte;

char message[512];

struct sockaddr_in serverAdd , clientAdd;

if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)

perror("Socket Creation Failed");


serverAdd.sin_family = AF_INET;

serverAdd.sin_port = htons(5000);

serverAdd.sin_addr.s_addr = INADDR_ANY;


if (bind(sock,(struct sockaddr *)&serverAdd,sizeof(struct sockaddr)) == -1)

perror("Bind Error");


IPlength = sizeof(struct sockaddr);

printf("\nUDP Server Waiting for client Message\n");


while (1)

TotalByte = recvfrom(sock,message,512,0,(struct sockaddr *)&clientAdd, &IPlength);

message[TotalByte] = '\0';

printf("Received Message: %s", message);


return 0;

Client Side

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <netdb.h>

#include <stdio.h>

#include <unistd.h>

#include <errno.h>

#include <string.h>

#include <stdlib.h>

int main()

int sock;

struct sockaddr_in serverAdd;

struct hostent *host;

char sendMessage[512];

host= (struct hostent *) gethostbyname((char *)"Server’s IP address");

if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)

perror("socket Creation Failed");


serverAdd.sin_family = AF_INET;

serverAdd.sin_port = htons(5000);

serverAdd.sin_addr = *((struct in_addr *)host->h_addr);


while (1)

printf("Enter the Message:");


sendto(sock, sendMessage, strlen(sendMessage), 0,(struct sockaddr *)&serverAdd,

sizeof(struct sockaddr));

memset (sendMessage , 0 , sizeof(sendMessage));