Top Banner
NETWORK PROGRAMMING Lab Manual IV / IV B.Tech. I st Semester Information Technology LAKIREDDY BALIREDDY COLLEGE OF ENGINEERING(AUTONOMOUS) (Affiliated to JNTU, Hyderabad, Approved by AICTE, Accredited by NBA, New Delhi) LB REDDY NAGAR, MYLAVARAM 521 230, KRISHNA(Dist), A.P. INDIA Website: www.lbrce.com Fax: 08659-222931
70
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: NP LAB

NETWORK PROGRAMMING

Lab Manual

IV / IV B.Tech. Ist Semester

Information Technology

LAKIREDDY BALIREDDY COLLEGE OF ENGINEERING(AUTONOMOUS)

(Affiliated to JNTU, Hyderabad, Approved by AICTE, Accredited by NBA, New Delhi)

LB REDDY NAGAR, MYLAVARAM – 521 230, KRISHNA(Dist), A.P. INDIA

Website: www.lbrce.com Fax: 08659-222931

Page 2: NP LAB

Week1.

Implement the following forms of IPC.

a)Pipes

b)FIFO

Week2.

Implement file transfer using Message Queue form of IPC

Week3.

Write a program to create an integer variable using shared memory concept and

increment the variable

simultaneously by two processes. Use semaphores to avoid race conditions

Week4.

Design TCP iterative Client and server application to reverse the given input sentence

Week5.

Design TCP iterative Client and server application to reverse the given input sentence

Week6.

Design TCP client and server application to transfer file

Week7.

Design a TCP concurrent server to convert a given text into upper case using multiplexing

system call “select”

Week8.

Design a TCP concurrent server to echo given set of sentences using poll functions

Week9.

Design UDP Client and server application to reverse the given input sentence

Page 3: NP LAB

Introduction

The Internet is all about connecting machines together. One of the most exciting aspects of

Java is that it incorporates an easy-to-use, cross-platform model for network communications that

makes it possible to learn network programming without years of study. This opens up a whole new

class of applications to programmers.

What is a Socket?

Java's socket model is derived from BSD (UNIX) sockets, introduced in the early 1980s for

interprocess communication using IP, the Internet Protocol.

The Internet Protocol breaks all communications into packets, finite-sized chunks of data which

are separately and individually routed from source to destination. IP allows routers, bridges, etc. to

drop packets--there is no delivery guarantee. Packet size is limited by the IP protocol to 65535 bytes.

Of this, a minimum of 20 bytes is needed for the IP packet header, so there is a maximum of 65515

bytes available for user data in each packet.

Sockets are a means of using IP to communicate between machines, so sockets are one major

feature that allows Java to interoperate with legacy systems by simply talking to existing servers using

their pre-defined protocol.

Other common protocols are layered on top of the Internet protocol. The ones we discuss in

this chapter are the User Datagram Protocol (UDP) and the Transmission Control Protocol (TCP).

Applications can make use of these two protocols to communicate over the network, commonly by

building additional protocols on top of the TCP or UDP base.

Internet Addresses

Internet addresses are manipulated in Java by the use of the InetAddress class. InetAddress takes care

of the Domain Name System (DNS) look-up and reverse look-up; IP addresses can be specified by

either the host name or the raw IPaddress. InetAddres provides methods to getByName(),

getAllByName(),getLocalHost(), getAddress(), etc.

Page 4: NP LAB

IP Addresses

IP addresses are a 32-bit number, often represented as a "quad" of four 8-bit

numbers separated by periods. They are organized into classes (A, B, C, D, and

E) which are used to group varying numbers of hosts in a hierarchical numbering

scheme.

Class A

1.0.0.0 to 126.255.255.255, inclusive. About 16 million IP addresses in a class A

domain.

Class B

128.1.0.0 to 191.254.255.255, inclusive. About 64 thousand IP addresses in a

class B domain.

Class C

192.0.1.0 to 223.255.254.255, inclusive. 256 IP addresses in a class C domain.

Class D

224.0.0.1 to 239.255.255.255, inclusive, denote multicast groups.

Class E

240.0.0.0 to 254.255.255.255, inclusive. Reserved for future use.

The IP address 127.0.0.1 is special, and is reserved to represent the loopback or

"localhost" address.

Port number

The port number field of an IP packet is specified as a 16-bit unsigned integer.

