Network Programming Lab Practicals Complete File

  1. Write an echo program with client and iterative server using TCP.
Implementing the solution
1) Write a server (TCP) C Program that opens a listening socket and waits to serve client
2) Write a client (TCP) C Program that connects with the server program knowing IP
address and port number.
3) Get the input string from console on client and send it to server, server echoes back
that string to client.
3.3.1 Writing the source code
Client.c
Server.c
3.3.2 Compilation and Running the Solution
1) Compilation
Compile client and server programs using gcc.
gcc server.c –o server
gcc client.c –o client
2) Executing the solution
Execute server program : ./server
Execute client program by passing arguments : ServerIP, EchoString, PortNo.
./client 192.168.31.10 Hello 8089
  1. Write an echo program with client and concurrent server using TCP.
Server:
Client:

 

  1. Write an echo program with client and concurrent server using UDP.
AIM:
Program that illustrates UDP client server communication in detail
PROGRAM:
UDP ECHO SERVER:main() function:
#include “unp.h”
main(int argc,char **argv)
{
int sockfd;
pid_t childfd;
socklen_t clilen;
struct sock_addr_in cliaddr,servaddr;
sockfd=Socket(AF_INET,SOCK_DGRAM,0);
bzero(&servadr;,sizeof(servaddr);
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr,sin_port=htons(SERV_PORT);
bind(listenfd,(SA *) &servaddr;, sizeof(servaddr));
dg_echo(sockfd,(SA *) &cliaddre;,sizeof(cliaddr));
}
UDP ECHO SERVER:dg_echo function:
#include “unp.h”
void dg(int sockfd, SA *pcliaddr, sockeln_t clilen)
{
int n;
socklen_t len;
char mesg[MAXLINE];
for( ; ; )
{
len=clilen;
n=recvfrom(sockfd,mesg,MAXLINE,0,pcliaddr,&len;);
sendto(sockfd,mesg,n,0,pcliaddr,len);
}
}
UDP ECHO CLIENT:main() function:
#include “unp.h”
int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr;
if(argc!=2)
err_quit(“usauge:UDPcli”);
bzero(servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htons(SERV_PORT);
inet_pton(AF_INET,argv[1],&servaddr.sin;_addr);
sockfd=socket(AF_INET,SOCK_DGRAM,0);
dg_cli(stdin,sockfd,(SA *) &servaddr;,sizeof(servaddr));
exit(0);
}
UDP ECHO CLIENT:dg_cli function:
#include “unp.h”
void dg_cli(FILE *fp,int sockfd,const SA *pervaddr,socklen_t servlen)
{
Int n;
char sendline[MAXLINE],recvline[MAXLINE];
while(fgets(sendline,MAXLINE,fp)! = NULL)
{
sendto(sockfd,sendline,strlen(sendline),0,servaddr,servlen);
n=recvfrom(sockfd,recvline,MAXLINE,0,NULL,NULL);
recvline[n]=0;
fputs(recvline,stdout);
}
}
  1. Write a client and server program for chatting.
Client:
#include
#include
#include
#include types.h><span>
#include
#include in.h><span>
#include socket.h><span>
#include inet.h><span>
#define BUF_SIZE 500
#define PORT 3457
int main(void) {
int s;
int rtn;
char buff[BUF_SIZE];
struct sockaddr_in addr;
puts(“Entering program”);
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == -1) {
perror(“Failed to get socket”);
exit(EXIT_FAILURE);
}
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(PORT);
rtn = connect(s, (struct sockaddr * )&addr;, sizeof(addr) );
if (rtn == -1) {
perror(“Failed to connect to server”);
exit(EXIT_FAILURE);
}
for(;;) {
ssize_t len;
printf(“speak “);
fflush(stdout);
/*gets(buff);*/ /* gets is BAD!!! */
if (fgets(buff, BUF_SIZE, stdin) == NULL) {
fprintf(stderr, “Failed to read inputn”);
exit(EXIT_FAILURE);
}
len = write(s, buff, strlen(buff));
if (len == -1) {
perror(“Failed to writen”);
exit(EXIT_FAILURE);
}
len = read(s, buff, BUF_SIZE);
/* read returns -1 on error. Don’t want to index an array with -1! */
if (len < 0) {
fprintf(stderr, “Failed to read network datan”);
}
else if (len == 0) {
fprintf(stderr, “No response data readn”);
}
else {
buff[len] = ”;
printf(“server says : %sn”, buff);
}
}
return 0;
}
Server:
#include
#include
#include
#include types.h><span>
#include
#include in.h><span>
#include socket.h><span>
#include inet.h><span>
#define BUF_SIZE 500
#define PORT 3457
int main(int argc,char * argv[]) {
int s;
int rtn;
char buff[BUF_SIZE];
struct sockaddr_in addr;
int incoming_s;
socklen_t incoming_len;
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == -1) {
perror(“Failed to get socket”);
exit(EXIT_FAILURE);
}
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(PORT);
rtn = bind(s, (struct sockaddr*)&addr;, sizeof(addr));
if (rtn == -1) {
perror(“Failed to get socket”);
exit(EXIT_FAILURE);
}
rtn = listen(s, 10);
if (rtn == -1) {
perror(“Failed to listen on socket”);
exit(EXIT_FAILURE);
}
incoming_len = sizeof(addr);
memset(&addr;, 0, sizeof(addr));
incoming_s = accept(s, (struct sockaddr *)&addr;, &incoming;_len);
if (incoming_s == -1) {
perror(“Failed to accept incoming connection”);
exit(EXIT_FAILURE);
}
printf(“Accepted incoming connectionn”);
for (;;) {
ssize_t len = read(incoming_s, buff, BUF_SIZE);
/* read returns -1 on error. Don’t want to index an array with -1! */
if (len < 0) {
fprintf(stderr, “Failed to read network datan”);
}
else if (len == 0) {
fprintf(stderr, “No response data readn”);
}
else {
buff[len] = ”;
printf(“client says : %s”, buff);
printf(“speak “);
}
/*gets(buff);*/ /* gets is BAD!!! */
if (fgets(buff, BUF_SIZE, stdin) == NULL) {
fprintf(stderr, “Failed to read inputn”);
exit(EXIT_FAILURE);
}
len = write(incoming_s, buff, strlen(buff));
if (len == -1) {
perror(“Failed to writen”);
exit(EXIT_FAILURE);
}
}
return 0;
}
  1. Write a program to retrieve date and time using TCP.
   AIM:
            To obtain the system date and time of server using TCP.
  
   ALGORITHM:
   CLIENT:
           1. Start and  import all  the necessary packages.
           2. Create a client side socket with server address.
           3. Send date or time request to server.
           4. Get response from socket and point the result.
           5. Close the socket and stop.
   SERVER:    
           1.  Start and import all  the necessary packages.
           2. Create server socket and accept client.
           3. Give response using Gregorian calendar.
           4. Close the socket and stop.
          PROGRAM:
          CLIENT:
                   import java.io.*;
                   import java.net.*;
                   public class dtclient
                  
                       public static void main(String args[])throws IOException
                      
                           String rec;
                           String res;
                           try
                          
                               Socket s=new Socket(“127.0.0.1”,8081);
                               BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                               BufferedReader brl=new BufferedReader(new InputStreamReader(s.getInputStream()));
                               PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
                               do
                              
                                   rec=br.readLine();
                                   pw.println(rec);
                                   res=brl.readLine();
                                   System.out.println(res);
                               }  
                               while(!rec.equalsIgnoreCase(“End”));
                           
                           catch(Exception e)
                          
                              System.out.println(“Error”+e);
                           }
                       }   
                  
          SERVER:
                 import java.io.*;
                 import java.net.*;
                 import java.util.*;
                 public class dtserver
                
                     public static void main(String args[])throws IOException
                    
                         try
                        
                             String com;
                             ServerSocket ss=new ServerSocket(8081);
                             Socket s=ss.accept();
                             System.out.println(“Connected”);
                             BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
                             PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
                             do
                            
                                 com=br.readLine();
                                 System.out.println(com);
                                 if(com.equalsIgnoreCase(“Date”))
                                
                                     GregorianCalendar c=new GregorianCalendar();
                                     pw.println(c.get(Calendar.DATE)+”/”+(c.get(Calendar.MONTH)+”/”+(c.get(Calendar.YEAR))));
                                 }
                                 else if(com.equalsIgnoreCase(“Time”))
                                
                                     GregorianCalendar t=new GregorianCalendar();
                                     t.setTime(new Date());
                                     pw.println(t.get(Calendar.HOUR)+”/”+(t.get(Calendar.MINUTE)+”/”+(t.get(Calendar.SECOND))));
                                 }
                                 else
                                
                                     pw.println(“Wrong”);
                                 }
                             }  
                             while(!com.equalsIgnoreCase(“End”));
                        
                         catch(Exception e)
                         {
                         }
                     }
                
          
           OUTPUT:
                       C:jdk1.3bin>javac dtclient.java
                       C:jdk1.3bin>javac dtserver.java
                       C:jdk1.3bin>java dtserver
                      
                       2nd
                       C:jdk1.3bin>java dtclient
                       date
                       16/8/2006
                       time
                       11/43/57
                       end
                       Wrong
                       C:jdk1.3bin>
                       1st
                       C:jdk1.3bin>java dtserver
                       Connected
                       date
                       time
                       end
                       C:jdk1.3bin>
  1. Write a program to retrieve date and time using UDP.
