100% found this document useful (1 vote)
125 views

NP Lab

Prepared by Padma Lochan Pradhan, [email protected] Dept of Computer Science & Engineering Central Institute of Technology, New Raipur, CG, India Branch: Computer Science & Engineering Semester: V Subject: UNIX

Uploaded by

Padma Pradhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
125 views

NP Lab

Prepared by Padma Lochan Pradhan, [email protected] Dept of Computer Science & Engineering Central Institute of Technology, New Raipur, CG, India Branch: Computer Science & Engineering Semester: V Subject: UNIX

Uploaded by

Padma Pradhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Network Programming Lab

Prepared by
Padma Lochan Pradhan, [email protected]
Dept of Computer Science & Engineering
Central Institute of Technology, New Raipur, CG, India

Semester: VII Branch: Computer Science & Engg.


Subject: Network Programming Lab
Code: 322762(22)
Total practical Periods: 42
Total Marks in End Semester Exam: 40

No 1. Write an echo program with client and iterative server using


TCP.
/*
TCP iterative SERVER program
The following program shows the contents of Filename : TCP_it_ser.c.
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#define MYPORT 13153 /*The port users will be connecting to*/
void readstring(int,char *);
int main(int C, char *V[] )
{
int listensocket,connectionsocket,retbind;
struct sockaddr_in
serveraddress,cliaddr;
socklen_t len;
char buf[100],databuf[1024];
listensocket = socket(AF_INET, SOCK_STREAM, 0 );
if (listensocket < 0 )
{
perror("socket" );
exit(1);
}
memset(&serveraddress, 0, sizeof(serveraddress) );
serveraddress.sin_family = AF_INET;
serveraddress.sin_port = htons(MYPORT);/*PORT NO*/
serveraddress.sin_addr.s_addr =
htonl(INADDR_ANY);/*ADDRESS*/
retbind=bind(listensocket,(struct sockaddr*)&serveraddress,
sizeof(serveraddress));
/*Check the return value of bind for error*/
if(-1==retbind)
{

perror("BIND ERROR\n");
exit(1);
}
listen(listensocket,5);
/*Beginning of the Main Server Processing Loop*/
for (;;)
{
printf("Server:I am waiting-----Start of Main Loop\n");
len=sizeof(cliaddr);
connectionsocket=accept(listensocket,
(struct sockaddr*)&cliaddr,&len);
if (connectionsocket < 0)
{
if (errno == EINTR)
printf("Interrupted system call ??");
continue;
}
printf("Connection from %s\n",
inet_ntop(AF_INET,&cliaddr.sin_addr,buf,sizeof(buf)));
readstring(connectionsocket , databuf);
close(connectionsocket);
printf("Finished Serving One Client\n");
}
}

No. 2 Code for TCP/IP program of concurrent TCP server for ECHO
service and echo one buffer of data, returning byte count in Networking
#include
#include
#include
#include

<sys/types.h>
<sys/socket.h>
<sys/time.h>
<netinet/in.h>

#include <unistd.h>
#include <string.h>
#include <stdio.h>
#define
BUFSIZE

QLEN

/* maximum connection queue length

externint
int
int
int

errno;
errexit(constchar *format, ...);
passiveTCP(constchar *service, int qlen);
echo(int fd);

*/#define

4096