This means that valid port numbers range from 1 through 65535. (Port number 0

is reserved and can't be used).

Page 5: NP LAB

Java does not have any unsigned data types; Java's short data type is 16 bits, but its range is -32768 to

32767 since it is a signed type. Thus, short is not large enough to hold a port number, so all classes

which use or return a port number must represent the port number as an int. In the JDK 1.1, using an

int with a value greater than 65535 will generate an IllegalArgumentException. In the JDK 1.0.2 and

earlier, values greater than 65535 are truncated and only the loworder 16 bits are used.

Port numbers 1 through 255 are reserved by IP for well-known services. A well-known service is a

service that is widely implemented which resides at a published, "well-known", port. If you connect to

port 80 of a host, for instance, you may expect to find an HTTP server. On UNIX machines, ports less

than1024 are privileged and can only be bound by the root user. This is so an arbitrary user on a multi-

user system can't impersonate well-known services like TELNET (port 23), creating a security problem.

Windows has no such restrictions, but you should program as if it did so that your applications will

work cross-platform.

Client/Server Computing

You can use the Java language to communicate with remote file systems using

client/server model. A server listens for connection requests from clients across the network or even

from the same machine. Clients know how to connect to the server via an IP address and port number.

Upon connection, the server reads the request sent by the client and responds appropriately. In this

way, applications can be broken down into specific tasks that are accomplished in separate locations.

The data that is sent back and forth over a socket can be anything you like. Normally, the client sends a

request for information or processing to the server, which performs a task or sends data back. You

could, for example, place an SQL shell on the server and let people talk to it via a simple client "chat"

program. The IP and port number of the server is generally well-known and advertised so the client

knows where to find the service. In contrast, the port number on client the side is generally allocated

automatically by the kernel.

Many protocols used on the Internet (HTTP for example) are designed to be driven from the command

line. They send their requests and responses across the net in plain text. One of the easiest ways to

become familiar with network programming and/or specific protocols is to use the TELNET application

to "talk “directly to a server from the command line.

User Datagram Protocol (UDP)

UDP provides an unreliable packet delivery system built on top of the IPprotocol. As with IP, each

packet is an individual, and is handled separately. Because of this, the amount of data that can be sent

in a UDP packet is limited to the amount that can be contained in a single IP packet. Thus, a UDP

Page 6: NP LAB

packet can contain at most 65507 bytes (this is the 65535-byte IP packet size minus the minimum IP

header of 20 bytes and minus the 8-byte UDP header).

UDP packets can arrive out of order or not at all. No packet has any knowledge of the preceding or

following packet. The recipient does not acknowledge packets, so the sender does not know that the

transmission was successful. UDP has no provisions for flow control--packets can be received faster

than they can be used. We call this type of communication connectionless because the packets have no

relationship to each other and because there is no state maintained.

The destination IP addresses and port number is encapsulated in each UDP packet. These two numbers

together uniquely identify the recipient and are used by the underlying operating system to deliver the

packet to a specific process(application).

One way to think of UDP is by analogy to communications via a letter. You write the letter (this is the

data you are sending); put the letter inside an envelope (the UDP packet); address the envelope (using

an IP address and a port number); put your return address on the envelope (your local IP address and

port number); and then you send the letter.

Like a real letter, you have no way of knowing whether a UDP packet was received. If you send a

second letter one day after the first, the second one may be received before the first. Or, the second

one may never be received.

So why use UDP if it unreliable? Two reasons: speed and overhead. UDP packets have almost no

overhead--you simply send them then forget about them. And they are fast, since there is no

acknowledgement required for each packet. Keep in mind the degree of unreliability we are talking

about. For all practical purposes, an Ethernet breaks down if more than about 2 percent of all packets

are lost. So, when we say unreliable, the worst-case loss is very small.

UDP is appropriate for the many network services that do not require guaranteed delivery. An example

of this is a network time service. Consider a time daemon that issues a UDP packet every second so

computers on the LAN can synchronize their clocks. If a packet is lost, it's no big deal--the next one will

be by in another second and will contain all necessary information to accomplish the task.

Another common use of UDP is in networked, multi-user games, where a player's position is sent

periodically. Again, if one position update is lost, the next one will contain all the required information.

A broad class of applications is built on top of UDP using streaming protocols. With streaming

protocols, receiving data in real-time is far more important than guaranteeing delivery. Examples of

real-time streaming protocols are RealAudio and Real Video which respectively deliver real-time

streaming audio and video over the Internet. The reason a streaming protocol is desired in these cases

is because if an audio or video packet is lost, it is much better for the client to see this as noise or

"drop-out" in the sound or picture rather than having a long pause while the client software stops the

playback, requests the missing data from the server. That would result in a very choppy, busty playback

which most people find unacceptable, and which would place a heavy demand on the server.

Page 7: NP LAB

Creating UDP Servers

To create a server with UDP, do the following:

1. Create a Datagram Socket attached to a port.

int port = 1234;

DatagramSocket socket = new DatagramSocket(port);

2. Allocate space to hold the incoming packet, and create an instance of

DatagramPacket to hold the incoming data.

byte[] buffer = new byte[1024];

DatagramPacket packet =new DatagramPacket(buffer, buffer.length);

3. Block until a packet is received, then extract the information you need from the packet.

// Block on receive()

socket.receive(packet);

// Find out where packet came from

// so we can reply to the same host/port

InetAddress remoteHost = packet.getAddress();

int remotePort = packet.getPort();

// Extract the packet data

byte[] data = packet.getData();

The server can now process the data it has received from the client, and issue an

appropriate reply in response to the client's request.

Creating UDP Clients

Writing code for a UDP client is similar to what we did for a server. Again, weneed a DatagramSocket

and a DatagramPacket. The only real difference is thatwe must specify the destination address with each

packet, so the form of theDatagramPacket constructor used here specifies the destination host and

portnumber. Then, of course, we initially send packets instead of receiving.

Page 8: NP LAB

1. First allocate space to hold the data we are sending and create an instance of

DatagramPacket to hold the data.

byte[] buffer = new byte[1024];

int port = 1234;

InetAddress host = InetAddress.getByName("magelang.com");

DatagramPacket packet = new DatagramPacket(buffer, buffer.length,

host, port);

2. Create a DatagramSocket and send the packet using this socket.

DatagramSocket socket = new DatagramSocket();

socket.send(packet);

The DatagramSocket constructor that takes no arguments will allocate a free local port to use. You can

find out what local port number has been allocated for your socket, along with other information

about your socket if needed.

// Find out where we are sending from

InetAddress localHostname = socket.getLocalAddress();

int localPort = socket.getLocalPort();

The client then waits for a reply from the server. Many protocols require theserver to reply to the host

and port number that the client used, so the client cannow invoke socket.receive() to wait for

information from the server.

Transmission Control Protocol (TCP)

We saw in the previous section that UDP provides an unreliable packet delivery system--each packet is

an individual, and is handled separately. Packets can arrive out of order or not at all. The recipient does

not acknowledge them, so the sender does not know that the transmission was successful. There is no

provisions forflow control--packets can be received faster than they can be used. Packet size was

limited by the underlying IP protocol.

TCP, Transmission Control Protocol, was designed to address these problems.TCP packets are lost

occasionally, just like UDP packets. The difference is that the TCP protocol takes care of requesting

retransmits to ensure that all packets show up, and tracks packet sequence numbers to be sure that

they are delivered in the correct order. While UDP required us to send packets of byte arrays, with TCP

we can use streams along with the standard Java file I/O mechanism.

Page 9: NP LAB

Unlike UDP, the Transmission Control Protocol, TCP, establishes a connection between the two

endpoints. Negotiation is performed to establish a socket, and the socket remains open throughout the

duration of the communications. The recipient acknowledges each packet, and packet retransmissions

are performed by the protocol if packets are missed or arrive out of order. In this way TCP can allow an

application to send as much data as it desires and not be subject to the IP packet size limit. TCP is

responsible for breaking the data into packets, buffering the data, resending lost or out of order

packets, acknowledging receipt, and controlling rate of data flow by telling the sender to speed up or

slow down so that the application never receives more than it can handle.

Again, unlike UDP, the destination host and port number is not sufficient to identify a recipient of a

TCP connection. There are five distinct elements that make a TCP connection unique:

IP address of the server

IP address of the client

Port number of the server

Port number of the client

Protocol (UDP, TCP/IP, etc...)

where each requested client socket is assigned a unique port number whereas the server port number

is always the same. If any of these numbers is different, the socket is different. A server can thus listen

to one and only one port, and talk to multiple clients at the same time.

So a TCP connection is more like a telephone connection than a letter; you need to know not only the

phone number (IP address), but since the phone may be shared by many people at that location, you

also need the name of the user you want to talk to at the other end (port number). The analogy can be

taken a little further. If you don't hear what the other person has said, a simple request ("What?") will

prompt the other end to resend or repeat the phrase. And, the connection remains open until

someone hangs up.

Creating TCP Servers

To create a TCP server, do the following:

1. Create a ServerSocket attached to a port number.

Page 10: NP LAB

ServerSocket server = new ServerSocket(port);

2. Wait for connections from clients requesting connections to that port.

// Block on accept()

Socket channel = server.accept();

You'll get a Socket object as a result of the connection.

3. Get input and output streams associated with the socket.

out = new PrintWriter

(channel.getOutputStream());

reader = new InputStreamReader

(channel.getInputStream());

in = new BufferedReader (reader);

Now you can read and write to the socket, thus, communicating with the client.

String data = in.readLine();

out.println("Hey! I heard you over this socket!");

When a server invokes the accept() method of the Server Socket instance, the main server thread blocks

until a client connects to the server; it is then prevented from accepting further client connections until

the server has processed the client's request. This is known as an iterative server, since the main server

method handles each client request in its entirety before moving on to the next request. Iterative

servers are good when the requests take a known, short period of time. For example, requesting the

current day and time from a time-of-day server.

Creating TCP Clients

To create a TCP client, do the following:

1. Create a Socket object attached to a remote host, port.

Socket client = new Socket(host, port);

When the constructor returns, you have a connection.

2. Get input and output streams associated with the socket.

out = new PrintWriter

Page 11: NP LAB

(client.getOutputStream());

reader = new InputStreamReader

(client.getInputStream());

in = new BufferedReader (reader);

Now you can read and write to the socket, thus, communicating with the server.

out.println("Watson!" + "Come here...I need you!");

String data = in.readLine();

Servers Handling Multiple Clients

While iterative servers are simple, they are severely limited in their performance since only one client

at a time can be handled. In particular, when the amount of processing needed to handle a client

request is unknown a priori (i.e., depends on the request itself), iterative servers are unacceptable. A

TELNET session, for instance, can take an unbounded amount of time, so the server should not wait

until that session is over before accepting new clients.

To overcome this problem with iterative servers, a separate thread can handle each client session,

allowing the server to deal with multiple clients simultaneously. This is known as a concurrent server--

the main server method launches a thread to handle each client request, then continues to listen for

additional clients.

Here is an example server method called acceptClients() that listens for

connections and handles multiple clients, each in a separate thread:

public void acceptClients() {

Socket socket = null;

while (true) {

// For each connection, start a new handler

// in its own thread and keep on listening

Page 12: NP LAB

try {

socket = server.accept();

PrintWriter out =

new PrintWriter(socket.getOutputStream());

InputStreamReader reader =

new InputStreamReader(socket.getInputStream());

BufferedReader in = new BufferedReader(reader);

// Create new client handler

// and launch thread on it.

Handler h = new Handler(in, out);

(new Thread(h)).start();

}

catch (IOException e) {

System.err.println

("Error creating socket connection");

System.exit(1);

}

}

}

An enhancement to this server could be to pre-allocate a collection of Thread objects to be used for

handling client requests. This will allow the server to handle the requests quicker by utilizing a thread

from the pool rather than dynamically allocating one. In addition, it will allow the server to manage the

client connections for the purpose of limiting number of clients or setting timeout values for the client

connections.

Multithreaded Clients

In the previous section we learned why we needed to use threads in our server if we wanted to

simultaneously deal with multiple clients. It is not so clear why we would need more than one thread

for our client, but we generally do. The reason for this is that the I/O operations we perform on a

Page 13: NP LAB

socket generally block. So the client can read or write to the socket, but not both at the same time.

This poses a problem when the client does not know ahead of time how much data the server is going

to send back in response to the client's request. How many times should the client call readLine()?

Having one thread to read and one thread to write, we can ensure that we never enter into a situation

where the client fails to read the entire server response, or where the client is stuck waiting for too

much data from the server. Instead of creating two threads within your client, a more common

scenario would be to take advantage of the fact that the WT handles user input in a separate thread;

you can receive user input and send data over the socket from an AWT event handling method, while

your client class receives data in its run() method.

Sending Objects

TCP is a stream protocol; we can do anything with socket streams that we can with file streams. One

way we can greatly simplify communications between clients and servers written in Java is to use an

ObjectInputStream andObjectOutputStream combination to read and write objects across the socket.

This is a higher level of abstraction--we don't have to write int or float data

types, but we can send a whole object. For example:

1. First, define an object to send. We'll define a class called Message to encapsulate our

communications.

public class Message implements Serializable {

private int senderID;

private String messageText;

public Message(int id, String text) {

senderID = id;

messageText = text;

}

public String getText() {

return messageText;

}

}

Page 14: NP LAB

2. Next, instantiate the object; wrap the socket's streams in object streams; and then send the message

across the socket.

Message sayhey = new Message("123456789", "Hello");

out = new ObjectOutputStream(socket.getOutputStream());

in = new ObjectInputStream(socket.getInputStream());

out.writeObject(sayhey);

3. On the other side of the socket, the message can be retrieved and used by invoking methods on the

returned object.

Message messageObject = (Message) in.readObject();

String messageText = messageObject.getText();

Network Programming

Network Programming -12 © 1996-2003 jGuru.com. All Rights Reserved.

Socket APIs

* socket: creates a socket of a given domain, type, protocol

(buy a phone)

* bind: assigns a name to the socket (get a telephone number)

* listen: specifies the number of pending connections that

can be queued for a server socket. (call waiting allowance)

* accept: server accepts a connection request from a client

(answer phone)

* connect: client requests a connection request to a server

(call)

* send, sendto: write to connection (speak)

* recv, recvfrom: read from connection (listen)

* shutdown: end the call

Page 15: NP LAB

Server performs the following actions

* socket: create the socket

* bind: give the address of the socket on the server

* listen: specifies the maximum number of connection

requests that can be pending for this process

* accept: establish the connection with a specific client

* send,recv: stream-based equivalents of read and write

(repeated)

* shutdown: end reading or writing

* close: release kernel data structures

Client performs the following actions

* socket: create the socket

* connect: connect to a server

* send,recv: (repeated)

* shutdown

* close

Page 16: NP LAB
Page 17: NP LAB
Page 18: NP LAB
Page 19: NP LAB
Page 20: NP LAB
Page 21: NP LAB
Page 22: NP LAB
Page 23: NP LAB
Page 24: NP LAB

Week1:

AIM:Implement the following forms of IPC.

a) Pipes b) FIFO

