NP Lab
NP Lab
Prepared by
Padma Lochan Pradhan, [email protected]
Dept of Computer Science & Engineering
Central Institute of Technology, New Raipur, CG, India
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
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
*/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);
Client:
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
{
if (in.hasNext())
{
String input = in.nextLine();
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. }
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>
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");
printf("Sent!\n");
printf("\n");
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());
}
}
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();
}