/*------------------------------------------------------------------------ * main Concurrent TCP server for ECHO service *----------------------------------------------------------------------- */int
main(int argc, char *argv[])
{
char
*service = "echo";
/* service name or port number
*/struct
sockaddr_in fsin;
/* the from address of a client
*/int
msock;
/* master server socket
*/
fd_set
rfds;
/* read file descriptor set
*/

fd_set
afds;
/* from-address length

/* active file descriptor set


*/int
fd, nfds;

*/int

alen;

switch (argc) {
case
1:
break;
case
2:
service = argv[1];
break;
default:
errexit("usage: TCPmechod [port]\n");
}
msock = passiveTCP(service, QLEN);
nfds = getdtablesize();
FD_ZERO(&afds);
FD_SET(msock, &afds);
while (1) {
memcpy(&rfds, &afds, sizeof(rfds));
if (select(nfds, &rfds, (fd_set *)0, (fd_set *)0,
(struct timeval *)0) < 0)
errexit("select: %s\n", strerror(errno));
if (FD_ISSET(msock, &rfds)) {
int
ssock;
alen = sizeof(fsin);
ssock = accept(msock, (struct sockaddr *)&fsin,
&alen);
if (ssock < 0)
errexit("accept: %s\n",
strerror(errno));
FD_SET(ssock, &afds);
}
for (fd=0; fd<nfds; ++fd)
if (fd != msock && FD_ISSET(fd, &rfds))
if (echo(fd) == 0) {
(void) close(fd);
FD_CLR(fd, &afds);
}
}
}
/*------------------------------------------------------------------------ * echo echo one buffer of data, returning byte count *----------------------------------------------------------------------- */int
echo(int fd)
{
char
buf[BUFSIZ];
int
cc;
cc = read(fd, buf, sizeof buf);
if (cc < 0)
errexit("echo read: %s\n", strerror(errno));
if (cc && write(fd, buf, cc) < 0)
errexit("echo write: %s\n", strerror(errno));
return cc;
}

No 3. Code for Corba program to Write a Echo server and client with
UDP server and client in Java
// Server
import java.io.*;
import java.net.*;
publicclass EServer
{
publicstaticvoid main(String[] args) throws IOException
{
ServerSocket S = new ServerSocket(3000);
while(true)
{
Socket Client = S.accept();
InputStream in = Client.getInputStream();
DataInputStream Dis = new DataInputStream(in);
System.out.println(Dis.readUTF());
Client = new Socket("localhost",4000);
BufferedReader buff = new BufferedReader(new InputStreamReader (System.in));
String Str = buff.readLine();
OutputStream out = Client.getOutputStream();
DataOutputStream Dos = new DataOutputStream(out);
Str = "Server Says :: " + Str;
Dos.writeUTF(Str);
Client.close();
}
}
}
// Client
import java.io.*;
import java.net.*;
import java.util.*;
publicclass EClient
{
publicstaticvoid main(String[] args) throws IOException
{
Socket C = new Socket("localhost",3000);
BufferedReader buff = new BufferedReader(new InputStreamReader (System.in));
String Str = buff.readLine();
OutputStream out = C.getOutputStream();
DataOutputStream Dos = new DataOutputStream(out);

Dos.writeUTF("Client Say :: " + Str);


Dos.flush();
ServerSocket S = new ServerSocket(4000);
Socket Client = S.accept();
InputStream in = Client.getInputStream();
DataInputStream Dis = new DataInputStream(in);
System.out.println(Dis.readUTF());
Client.close();
}
}

No. 4 Write a client and server program for chatting.


ServerSocket server = new ServerSocket(PORT); //SET PORT NUMBER
System.out.println("Waiting for clients...");//AT
THE START PRINT THIS
while (true)//WHILE THE PROGRAM IS RUNNING
{
Socket s = server.accept();//ACCEPT
SOCKETS(CLIENTS) TRYING TO CONNECT
System.out.println("Client connected from "
+ s.getLocalAddress().getHostName()); //
TELL THEM THAT THE CLIENT
CONNECTED
Client chat = new Client(s);//CREATE A NEW
CLIENT OBJECT
Thread t = new Thread(chat);//MAKE A NEW
THREAD
t.start();//START THE THREAD
}
}
catch (Exception e)
{
System.out.println("An error occured.");//IF AN
ERROR OCCURED THEN PRINT IT
e.printStackTrace();
}
}
}

Client:

import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client implements Runnable{


private Socket socket;//SOCKET INSTANCE VARIABLE
public Client(Socket s)
{
socket = s;//INSTANTIATE THE SOCKET
}
@Override
public void run() //(IMPLEMENTED FROM THE RUNNABLE INTERFACE)
{
try //HAVE TO HAVE THIS FOR THE in AND out VARIABLES
{
Scanner in = new
Scanner(socket.getInputStream());//GET THE SOCKETS INPUT STREAM (THE STREAM
THAT YOU WILL GET WHAT THEY TYPE FROM)
PrintWriter out = new
PrintWriter(socket.getOutputStream());//GET THE SOCKETS OUTPUT STREAM (THE
STREAM YOU WILL SEND INFORMATION TO THEM FROM)
while (true)//WHILE THE PROGRAM IS RUNNING
{
if (in.hasNext())
{
String input = in.nextLine();//IF
THERE IS INPUT THEN MAKE A NEW VARIABLE input AND READ WHAT THEY TYPED
System.out.println("Client Said: " +
input);//PRINT IT OUT TO THE SCREEN
out.println("You Said: " +
input);//RESEND IT TO THE CLIENT
out.flush();//FLUSH THE STREAM
}
}
}
catch (Exception e)
{
e.printStackTrace();//MOST LIKELY THERE WONT BE AN
ERROR BUT ITS GOOD TO CATCH
}
}
}
The first part is our constructor and our instance variable: socket:

private Socket socket;


public Client(Socket s)
{
socket = s;
}

{
if (in.hasNext())
{
String input = in.nextLine();

System.out.println("Client Said: " + input);


out.println("You Said: " + input);
out.flush();
}
}

5. Write a program to retrieve date and time using TCP.


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.

SERVER:
#include"netinet/in.h"
#include"sys/socket.h"#include"stdio.h"
#include"string.h"
#include"time.h"
main( )
{
struct sockaddr_in sa;
struct sockaddr_in cli;int sockfd,conntfd;int len,ch;char str[100];
time_t tick;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
{
printf("error in socket\n");
exit(0);
}
else printf("Socket opened");
bzero(&sa,sizeof(sa));
sa.sin_port=htons(5600);
sa.sin_addr.s_addr=htonl(0);
if(bind(sockfd,(struct sockaddr*)&sa,sizeof(sa))<0)
{
printf("Error in binding\n");
}
else
printf("Binded Successfully");
listen(sockfd,50);
for(;;)
{
len=sizeof(ch);
conntfd=accept(sockfd,(struct sockaddr*)&cli,&len);
printf("Accepted");
tick=time(NULL);
snprintf(str,sizeof(str),"%s",ctime(&tick));
printf("%s",str);write(conntfd,str,100);
}
}

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.

CLIENT:
#include"netinet/in.h"
#include"sys/socket.h"
#include"stdio.h"
main()
{
struct sockaddr_in sa,cli;
int n,sockfd;
int len;char buff[100];
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0){ printf("\nError in Socket");
exit(0);
}
else printf("\nSocket is Opened");
bzero(&sa,sizeof(sa));
sa.sin_family=AF_INET;
sa.sin_port=htons(5600);
if(connect(sockfd,(struct sockaddr*)&sa,sizeof(sa))<0)
{
printf("\nError in connection failed");
exit(0);
}
else
printf("\nconnected successfully");
if(n=read(sockfd,buff,sizeof(buff))<0)
{
printf("\nError in Reading");
exit(0);
}
else
{printf("\nMessage Read %s",buff);
}}

No. 6 Code for TCP/IP program of UDP client for TIME service
that prints the resulting time in Networking
34. #include <sys/types.h>
35. #include <unistd.h>
36. #include <stdlib.h>
37. #include <string.h>
38. #include <stdio.h>
39.
40. #define
BUFSIZE 64
41.
42. #define
UNIXEPOCH
2208988800
/* UNIX epoch, in UCT secs
*/#define
MSG
"what time is it?\n"externint
errno;
43.
44. int
connectUDP(constchar *host, constchar *service);
45. int
errexit(constchar *format, ...);