a)PIPES:

PROGRAM:

PIPE.c:

#include <unistd.h>

#include <stdio.h>

#define MSGSIZE 16

char *msg1 = "hello #1";

char *msg2 = "hello #2";

char *msg3 = "hello #3";

main()

{ char inbuf[MSGSIZE];

int p[2], j;

/* open pipe */

if(pipe(p) == -1)

{ perror("pipe call error");

exit(1);

}

printf("read pipe fd=%d,write pipe fd= %d\n",p[0],p[1]);

/* write down pipe */

write(p[1], msg1, MSGSIZE);

write(p[1], msg2, MSGSIZE);

write(p[1], msg3, MSGSIZE);

/* read pipe */

for(j=0; j<3; j++)

{ read(p[0], inbuf, MSGSIZE);

printf("%s\n", inbuf);

}

Page 25: NP LAB

exit(0);

}

Output:

:~$ cc PIPE.c

:~$ ./a.out

read pipe fd=3,write pipe fd= 4

hello #1

hello #2

hello #3

b) FIFO:

PROGRAM:

fullduplex.h:

#define NP2 "/tmp/np2"

#define MAX_BUF_SIZE 255

fd_server.c:

#include <errno.h>

#include <ctype.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include "fullduplex.h" /* For name of the named-pipe */

#include <stdlib.h>

#include<string.h>

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

{

int rdfd, wrfd, ret_val, count, numread;

char buf[MAX_BUF_SIZE];

/* Create the first named - pipe */

ret_val = mkfifo(NP1, 0666);

if ((ret_val == -1) && (errno != EEXIST)) {

perror("Error creating the named pipe");

exit (1);

Page 26: NP LAB

}

ret_val = mkfifo(NP2, 0666);

if ((ret_val == -1) && (errno != EEXIST)) {

perror("Error creating the named pipe");

exit (1);

}

/* Open the first named pipe for reading */

rdfd = open(NP1, O_RDONLY);

/* Open the second named pipe for writing */

wrfd = open(NP2, O_WRONLY);

/* Read from the first pipe */

numread = read(rdfd, buf, MAX_BUF_SIZE);

buf[numread] = '0';

printf("Full Duplex Server : Read From the pipe : %s\n", buf);

/* Convert to the string to upper case */

count = 0;

while (count < numread) {

buf[count] = toupper(buf[count]);

count++;

}

write(wrfd, buf, strlen(buf));

}