Client:
#include
#include
#include
#include
#include
#define SIZE 500
void usage(void);
int main(int argc, char **argv)
{
WSADATA w; /* Used to open Windows connection */
unsigned short port_number; /* The port number to use */
SOCKET sd; /* The socket descriptor */
int server_length; /* Length of server struct */
char send_buffer[SIZE] = “GET TIMErn”;/* Data to send */
time_t current_time; /* Time received */
struct hostent *hp; /* Information about the server */
struct sockaddr_in server; /* Information about the server */
struct sockaddr_in client; /* Information about the client */
int a1, a2, a3, a4; /* Server address components in xxx.xxx.xxx.xxx form */
int b1, b2, b3, b4; /* Client address components in xxx.xxx.xxx.xxx form */
char host_name[256]; /* Host name of this computer */
/* Make sure command line is correct */
if (argc != 3 && argc != 4)
{
usage();
}
if (sscanf(argv[1], “%d.%d.%d.%d”, &a1;, &a2;, &a3;, &a4;) != 4)
{
usage();
}
if (sscanf(argv[2], “%u”, &port;_number) != 1)
{
usage();
}
if (argc == 4)
{
if (sscanf(argv[3], “%d.%d.%d.%d”, &b1;, &b2;, &b3;, &b4;) != 4)
{
usage();
}
}
/* Open windows connection */
if (WSAStartup(0x0101, &w;) != 0)
{
fprintf(stderr, “Could not open Windows connection.n”);
exit(0);
}
/* Open a datagram socket */
sd = socket(AF_INET, SOCK_DGRAM, 0);
if (sd == INVALID_SOCKET)
{
fprintf(stderr, “Could not create socket.n”);
WSACleanup();
exit(0);
}
/* Clear out server struct */
memset((void *)&server;, ”, sizeof(struct sockaddr_in));
/* Set family and port */
server.sin_family = AF_INET;
server.sin_port = htons(port_number);
/* Set server address */
server.sin_addr.S_un.S_un_b.s_b1 = (unsigned char)a1;
server.sin_addr.S_un.S_un_b.s_b2 = (unsigned char)a2;
server.sin_addr.S_un.S_un_b.s_b3 = (unsigned char)a3;
server.sin_addr.S_un.S_un_b.s_b4 = (unsigned char)a4;
/* Clear out client struct */
memset((void *)&client;, ”, sizeof(struct sockaddr_in));
/* Set family and port */
client.sin_family = AF_INET;
client.sin_port = htons(0);
if (argc == 3)
{
/* Get host name of this computer */
gethostname(host_name, sizeof(host_name));
hp = gethostbyname(host_name);
/* Check for NULL pointer */
if (hp == NULL)
{
fprintf(stderr, “Could not get host name.n”);
closesocket(sd);
WSACleanup();
exit(0);
}
/* Assign the address */
client.sin_addr.S_un.S_un_b.s_b1 = hp->h_addr_list[0][0];
client.sin_addr.S_un.S_un_b.s_b2 = hp->h_addr_list[0][1];
client.sin_addr.S_un.S_un_b.s_b3 = hp->h_addr_list[0][2];
client.sin_addr.S_un.S_un_b.s_b4 = hp->h_addr_list[0][3];
}
else
{
client.sin_addr.S_un.S_un_b.s_b1 = (unsigned char)b1;
client.sin_addr.S_un.S_un_b.s_b2 = (unsigned char)b2;
client.sin_addr.S_un.S_un_b.s_b3 = (unsigned char)b3;
client.sin_addr.S_un.S_un_b.s_b4 = (unsigned char)b4;
}
/* Bind local address to socket */
if (bind(sd, (struct sockaddr *)&client;, sizeof(struct sockaddr_in)) == -1)
{
fprintf(stderr, “Cannot bind address to socket.n”);
closesocket(sd);
WSACleanup();
exit(0);
}
/* Tranmsit data to get time */
server_length = sizeof(struct sockaddr_in);
if (sendto(sd, send_buffer, (int)strlen(send_buffer) + 1, 0, (struct sockaddr *)&server;, server_length) == -1)
{
fprintf(stderr, “Error transmitting data.n”);
closesocket(sd);
WSACleanup();
exit(0);
}
/* Receive time */
if (recvfrom(sd, (char *)¤t;_time, (int)sizeof(current_time), 0, (struct sockaddr *)&server;, &server;_length) < 0)
{
fprintf(stderr, “Error receiving data.n”);
closesocket(sd);
WSACleanup();
exit(0);
}
/* Display time */
printf(“Current time: %s”, ctime(¤t;_time));
closesocket(sd);
WSACleanup();
return 0;
}
void usage(void)
{
fprintf(stderr, “Usage: timecli server_address port [client_address]n”);
exit(0);
}
Server:
#include
#include
#include
#include
#include
#define BUFFER_SIZE 4096
void usage(void);
int main(int argc, char **argv)
{
WSADATA w; /* Used to open windows connection */
unsigned short port_number; /* Port number to use */
int a1, a2, a3, a4; /* Components of address in xxx.xxx.xxx.xxx form */
int client_length; /* Length of client struct */
int bytes_received; /* Bytes received from client */
SOCKET sd; /* Socket descriptor of server */
struct sockaddr_in server; /* Information about the server */
struct sockaddr_in client; /* Information about the client */
char buffer[BUFFER_SIZE]; /* Where to store received data */
struct hostent *hp; /* Information about this computer */
char host_name[256]; /* Name of the server */
time_t current_time; /* Current time */
/* Interpret command line */
if (argc == 2)
{
/* Use local address */
if (sscanf(argv[1], “%u”, &port;_number) != 1)
{
usage();
}
}
else if (argc == 3)
{
/* Copy address */
if (sscanf(argv[1], “%d.%d.%d.%d”, &a1;, &a2;, &a3;, &a4;) != 4)
{
usage();
}
if (sscanf(argv[2], “%u”, &port;_number) != 1)
{
usage();
}
}
else
{
usage();
}
/* Open windows connection */
if (WSAStartup(0x0101, &w;) != 0)
{
fprintf(stderr, “Could not open Windows connection.n”);
exit(0);
}
/* Open a datagram socket */
sd = socket(AF_INET, SOCK_DGRAM, 0);
if (sd == INVALID_SOCKET)
{
fprintf(stderr, “Could not create socket.n”);
WSACleanup();
exit(0);
}
/* Clear out server struct */
memset((void *)&server;, ”, sizeof(struct sockaddr_in));
/* Set family and port */
server.sin_family = AF_INET;
server.sin_port = htons(port_number);
/* Set address automatically if desired */
if (argc == 2)
{
/* Get host name of this computer */
gethostname(host_name, sizeof(host_name));
hp = gethostbyname(host_name);
/* Check for NULL pointer */
if (hp == NULL)
{
fprintf(stderr, “Could not get host name.n”);
closesocket(sd);
WSACleanup();
exit(0);
}
/* Assign the address */
server.sin_addr.S_un.S_un_b.s_b1 = hp->h_addr_list[0][0];
server.sin_addr.S_un.S_un_b.s_b2 = hp->h_addr_list[0][1];
server.sin_addr.S_un.S_un_b.s_b3 = hp->h_addr_list[0][2];
server.sin_addr.S_un.S_un_b.s_b4 = hp->h_addr_list[0][3];
}
/* Otherwise assign it manually */
else
{
server.sin_addr.S_un.S_un_b.s_b1 = (unsigned char)a1;
server.sin_addr.S_un.S_un_b.s_b2 = (unsigned char)a2;
server.sin_addr.S_un.S_un_b.s_b3 = (unsigned char)a3;
server.sin_addr.S_un.S_un_b.s_b4 = (unsigned char)a4;
}
/* Bind address to socket */
if (bind(sd, (struct sockaddr *)&server;, sizeof(struct sockaddr_in)) == -1)
{
fprintf(stderr, “Could not bind name to socket.n”);
closesocket(sd);
WSACleanup();
exit(0);
}
/* Print out server information */
printf(“Server running on %u.%u.%u.%un”, (unsigned char)server.sin_addr.S_un.S_un_b.s_b1,
(unsigned char)server.sin_addr.S_un.S_un_b.s_b2,
(unsigned char)server.sin_addr.S_un.S_un_b.s_b3,
(unsigned char)server.sin_addr.S_un.S_un_b.s_b4);
printf(“Press CTRL + C to quitn”);
/* Loop and get data from clients */
while (1)
{
client_length = (int)sizeof(struct sockaddr_in);
/* Receive bytes from client */
bytes_received = recvfrom(sd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client;, &client;_length);
if (bytes_received < 0)
{
fprintf(stderr, “Could not receive datagram.n”);
closesocket(sd);
WSACleanup();
exit(0);
}
/* Check for time request */
if (strcmp(buffer, “GET TIMErn”) == 0)
{
/* Get current time */
current_time = time(NULL);
/* Send data back */
if (sendto(sd, (char *)¤t;_time, (int)sizeof(current_time), 0, (struct sockaddr *)&client;, client_length) != (int)sizeof(current_time))
{
fprintf(stderr, “Error sending datagram.n”);
closesocket(sd);
WSACleanup();
exit(0);
}
}
}
closesocket(sd);
WSACleanup();
return 0;
}
void usage(void)
{
fprintf(stderr, “timeserv [server_address] portn”);
exit(0); }
7. Write an echo client and server program using Unix domain stream socket.
/*
** client.c— a stream socket client demo
*/
#include
#include
#include
#include
#include
#include
#include types.h><span>
#include in.h><span>
#include socket.h><span>
#include inet.h><span>
#define PORT “3490” // the port client will be connecting to
#define MAXDATASIZE 100 // max number of bytes we can get at once
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(int argc, char *argv[])
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
if (argc != 2) {
fprintf(stderr,”usage: client hostnamen”);
exit(1);
}
memset(&hints;, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(argv[1], PORT, &hints;, &servinfo;)) != 0) {
fprintf(stderr, “getaddrinfo: %sn”, gai_strerror(rv));
return 1;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror(“client: socket”);
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror(“client: connect”);
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, “client: failed to connectn”);
return 2;
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
s, sizeof s);
printf(“client: connecting to %sn”, s);
freeaddrinfo(servinfo); // all done with this structure
if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
perror(“recv”);
exit(1);
}
buf[numbytes] = ”;
printf(“client: received ‘%s’n”,buf);
close(sockfd);
return 0;
}
/*
** server.c— a stream socket server demo
*/
#include
#include
#include
#include
#include
#include types.h><span>
#include socket.h><span>
#include in.h><span>
#include
#include inet.h><span>
#include wait.h><span>
#include
#define PORT “3490” // the port users will be connecting to
#define BACKLOG 10 // how many pending connections queue will hold
void sigchld_handler(int s)
{
while(waitpid(-1, NULL, WNOHANG) > 0);
}
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(void)
{
int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector’s address information
socklen_t sin_size;
struct sigaction sa;
int yes=1;
char s[INET6_ADDRSTRLEN];
int rv;
memset(&hints;, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, PORT, &hints;, &servinfo;)) != 0) {
fprintf(stderr, “getaddrinfo: %sn”, gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror(“server: socket”);
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes;,
sizeof(int)) == -1) {
perror(“setsockopt”);
exit(1);
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror(“server: bind”);
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, “server: failed to bindn”);
return 2;
}
freeaddrinfo(servinfo); // all done with this structure
if (listen(sockfd, BACKLOG) == -1) {
perror(“listen”);
exit(1);
}
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa;_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa;, NULL) == -1) {
perror(“sigaction”);
exit(1);
}
printf(“server: waiting for connections…n”);
while(1) { // main accept() loop
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their;_addr, &sin;_size);
if (new_fd == -1) {
perror(“accept”);
continue;
}
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their;_addr),
s, sizeof s);
printf(“server: got connection from %sn”, s);
if (!fork()) { // this is the child process
close(sockfd); // child doesn’t need the listener
if (send(new_fd, “Hello, world!”, 13, 0) == -1)
perror(“send”);
close(new_fd);
exit(0);
}
close(new_fd); // parent doesn’t need this
}
return 0;
}
8. Write an echo client and server program using Unix domain Datagram socket.
/*
** listener.c — a datagram sockets “server” demo
*/
#include
#include
#include
#include
#include
#include types.h><span>
#include socket.h><span>
#include in.h><span>
#include inet.h><span>
#include
#define MYPORT “4950” // the port users will be connecting to
#define MAXBUFLEN 100
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(void)
{
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
struct sockaddr_storage their_addr;
char buf[MAXBUFLEN];
socklen_t addr_len;
char s[INET6_ADDRSTRLEN];
memset(&hints;, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, MYPORT, &hints;, &servinfo;)) != 0) {
fprintf(stderr, “getaddrinfo: %sn”, gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror(“listener: socket”);
continue;
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror(“listener: bind”);
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, “listener: failed to bind socketn”);
return 2;
}
freeaddrinfo(servinfo);
printf(“listener: waiting to recvfrom…n”);
addr_len = sizeof their_addr;
if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,
(struct sockaddr *)&their;_addr, &addr;_len)) == -1) {
perror(“recvfrom”);
exit(1);
}
printf(“listener: got packet from %sn”,
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their;_addr),
s, sizeof s));
printf(“listener: packet is %d bytes longn”, numbytes);
buf[numbytes] = ”;
printf(“listener: packet contains “%s”n”, buf);
close(sockfd);
return 0;
}
/*
** talker.c — a datagram “client” demo
*/
#include
#include
#include
#include
#include
#include types.h><span>
#include socket.h><span>
#include in.h><span>
#include inet.h><span>
#include
#define SERVERPORT “4950” // the port users will be connecting to
int main(int argc, char *argv[])
{
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
if (argc != 3) {
fprintf(stderr,”usage: talker hostname messagen”);
exit(1);
}
memset(&hints;, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo(argv[1], SERVERPORT, &hints;, &servinfo;)) != 0) {
fprintf(stderr, “getaddrinfo: %sn”, gai_strerror(rv));
return 1;
}
// loop through all the results and make a socket
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror(“talker: socket”);
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, “talker: failed to bind socketn”);
return 2;
}
if ((numbytes = sendto(sockfd, argv[2], strlen(argv[2]), 0,
p->ai_addr, p->ai_addrlen)) == -1) {
perror(“talker: sendto”);
exit(1);
}
freeaddrinfo(servinfo);
printf(“talker: sent %d bytes to %sn”, numbytes, argv[1]);
close(sockfd);
return 0;
}
9. Write a client and server program to implement file transfer.
   AIM:
            To implement file transfer using TCP from client to server in java.
  
   ALGORITHM:
   SERVER:
           1. Start , import the required header files.
           2. Create server socket to establish the connetion.
           3. Create bufferred reader to read input array and send the output to print writer objects to display output.
           4. Let the file name that is to be transferred, read every character of the file until null and display it.
            5. Stop.
   CLIENT:
            1.  Start , import the required header files.
            2. Create a socket containing the required IP address.
            3. Create a input buffer reader to read input stream and send the output print object to display output.
            4. Get the file name and read every character of the file until known to transfer the file.
  
          PROGRAM:
          CLIENT:
                   import java.io.*;
                   import java.net.*;
                   import java.util.*;
                   public class ft1client
                   {
                        public static void main(String args[])
                        {
                             try
                             {  
                                  DataInputStream dis=new DataInputStream(System.in);
                                  System.out.println(“Enter the file name :”);
                                  String f=dis.readLine();
                                  File f1= new File(f);
                                  FileReader fr=new FileReader(f1);
                                  Socket s=new Socket(“127.0.0.1”,8081);
                                  PrintWriter put=new PrintWriter(s.getOutputStream(),true);
                                  put.println(f);
                                  int c=0;
                                  while((c=fr.read())!=-1)
                                  put.println(c);
                                  System.out.println(“File content are transferred”);
                                  fr.close();
                                  s.close();
                             }  
                             catch(IOException e)
                             {
                             }
                        }   
                   }   
     
          SERVER:
                 import java.io.*;
                 import java.net.*;
                 import java.util.*;
                 public class ft1server
                
                     public static void main(String args[])throws IOException
                     {   
                         ServerSocket ss;
                         Socket s;
                         try
                         {
                             System.out.println(“Waiting for client”);
                             ss=new ServerSocket(8081);
                             s=ss.accept();
                             System.out.println(“Connection established”);
                             BufferedReader get=new BufferedReader(new InputStreamReader(s.getInputStream()));
                             String fname;
                             fname =get.readLine();
                             System.out.println(“File name is : “+fname);
                             File f=new File(fname);
                             FileWriter fw=new FileWriter(f);
                             String c;
                             while((c=get.readLine())!=null)
                             fw.write(Integer.parseInt(c));
                             System.out.println(“Finished the content”);
                             fw.close();
                         }           
                         catch(IOException e)
                         {
                         }
                     }    
                
        
           OUTPUT:
                  C:jdk1.3bin>javac ft1client.java
                       Note: ft1client.java uses or overrides a deprecated API.
                       Note: Recompile with -deprecation for details.
                       C:jdk1.3bin>javac ft1server.java
                       C:jdk1.3bin>java ft1server
                       Waiting for client
                       2nd
                       C:jdk1.3bin>java ft1client
                       Enter the file name :
                       u1.txt
                       File content are transferred
                       1st
                       C:jdk1.3bin>java ft1server
                       Waiting for client
                       Connection established
                       File name is : u1.txt
                       Finished the content