46.
47. /*------------------------------------------------------------------------ *
main - UDP client for TIME service that prints the resulting time *----------------------------------------------------------------------- */int
48. main(int argc, char *argv[])
49. {
50.
char
*host = "localhost";
/* host to use if none supplied
*/char
*service = "time";
/* default service name
*/
51.
time_t
now;
/* 32-bit integer to hold time
*/int
s,
n;
/* socket descriptor, read count*/switch (argc) {
52.
case 1:
53.
host = "localhost";
54.
break;
55.
case 3:
56.
service = argv[2];
57.
/* FALL THROUGH */case 2:
58.
host = argv[1];
59.
break;
60.
default:
61.
fprintf(stderr, "usage: UDPtime [host [port]]\n");
62.
exit(1);
63.
}
64.
65.
s = connectUDP(host, service);
66.
67.
(void) write(s, MSG, strlen(MSG));
68.
69.
/* Read the time */
70.
71.
n = read(s, (char *)&now, sizeof(now));
72.
if (n < 0)
73.
errexit("read failed: %s\n", strerror(errno));
74.
now = ntohl((u_long)now);
/* put in host byte order
*/
75.
now -= UNIXEPOCH;
/* convert UCT to UNIX epoch
*/
76.
printf("%s", ctime(&now));
77.
exit(0);
78. }

7. Write a client and server routines showing Blocking I/O.


//create initial I/O completion port with the number of
worker threads
hCompletionPort =
CreateIoCompletionPort(INVALID_FILE_HANDLE,
NULL, 0,
nWorkerThreads);
if( hCompletionPort == NULL){
return GetLastError();
}
//Add a file handle for the I/O completion to watch

hCompletionPort1 = CreateIoCompletionPort( hFile,


hCompletionPort,
dwCompletionKey, nWorkerThreads);
if( hCompletionPort1 == NULL ){
return GetLastError();
}
//perform Non-Blocking read so GetQueuedCompletionStatus
can notify
//
us when
the read has completed.
nRet = WSARecv(hFile, lpBuffers, dwBuffCount,
&dwBytesReceived,
&dwFlags,
&OverLapped, NULL);
if( nRet != 0 ){
return WSAGetLastError();
}
//block on GetQueuedCompletionStatus until the I/O
operation completes.
// The I/O will be in the buffer specified supplied in
WSARecv
nRet = GetQueuedCompletionStatus(hCompletionPort,
&dwBytesReceived,
&dwCompletionKey,
&OverLapped, TIME_OUT);
if( nRet == 0 && GetLastError() != WAIT_TIMEOUT){
return GetLastError();
}

No 8 Write a client and server routines showing I/O multiplexing.


// Get Handle to the /dev/poll device
if ((fd = open("/dev/poll", O_RDWR)) < 0) {
return EPERM;
}
//create a pollfd structure large enough to hold all file
//
descriptors that will be watched
pollfd = (struct pollfd* )malloc(sizeof(struct pollfd) * MAXBUF);
if (pollfd == NULL) {
close(fd);
return ENOMEM;
}
// Setup dev poll to watch for I/O events from file descriptors
for (i = 0; i < nFileDescriptorCount; i++) {

pollfd[i].fd = fds[i];
pollfd[i].events = POLLIN;
pollfd[i].revents = 0;
}
if (write(fd, &pollfd[0], sizeof(struct pollfd) * MAXBUF) !=
sizeof(struct pollfd) * MAXBUF) {
perror("failed to write register file descriptor with /dev/poll");
close (fd);
free(pollfd);
return EBADF;
}
// Get I/O and events from the
dopoll.dp_timeout = -1;
dopoll.dp_nfds = MAXBUF;
dopoll.dp_fds = pollfd;
nDescriptorsSignalled = ioctl(wfd, DP_POLL, &dopoll);
if (nDescriptorsSignalled < 0) {
perror("/dev/poll ioctl DP_POLL failed");
close (fd);
free(pollfd);
return EINVAL;
}
while( nDescriptorsSignalled-- ) {
read(dopoll.dp_fds[i].fd, rbuf, STRLEN);
}

No 9 Write an echo client and server program using Unix domain stream
socket.
Sample UNIX server
#include
#include
#include
#include

<sys/types.h>
<sys/socket.h>
<sys/un.h>
<stdio.h>

#define NAME "socket"