7

fd_client.c:

#include <errno.h>

#include <ctype.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include "fullduplex.h" /* For name of the named-pipe */

#include <stdlib.h>

#include<string.h>

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

{

int wrfd, rdfd, numread;

char rdbuf[MAX_BUF_SIZE];

/* Check if an argument was specified. */

if (argc != 2) {

printf("Usage : %s <string to be sent to the server>\n", argv[0]);

exit (1);

Page 27: NP LAB

}

/* Open the first named pipe for writing */

wrfd = open(NP1, O_WRONLY);

/* Open the second named pipe for reading */

rdfd = open(NP2, O_RDONLY);

/* Write to the pipe */

write(wrfd, argv[1], strlen(argv[1]));

/* Read from the pipe */

numread = read(rdfd, rdbuf, MAX_BUF_SIZE);

rdbuf[numread] = '0';

printf("Full Duplex Client : Read From the Pipe : %s\n", rdbuf);

}

Output:

Run the server:

:~$ cc fd_server.c

:~$ ./a.out

The server program will block here, and the shell will return control to the

command line.

Run the client:

:~$ cc fd_client.c

:~$ ./a.out lbrce

The client program will send the string to server and block on the read

to await the server's response.

The server prints the following:

Full Duplex Server : Read From the pipe : lbrce

The client prints the following:

Full Duplex Client : Read From the pipe : LBRCE

Page 28: NP LAB

Week2:

AIM:Implement file transfer using Message Queue form of IPC

PROGRAM:

message_send.c:

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/msg.h>

#include <stdio.h>

#include <string.h>

#define MSGSZ 128

typedef struct msgbuf {

long mtype;

char mtext[MSGSZ];

} message_buf;

main()

{

int msqid;

int msgflg = IPC_CREAT | 0666;

key_t key;

message_buf sbuf;

size_t buf_length;

key = 1234;

if ((msqid = msgget(key, msgflg )) < 0) {

perror("msgget");

exit(1);

}

else

(void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid);

sbuf.mtype = 1;

(void) strcpy(sbuf.mtext, "WELCOME TO LBRCE");

Page 29: NP LAB

buf_length = strlen(sbuf.mtext) + 1 ;

if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) {

printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buf_length);

perror("msgsnd");

exit(1);

}

else

printf("Message: \"%s\" Sent\n", sbuf.mtext);

exit(0);

}

message_rec.c:

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/msg.h>

#include <stdio.h>

#define MSGSZ 128

typedef struct msgbuf {

long mtype;

char mtext[MSGSZ];

} message_buf;

main()

{

int msqid;

key_t key;

message_buf rbuf;

key = 1234;

if ((msqid = msgget(key, 0666)) < 0) {

perror("msgget");

exit(1);

Page 30: NP LAB

}

if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) {

perror("msgrcv");

exit(1);

}

printf("%s\n", rbuf.mtext);

exit(0);

}

Output:

:~$ cc message_send.c

:~$ ./a.out

msgget: msgget succeeded: msqid = 0

Message: "WELCOME TO LBRCE" Sent

:~$ cc message_rec.c

:~$ ./a.out

WELCOME TO LBRCE

Page 31: NP LAB

Week3:

AIM:Write a program to create an integer variable using shared memory concept and

increment the variable simultaneously by two processes. Use semaphores to avoid race

conditions.

PROGRAM:

sheredserver.c:

#include <string.h>

#include <sys/ipc.h>

#include <sys/sem.h>

#include <sys/shm.h>

#define SEMKEYPATH "/dev/null" /* Path used on ftok for semget key */

#define SEMKEYID 1 /* Id used on ftok for semget key */

#define SHMKEYPATH "/dev/null" /* Path used on ftok for shmget key */

#define SHMKEYID 1 /* Id used on ftok for shmget key */

#define NUMSEMS 2 /* Num of sems in created sem set */

#define SIZEOFSHMSEG 50 /* Size of the shared mem segment */

#define NUMMSG 2 /* Server only doing two "receives"

on shm segment */

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

{

int rc, semid, shmid, i;

key_t semkey, shmkey;

void *shm_address;

struct sembuf operations[2];

struct shmid_ds shmid_struct;

short sarray[NUMSEMS];

/* Generate an IPC key for the semaphore set and the shared */

/* memory segment. Typically, an application specific path and */

/* id would be used to generate the IPC key. */

semkey = ftok(SEMKEYPATH,SEMKEYID);

if ( semkey == (key_t)-1 )

{

printf("main: ftok() for sem failed\n");

Page 32: NP LAB

return -1;

}

shmkey = ftok(SHMKEYPATH,SHMKEYID);

if ( shmkey == (key_t)-1 )

{

printf("main: ftok() for shm failed\n");

return -1;

}

semid = semget( semkey, NUMSEMS, 0666 | IPC_CREAT | IPC_EXCL );

if ( semid == -1 )

{

printf("main: semget() failed\n");

return -1;

}

sarray[1] = 0;

if(rc == -1)

{

printf("main: semctl() initialization failed\n");

return -1;

}

if (shmid == -1)

{

printf("main: shmget() failed\n");

return -1;

}

if ( shm_address==NULL )

{

printf("main: shmat() failed\n");

return -1;

}

printf("Ready for client jobs\n");

/* Loop only a specified number of times for this example. */

for (i=0; i < NUMMSG; i++)

{

operations[0].sem_num = 1;

/* Operate on the second sem */

operations[0].sem_op = -1;

Page 33: NP LAB

/* Decrement the semval by one */

operations[0].sem_flg = 0;

/* Allow a wait to occur */

operations[1].sem_num = 0;

/* Operate on the first sem */

operations[1].sem_op = 1;

/* Increment the semval by 1 */

operations[1].sem_flg = IPC_NOWAIT;

/* Do not allow to wait */

rc = semop( semid, operations, 2 );

if (rc == -1)

{

printf("main: semop() failed\n");

return -1;

}

/* Print the shared memory contents. */

printf("Server Received : \"%s\"\n", (char *) shm_address);

/* Signal the first semaphore to free the shared memory. */

operations[0].sem_num = 0;

operations[0].sem_op = -1;

operations[0].sem_flg = IPC_NOWAIT;

rc = semop( semid, operations, 1 );

if (rc == -1)

{

printf("main: semop() failed\n");

return -1;

}

} /* End of FOR LOOP */

if (rc==-1)

{

printf("main: semctl() remove id failed\n");

return -1;

}

rc = shmdt(shm_address);

if (rc==-1)

{

Page 34: NP LAB

printf("main: shmdt() failed\n");

return -1;

}

rc = shmctl(shmid, IPC_RMID, &shmid_struct);

if (rc==-1)

{

printf("main: shmctl() failed\n");

return -1;

}

return 0;

}

sheredclient.c:

#include <stdio.h>

#include <string.h>

#include <sys/ipc.h>

#include <sys/sem.h>

#include <sys/shm.h>