10. Write a client and server program to implement the remote command execution.
   AIM:
            To create a program for executing a command in the system from a remote point.
  
  ALGORITHM:
    CLIENT:
           1. Start and  import all  the necessary packages.
            2. Create a client side socket with local socket address.
            3. Get the command from user and put it on output stream of socket.
            4. Close the socket and stop.
   SERVER:    
            1.  Start and import all  the necessary packages.
            2. Create a client and server socket and accept the incoming  client request.
            3. Using runtime , create runtime environment.
            4. Using process execution to remote command and stop.
  
          PROGRAM:
          CLIENT:
                  import java.io.*;
                  import java.net.*;
                  public class remclient
                 
                      public static void main(String args[])throws IOException
                     
                          try
                         
                              Socket s=new Socket(“127.0.0.1”,8081);
                              PrintWriter out=new PrintWriter(s.getOutputStream(),true);
                              String cmd;
                              DataInputStream in=new DataInputStream(System.in);
                              System.out.println(“Enter the command to execute on server : “);
                              cmd=in.readLine();
                              out.println(cmd);
                         
                          catch(Exception e)
                         
                              System.out.println(e);
                          }
                     
                  }  
      
           SERVER:
                 import java.io.*;
                 import java.net.*;
                 public class remserver
                
                     public static void main(String args[])throws IOException
                     {
                         ServerSocket ss=new ServerSocket(8081);
                         Socket s=ss.accept();
                         String cmd;
                         BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
                         cmd=in.readLine();
                         try
                         {   
                             Runtime r=Runtime.getRuntime();
                             Process a=r.exec(cmd);
                             System.out.println(“Executing command : “+cmd);
                        
                         catch(Exception e)
                        
                             System.out.println(“Error”+e);
                         }
                         s.close();
                    
                
         
           OUTPUT:
                       C:jdk1.3bin>javac remclient.java
                       Note: remclient.java uses or overrides a deprecated API.
                       Note: Recompile with -deprecation for details.
                       C:jdk1.3bin>javac remserver.java
                       C:jdk1.3bin>java remserver
                       
                       2nd
                       C:jdk1.3bin>java remclient
                       Enter the command to execute on server :
                       notepad
                       C:jdk1.3bin>
                       1st
                       C:jdk1.3bin>java remserver
                       Executing command : notepad
                       C:jdk1.3bin>