main()
{
int sock, msgsock, rval;
struct sockaddr_un server;
char buf[1024];
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock < 0) {
perror("opening stream socket");
exit(1);
}
server.sun_family = AF_UNIX;
strcpy(server.sun_path, NAME);
if (bind(sock, (struct sockaddr *) &server, sizeof(struct
sockaddr_un))) {
perror("binding stream socket");
exit(1);
}
printf("Socket has name %s\n", server.sun_path);
listen(sock, 5);
for (;;) {
msgsock = accept(sock, 0, 0);
if (msgsock == -1)
perror("accept");
else do {
bzero(buf, sizeof(buf));
if ((rval = read(msgsock, buf, 1024)) < 0)
perror("reading stream message");
else if (rval == 0)

printf("Ending connection\n");
else
printf("-->%s\n", buf);
} while (rval > 0);
close(msgsock);
}
close(sock);
unlink(NAME);
}

No 10. Write an echo client and server program using Unix domain
Datagram socket.
int s = socket(AF_UNIX, SOCK_DGRAM, 0);
struct sockaddr_un sa;
sa.sun_family = AF_UNIX;
strcpy(sa.sun_path, "/tmp/test.socket");

const char *data = "Testing data";


int err = sendto(s, data, strlen(data), 0, (struct sockaddr *)(&sa), sizeof(struct
sockaddr_un));

printf("Sent!\n");

unsigned char *buffer = malloc(BUFFER_LENGTH);


struct sockaddr_storage recv_sa;
int recv_sa_len = 0;
int recv_len = recvfrom(s, buffer, BUFFER_LENGTH, 0, (struct sockaddr *)&recv_sa,
&recv_sa_len);

for (int i = 0; i < recv_len; i++) {


putc(buffer[i], stdout);

printf("\n");

No 11. Write a client and server program to implement file transfer.


FileInputStream fileinputstream = new FileInputStream(samplefile);
// now ready to send data from server .....
int notendcharacter;
do {
notendcharacter = fileinputstream.read();
stringdata = String.valueOf(notendcharacter);
toclient.println(stringdata);

if (notendcharacter != -1) {
file_still_present = true;
} else {
file_still_present = false;
}
} while(file_still_present);

fileinputstream.close();
System.out.println("File has been send successfully .. message
print from server");

if (str.equals("bye")) {
break;
}

fromclient.close();
toclient.close();

clientsocket.close();
}
} catch(Exception ex) {
System.out.println("Error in the code : " + ex.toString());
}
}

public static void main(String arg[]) {


MyServer serverobj = new MyServer();
}

No 12 Write a client and server program to implement the remote


command execution
* Implementation of Remote Command Execution using TCP */
// RemoteServer.java : A Simple Remote Server Program
import java.io.*;
import java.net.*;
class RemoteServer
{
public static void main(String args[])
{
try
{
int Port;
BufferedReader Buf =new BufferedReader(new
InputStreamReader(System.in));
System.out.print(" Enter the Port Address : " );
Port=Integer.parseInt(Buf.readLine());
ServerSocket ss=new ServerSocket(Port);
System.out.println(" Server is Ready To Receive a Command. ");
System.out.println(" Waiting ..... ");
Socket s=ss.accept();
if(s.isConnected()==true)
System.out.println(" Client Socket is Connected Succecfully. ");
InputStream in=s.getInputStream();
OutputStream ou=s.getOutputStream();
BufferedReader buf=new BufferedReader(new
InputStreamReader(in));

String cmd=buf.readLine();
PrintWriter pr=new PrintWriter(ou);
pr.println(cmd);
Runtime H=Runtime.getRuntime();
Process P=H.exec(cmd);
System.out.println(" The " + cmd + " Command is Executed Successfully. ");
pr.flush();
pr.close();
ou.close();
in.close();
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
}
}

No 13 Write a client program that gets a number from the user and
sends the number to server for conversion into hexadecimal and
gets the result from the server.
PrintWriter pw1 = new PrintWriter(new FileWriter("data01.png"));
{
String hello = (new String(byteBuffer)).toString();
int cal = recvMsgSize/2; //Calculate the Receiving Message Size
String result=""; // Declare of the text send by client
int first = 0;
int second = 2;
for (int c=0;c<cal;c++)//Create a loop
{
String hex = hello.substring(first, second);
int intVal = Integer.parseInt(hex, 16);
char charVal = (char) intVal;
result += charVal;
first+=2;
second+=2;
}
System.out.println("Client Send: "+result);
pw1.print(result+"\n");//Print to data02.png
pw1.close();
}

You might also like