#define SEMKEYPATH "/dev/null" /* Path used on ftok for semget key */

#define SEMKEYID 1 /* Id used on ftok for semget key */

#define SHMKEYPATH "/dev/null" /* Path used on ftok for shmget key */

#define SHMKEYID 1 /* Id used on ftok for shmget key */

#define NUMSEMS 2

#define SIZEOFSHMSEG 50

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

{

struct sembuf operations[2];

void *shm_address;

int semid, shmid, rc;

key_t semkey, shmkey;

/* Generate an IPC key for the semaphore set and the shared */

/* memory segment. Typically, an application specific path and */

/* id would be used to generate the IPC key. */

semkey = ftok(SEMKEYPATH,SEMKEYID);

if ( semkey == (key_t)-1 )

{

printf("main: ftok() for sem failed\n");

return -1;

Page 35: NP LAB

}

shmkey = ftok(SHMKEYPATH,SHMKEYID);

if ( shmkey == (key_t)-1 )

{

printf("main: ftok() for shm failed\n");

return -1;

}

if ( semid == -1 )

{

printf("main: semget() failed\n");

return -1;

}

if (shmid == -1)

{

printf("main: shmget() failed\n");

return -1;

}

/* Attach the shared memory segment to the client process. */

shm_address = shmat(shmid, NULL, 0);

if ( shm_address==NULL )

{

printf("main: shmat() failed\n");

return -1;

}

/* Operate on the first sem */

operations[0].sem_op = 0;

/* Wait for the value to be=0 */

operations[0].sem_flg = 0;

/* Allow a wait to occur */

operations[1].sem_num = 0;

/* Operate on the first sem */

operations[1].sem_op = 1;

/* Increment the semval by one */

operations[1].sem_flg = 0;

/* Allow a wait to occur */

rc = semop( semid, operations, 2 );

if (rc == -1)

Page 36: NP LAB

{

printf("main: semop() failed\n");

return -1;

}

strcpy((char *) shm_address, "Hello from Client");

/* Operate on the first sem */

operations[0].sem_op = -1;

/* Decrement the semval by one */

operations[0].sem_flg = 0;

/* Allow a wait to occur */

operations[1].sem_num = 1;

/* Operate on the second sem */

operations[1].sem_op = 1;

/* Increment the semval by one */

operations[1].sem_flg = 0;

/* Allow a wait to occur */

rc = semop( semid, operations, 2 );

if (rc == -1)

{

printf("main: semop() failed\n");

return -1;

}

/* Detach the shared memory segment from the current process. */

rc = shmdt(shm_address);

if (rc==-1)

{

printf("main: shmdt() failed\n");

return -1;

}

return 0;

}

Page 37: NP LAB

Output:

At server side:

:~$ cc sheredserver.c

Ready for client jobs

Server Received : "Hello from Client"

Server Received : "Hello from Client"

At client side:

:~$ cc sheredclient.c

:~$ ./a.out

:~$ cc sheredclient.c

:~$ ./a.out

Page 38: NP LAB

Week4:

AIM:Design TCP iterative Client and server application to reverse the given input

sentence

PROGRAM:

server2.c:

#include<stdlib.h>

#include<errno.h>

#include<string.h>

#include<sys/types.h>

#include<sys/socket.h>

#include<sys/un.h>

#define SOCK_PATH "echo_socket"

int main(void)

{

int s,s2,t,len,i,j;

struct sockaddr_un local,remote;

char str[100],str2[100],c;

if((s=socket(AF_UNIX,SOCK_STREAM,0))==-1)

{

perror("socket");

exit(1);

}

local.sun_family=AF_UNIX;

strcpy(local.sun_path,SOCK_PATH);

unlink(local.sun_path);

len=strlen(local.sun_path)+sizeof(local.sun_family);

if(bind(s,(struct sockaddr *)&local,len)==-1)

{

perror("bind");

exit(1);

}

if(listen(s,5)==-1)

{

perror("listen");

exit(1);

}

for( ; ;)

{

Page 39: NP LAB

int done,n;

printf("Waiting for a Connection...\n");

t=sizeof(remote);

if((s2=accept(s,(struct sockaddr *)&remote,&t))==-1)

{

perror("accept");

exit(1);

}

printf("Connected....\n");

done=0;

do

{

n=recv(s2,str,100,0);

if(n<=0)

{

if(n<0)

perror("recv");

done=1;

}

if(!done)

i=0;j=n-1;

while(i<=j)

{

c=str[i];

str[i]=str[j];

str[j]=c;

i++;

j--;

}

if(send(s2,str,n,0)<0)

{

perror("send");

done=1;

}

}while(!done);

close(s2);

}

return 0;

}

Page 40: NP LAB

client2.c:

#include<ctype.h>

#include<stdio.h>

#include<stdlib.h>

#include<errno.h>

#include<string.h>

#include<sys/types.h>

#include<sys/socket.h>

#include<sys/un.h>

#define SOCK_PATH "echo_socket"

int main(void)

{

int s,t,len;

struct sockaddr_un remote;

char str[100];

if((s=socket(AF_UNIX,SOCK_STREAM,0))==-1)

{

perror("Socket");

exit(1);

}

printf("Trying to connect...\n");

remote.sun_family=AF_UNIX;

strcpy(remote.sun_path,SOCK_PATH);

len=strlen(remote.sun_path)+sizeof(remote.sun_family);

if(connect(s,(struct sockaddr *)&remote,len)==-1)

{

perror("connect");

exit(1);

}

printf("Connected.....\n");

while(printf(">"),fgets(str,100,stdin),!feof(stdin))

{

if(send(s,str,strlen(str),0)==-1)

{

perror("send");

exit(1);

}

if((t=recv(s,str,100,0))>0)

{

Page 41: NP LAB

str[t]='\0';

printf("Reverse : %s \n",str);

}

else

{

if(t<0)

perror("recv");

else

printf("Server closed Connection..\n");

exit(1);

}

}

close(s);

return 0;

}

Output:

At server side:

:~$ cc server2.c

:~$ ./a.out

Waiting for a Connection...

Connected....

At Client side:

:~$ cc client2.c

:~$ ./a.out

Trying to connect...

Connected.....

>lbrce

Reverse :

ecrbl

>hello

Reverse :

olleh

Page 42: NP LAB

Week5:

AIM:Design TCP client and server application to transfer file

PROGRAM:

fserver.c:

#include<sys/types.h>

#include<netinet/in.h>

#include<arpa/inet.h>

#include<stdio.h>

#define PORT 2080

main(){

int sock1,sock2,clength;

sock1=socket(AF_INET,SOCK_STREAM,0);

struct sockaddr_in serv,cli;

serv.sin_family=AF_INET;

serv.sin_port=htons(PORT);

serv.sin_addr.s_addr=inet_addr("127.0.0.1");

bind(sock1,(struct sockaddr *)&serv,sizeof(serv));

listen(sock1,5);

clength=sizeof(cli);

int i=0;

char buf[50];

sock2=accept(sock1,(struct sockaddr *)&cli,&clength);

printf("\n Client Connected..\n");

FILE* fp=fopen("server2.txt","r");

while(!feof(fp))

{

//bzero(buf,sizeof(buf));

fread(buf,sizeof(char),50,fp);

write(sock2,buf,50);

}

write(sock2,"quit1234",50);

fclose(fp);

return 0;

}

Page 43: NP LAB

fclient.c:

#include<sys/socket.h>

#include<sys/types.h>

#include<netinet/in.h>

#include<arpa/inet.h>

#include<stdio.h>

#define PORT 2080

main()

{

int sock1;

sock1=socket(AF_INET,SOCK_STREAM,0);

struct sockaddr_in serv;

serv.sin_port=htons(PORT);

printf("%x %x\n",PORT,htons(PORT));

serv.sin_family=AF_INET;

serv.sin_addr.s_addr=inet_addr("127.0.0.1");

printf("Client Connecting.....");

connect(sock1,(struct sockaddr *)&serv,sizeof(serv));

char buf[50];

FILE* fp=fopen("client2.txt","w");

while(1)

{

//bzero(buf,sizeof(buf));

read(sock1,buf,50);

if(strcmp(buf,"quit1234")==0)

{

break;

}

fprintf(fp,"%s",buf);

}

fclose(fp);

}

Page 44: NP LAB

Output:

:~$vi server2.txt

Hello

How r u

Iam Fine....

At server side:

:~$ cc fserver.c

:~$ ./a.out

Client Connected..

At client side:

:~$ cc fclient.c

:~$ ./a.out

820 2008

Client Connecting.....

:~$ cat client2.txt

Hello

How r u

Iam Fine....

Page 45: NP LAB

Week6:

AIM:a)Design a TCP iterative server to convert a given text into upper case using

multiplexing system call “select”

.

PROGRAM:

iservertcp_select.c:

#include <stdio.h> /* for standard I/O */

#include <unistd.h> /* for read() and write() */

#include <strings.h> /* for bzero() */

#include <stdlib.h> /* for atoi() */

#include <sys/types.h> /* for accept() and connect() */

#include <sys/socket.h>

#include <sys/errno.h> /* for perror() */

#include <sys/select.h> /* for select() */

#include <netinet/in.h> /* for htonl() */

#define FD_SETSIZE 1

#define LISTENQ 2

#define BSIZE 256

#define USAGE "./iservertcp_select portno\n"

void error(char *msg)

Page 46: NP LAB

{

perror(msg);

exit(1);

}

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

{

int listenfd, connfd;/* socket file descriptor */

int j;

int portno;

socklen_t clilen;

char buffer[BSIZE];

struct sockaddr_in serv_addr, cli_addr;

int n;

/* variable declarations for select() */

int i, maxi, maxfd, sockfd;

int nready, client[FD_SETSIZE];

fd_set rset, allset; /* the bitmap */

if (argc < 2)

error(USAGE);

Page 47: NP LAB

/* create a listening socket */

listenfd = socket(PF_INET, SOCK_STREAM, 0);

if (listenfd < 0)

error("ERROR opening socket");

bzero((char *) &serv_addr, sizeof(serv_addr));

serv_addr.sin_family = AF_INET;

serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

portno = atoi(argv[1]);

serv_addr.sin_port = htons(3456);

if (bind(listenfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)

error("ERROR on binding");

listen(listenfd, LISTENQ);

maxfd = listenfd; /* the maximum fd so far */

maxi = -1; /* index to the client[] array */

for (i=0; i<=FD_SETSIZE;i++) /* initialize the client array */

client[i] = -1;

FD_ZERO(&allset); /* initialize the descriptor set */

FD_SET(listenfd, &allset); /* set the corresponding bit to on */

while (1) {

rset = allset; /* reset rset (a dynamic bitmap) */

nready = select(maxfd+1, &rset, NULL, NULL, NULL);

Page 48: NP LAB

if (FD_ISSET(listenfd, &rset)) {

/* accept connections */

clilen = sizeof(cli_addr);

connfd = accept(listenfd, (struct sockaddr *) &cli_addr, &clilen);

if (connfd < 0)

error("ERROR on accept");

for (i=0; i<FD_SETSIZE;i++)

if (client[i] < 0) {

client[i] = connfd;

break;

}

FD_SET(connfd, &allset); /* update the descriptor set (a static bitmap) */

if (connfd > maxfd) /* maxfd always records the largest fd */

maxfd = connfd;

if (i > maxi) /* update the index to the client array */

maxi = i;

if (--nready <= 0)

continue;

}

for (i=0; i<=maxi;i++) {

Page 49: NP LAB

if ((sockfd = client[i]) < 0)

continue;

if (FD_ISSET(sockfd, &rset)) {

bzero(buffer, BSIZE);

n = read(sockfd, buffer, BSIZE-1);

if (n < 0)

error("ERROR reading from socket");

if (n == 0) { /* receives a FIN package, close connection */

close(sockfd); /* close the socket */

FD_CLR(sockfd, &allset); /* clear off the descriptor set */

client[i] = -1; /* reset that entry in client array */

} else { /* if n>0, echo back */

for(j=0;j<strlen(buffer);j++)

{

if(buffer[j]>=65&&buffer[j]<=90)

{

buffer[j]+=32;

}

else if(buffer[j]>=97&&buffer[j]<=122)

Page 50: NP LAB

{

buffer[j]-=32;

}

}

printf("Here is the message: %s\n", buffer);

fflush(stdout);

n = write(sockfd, "I got your message", 18);

if (n < 0)

error("ERROR writing to socket");

if (--nready <= 0)

break;

}

}

}

}

return 0;

}

iclienttcp.c:

#include <stdio.h> /* for standard I/O */

#include <unistd.h> /* for read() and write() */

Page 51: NP LAB

#include <strings.h> /* for bzero() */

#include <stdlib.h> /* for atoi() */

#include <sys/socket.h>

#include <sys/types.h> /* for accept() and connect() */

#include <sys/errno.h> /* for perror() */

#include <netinet/in.h> /* for htonl() */

#include <netdb.h> /* for gethostbyname() */

#define BSIZE 256

#define USAGE "./iclienttcp server portno\n"

void error(char *msg)

{

perror(msg);

exit(1);

}

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

{

int connfd; /* socket file descriptor */

int portno;

Page 52: NP LAB

struct hostent *server;

char buffer[BSIZE];

struct sockaddr_in serv_addr;

int n;

if (argc < 3)

error(USAGE);

connfd = socket(PF_INET, SOCK_STREAM, 0);

if (connfd < 0)

error("ERROR opening socket");

bzero((char *) &serv_addr, sizeof(serv_addr));

serv_addr.sin_family = AF_INET;

server = gethostbyname(argv[1]);

if (server == NULL)

error("ERROR, no such host\n");

bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);

portno = atoi(argv[2]);

serv_addr.sin_port = htons(3456);

/* connect to server */

if (connect(connfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)

error("ERROR connecting");

Page 53: NP LAB

/* start sending message */

while(1) { /** just add a while loop here for iterative client **/

printf("Please enter the message: ");

bzero(buffer, BSIZE);

fgets(buffer, BSIZE-1, stdin);

n = write(connfd, buffer, strlen(buffer));

if (n < 0)

error("ERROR writing to socket");

bzero(buffer, BSIZE);

n = read(connfd, buffer, BSIZE-1);

if (n < 0)

error("ERROR reading from socket");

printf("%s\n\n", buffer);

fflush(stdout);

}

return 0;

}

Page 54: NP LAB

Output:

At server side:

:~$ cc iservertcp_select.c

:~$ ./a.out 3456

Here is the message: LBRCE

Here is the message: HELLO

Here is the message: HOW R U

Here is the message: IAM FINE HERE.....

At Client side:

:~$ cc iclienttcp.c

:~$ ./a.out 127.0.0.1 3456

Please enter the message: lbrce

I got your message

Please enter the message: hello

I got your message

Please enter the message: how r u

I got your message

Page 55: NP LAB

Please enter the message: iam fine here.....

I got your message

6 b)AIM: Design a TCP concurrent server to convert a given text into upper case using

multiplexing system call “select”

.

PROGRAM:

tcpservselect01.c:

#include <stdlib.h>

#include <unistd.h>

#include <errno.h>

#include <string.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <sys/select.h>

#include <sys/time.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <fcntl.h>

#define MAXLINE 100

#define SERV_PORT 13153

int main(int argc, char **argv)

{

int k, i, maxi, maxfd, listenfd, connfd, sockfd;

int nready, client[FD_SETSIZE];

ssize_t n;

fd_set rset, allset;

char line[MAXLINE],buf[100];

socklen_t clilen;

struct sockaddr_in cliaddr, servaddr;

listenfd = socket(AF_INET, SOCK_STREAM, 0);

if (listenfd < 0 )

{

perror("socket" );

Page 56: NP LAB

exit(1);

}

bzero(&servaddr, sizeof(servaddr));

servaddr.sin_family = AF_INET;

servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

servaddr.sin_port = htons(SERV_PORT);

bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

listen(listenfd,5);

maxfd = listenfd; /* initialize */

maxi = -1; /* index into client[] array */

for (i = 0; i < FD_SETSIZE; i++)

client[i] = -1; /* -1 indicates available entry */

FD_ZERO(&allset);

FD_SET(listenfd, &allset);

/* end fig01 */

/* include fig02 */

for ( ; ; ) {

printf("\n\nServer:I am waiting-----\n");

rset = allset; /* structure assignment */

nready = select(maxfd+1, &rset, NULL, NULL, NULL);

if (FD_ISSET(listenfd, &rset)) { /* new client connection */

clilen = sizeof(cliaddr);

connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);

#ifdef NOTDEF

printf("new client: %s, port %d\n",

inet_ntop(AF_INET, &cliaddr.sin_addr, buf, NULL),

ntohs(cliaddr.sin_port));

#endif

for (i = 0; i < FD_SETSIZE; i++)

if (client[i] < 0) {

client[i] = connfd; /* save descriptor */

break;

}

if (i == FD_SETSIZE)

{

printf("too many clients");

exit(0);

}

FD_SET(connfd, &allset); /* add new descriptor to set */

if (connfd > maxfd)

maxfd = connfd; /* for select */

if (i > maxi)

Page 57: NP LAB

maxi = i; /* max index in client[] array */

if (--nready <= 0)

continue; /* no more readable descriptors

*/

}

for (i = 0; i <= maxi; i++) { /* check all clients for data */

if ( (sockfd = client[i]) < 0)

continue;

if (FD_ISSET(sockfd, &rset)) {

if ( (n = read(sockfd, line, MAXLINE)) == 0) {

/*4connection closed by client */

close(sockfd);

FD_CLR(sockfd, &allset);

client[i] = -1;

} else

{

printf("\n output at server\n");

for(k=0;line[k]!='\0';k++)

printf("%c ",toupper(line[k]));

write(sockfd, line, n);

}

if (--nready <= 0)

break; /* no more readable descriptors

*/

}

}

}

}

tcpclient1.c:

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <errno.h>

#include <string.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <fcntl.h>

Page 58: NP LAB

#define MAXBUFFER 1024

void sendstring(int , char *);

int main( int C, char *V[] )

{

int sd,fd;

char c;

struct sockaddr_in serveraddress;

char text[100];

int i=0;

sd = socket( AF_INET, SOCK_STREAM, 0 );

if( sd < 0 ) {

perror( "socket" );

exit( 1 );

}

if (V[1] == NULL ) {

printf ("PL specfiy the server's IP Address \n");

exit(0);

}

if (V[2] == NULL ) {

printf ("PL specify the server's Port No \n");

exit(0);

}

memset( &serveraddress, 0, sizeof(serveraddress) );

serveraddress.sin_family = AF_INET;

serveraddress.sin_port = htons(atoi(V[2]));//PORT NO

serveraddress.sin_addr.s_addr = inet_addr(V[1]);//ADDRESS

if (connect(sd,(struct sockaddr*)&serveraddress,

sizeof(serveraddress))<0)

{

printf("Cannot Connect to server");

exit(1);

}

printf("enter sentence to end enter #");

while(1)

{

c=getchar();

if(c=='#')

break;

text[i++]=c;

}

text[i]='\0';

sendstring(sd,text);

close(sd);

Page 59: NP LAB

return 0;

}

void sendstring(

int sd, /*Socket Descriptor*/

char *fname) /*Array Containing the string */

{ int n , byteswritten=0 , written ;

char buffer[MAXBUFFER];

strcpy(buffer , fname);

n=strlen(buffer);

while (byteswritten<n)

{

written=write(sd , buffer+byteswritten,(n-byteswritten));

byteswritten+=written;

}

printf("String : %s -----> sent to server \n",buffer);

}

Output:

At server side:

:~$ cc tcpservselect01.c

:~$ ./a.out

Server:I am waiting-----

Server:I am waiting-----

output at server

H E L L O

Server:I am waiting-----

Server:I am waiting-----

At Client Side:

:~$ cc tcpclient1.c

Page 60: NP LAB

:~$ ./a.out 127.0.0.1 13153

enter sentence to end enter #hello#

String : hello -----> sent to server

Page 61: NP LAB

Week7:

AIM:Design a TCP concurrent server to echo given set of sentences using poll

functions.

PROGRAM:

tcpservpoll01.c:

#include <stdio.h>

#include <string.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <fcntl.h>

#include <limits.h> /* for OPEN_MAX */

#include <poll.h>

#include <errno.h>

#define MAXLINE 100

#define SERV_PORT 13154

#define POLLRDNORM 5

#define INFTIM 5

#define OPEN_MAX 5

int main(int argc, char **argv)

{

int k, i, maxi, listenfd, connfd, sockfd;

int nready;

ssize_t n;

char line[MAXLINE];

socklen_t clilen;

struct pollfd client[OPEN_MAX];

struct sockaddr_in cliaddr, servaddr;

listenfd = socket(AF_INET, SOCK_STREAM, 0);

bzero(&servaddr, sizeof(servaddr));

servaddr.sin_family = AF_INET;

servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

servaddr.sin_port = htons(SERV_PORT);

bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

listen(listenfd, 5);

client[0].fd = listenfd;

Page 62: NP LAB

client[0].events = POLLRDNORM;

for (i = 1; i < OPEN_MAX; i++)

client[i].fd = -1; /* -1 indicates available entry */

maxi = 0; /* max index into client[] array */

for ( ; ; ) {

nready = poll(client, maxi+1, INFTIM);

if (client[0].revents & POLLRDNORM) { /* new client connection */

clilen = sizeof(cliaddr);

connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);

#ifdef NOTDEF

printf("new client: %s\n", sock_ntop((struct sockaddr *) &cliaddr,

clilen));

#endif

for (i = 1; i < OPEN_MAX; i++)

if (client[i].fd < 0) {

client[i].fd = connfd; /* save descriptor */

break;

}

if (i == OPEN_MAX)

{

printf("too many clients");

exit(0);

}

client[i].events = POLLRDNORM;

if (i > maxi)

maxi = i; /* max index in client[] array */

if (--nready <= 0)

continue; /* no more readable descriptors

*/

}

for (i = 1; i <= maxi; i++) { /* check all clients for data */

if ( (sockfd = client[i].fd) < 0)

continue;

if (client[i].revents & (POLLRDNORM | POLLERR)) {

if ( (n = read(sockfd, line, MAXLINE)) < 0) {

if (errno == ECONNRESET) {

/*4connection reset by client */

#ifdef NOTDEF

printf("client[%d] aborted connection\n", i);

#endif

close(sockfd);

client[i].fd = -1;

Page 63: NP LAB

} else

printf("readline error");

} else if (n == 0) {

/*4connection closed by client */

#ifdef NOTDEF

printf("client[%d] closed connection\n", i);

#endif

close(sockfd);

client[i].fd = -1;

} else{ printf("\n data from client is \n");

k=strlen(line);

printf(" length=%d data = %s\n", k,line);

//write(sockfd, line, n);

strcpy(line," ");

}

if (--nready <= 0)

break; /* no more readable descriptors

*/

}

}

}

}

democlient.c:

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <errno.h>

#include <string.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <fcntl.h>

#define MAXBUFFER 1024

void sendstring(int , char *);

int main( int C, char *V[] )

{

int sd,fd;

char c;

Page 64: NP LAB

struct sockaddr_in serveraddress;

char text[100];

int i=0;

sd = socket( AF_INET, SOCK_STREAM, 0 );

if( sd < 0 ) {

perror( "socket" );

exit( 1 );

}

if (V[1] == NULL ) {

printf ("PL specfiy the server's IP Address \n");

exit(0);

}

if (V[2] == NULL ) {

printf ("PL specify the server's Port No \n");

exit(0);

}

memset( &serveraddress, 0, sizeof(serveraddress) );

serveraddress.sin_family = AF_INET;

serveraddress.sin_port = htons(atoi(V[2]));//PORT NO

serveraddress.sin_addr.s_addr = inet_addr(V[1]);//ADDRESS

if (connect(sd,(struct sockaddr*)&serveraddress,

sizeof(serveraddress))<0)

{

printf("Cannot Connect to server");

exit(1);

}

printf("enter sentence to end enter #");

while(1)

{

c=getchar();

if(c=='#')

break;

text[i++]=c;

}

text[i]='\0';

sendstring(sd,text);

close(sd);

return 0;

}

void sendstring(

int sd, /*Socket Descriptor*/

char *fname) /*Array Containing the string */

{ int n , byteswritten=0 , written ;

Page 65: NP LAB

char buffer[MAXBUFFER];

strcpy(buffer , fname);

n=strlen(buffer);

while (byteswritten<n)

{

written=write(sd , buffer+byteswritten,(n-byteswritten));

byteswritten+=written;

}

printf("String : %s sent to server \n",buffer);

}

Output:

At Server side:

:~$ cc tcpservpoll01.c

:~$ ./a.out

data from client is:

length=11 , data = welcome

data from client is:

length=11 , data = lbrce

At Client Side:

:~$ cc democlient.c

:~$ ./a.out 127.0.0.1 13154

enter sentence to end enter #welcome#

String : welcome----> sent to server

:~$ cc democlient.c

:~$ ./a.out 127.0.0.1 13154

enter sentence to end enter #lbrce#

String : lbrce----> sent to server

Page 66: NP LAB

Week8:

AIM:Design UDP Client and server application to reverse the given input sentence

PROGRAM:

udp-string-rev-ser.c:

#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,len,i;

int addr_len, bytes_read;

char recv_data[1024],buf[1024];

struct sockaddr_in server_addr , client_addr;

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

perror("Socket");

exit(1);

}

server_addr.sin_family = AF_INET;

server_addr.sin_port = htons(1223);

server_addr.sin_addr.s_addr = INADDR_ANY;

bzero(&(server_addr.sin_zero),8);

if (bind(sock,(struct sockaddr *)&server_addr,

sizeof(struct sockaddr)) == -1)

{

perror("Bind");

exit(1);

}

Page 67: NP LAB

addr_len = sizeof(struct sockaddr);

printf("\nUDPServer Waiting for client on port 1223");

fflush(stdout);

while (1)

{

bytes_read = recvfrom(sock,recv_data,1024,0,

(struct sockaddr *)&client_addr, &addr_len);

recv_data[bytes_read] = '\0';

printf("\n(%s , %d) Data : ",inet_ntoa(client_addr.sin_addr),

ntohs(client_addr.sin_port));

printf("%s", recv_data);

fflush(stdout);

strcpy(buf,recv_data);

len=strlen(recv_data);

for(i=0;i<len;i++)

recv_data[i]=buf[(len)-(i+1)];

recv_data[len]='\0';

sendto(sock,recv_data,strlen(recv_data),0,(struct sockaddr

*)&client_addr,sizeof(struct sockaddr));

}

return 0;

}

udp-string-rev-cli.c:

#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>

Page 68: NP LAB

#include <stdlib.h>

int main()

{

int sock;

int addr_len,bytes_read;

struct sockaddr_in server_addr;

struct hostent *host;

char send_data[1024],recv_data[1024];

host= (struct hostent *) gethostbyname((char *)"127.0.0.1");

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

{

perror("socket");

exit(1);

}

server_addr.sin_family = AF_INET;

server_addr.sin_port = htons(1223);

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

bzero(&(server_addr.sin_zero),8);

while (1)

{

printf("\nType Something (q or Q to quit):");

gets(send_data);

if ((strcmp(send_data , "q") == 0) || strcmp(send_data , "Q") == 0)

break;

else

sendto(sock, send_data, strlen(send_data), 0,

(struct sockaddr *)&server_addr, sizeof(struct sockaddr));

bytes_read = recvfrom(sock,recv_data,1024,0,

(struct sockaddr *)&server_addr, &addr_len);

recv_data[bytes_read] = '\0';

printf("\necho> %s",recv_data);

fflush(stdout);

Page 69: NP LAB

}

}

Output:

At Server Side:

:~$ cc udp-string-rev-ser.c

:~$ ./a.out

UDPServer Waiting for client on port 1223

(127.0.0.1 , 36636) said : phani

(127.0.0.1 , 36636) said : sandeep

(127.0.0.1 , 49097) said : vamsi

(127.0.0.1 , 49097) said : santosh

At Client Side:

:~$ cc udp-string-rev-cli.c

:~$ ./a.out

Type Something (q or Q to quit):phani

echo> inahp

Type Something (q or Q to quit):sandeep

echo> peednas

Type Something (q or Q to quit):vamsi

echo> ismav

Type Something (q or Q to quit):santosh

echo> hsotnas

Page 70: NP LAB