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**
```
#include /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), connect(), send(), and recv() */
#include <arpa/inet.h> /* for sockaddr_in and inet_addr() */
#include /* for atoi() and exit() */
#include /* for memset() */
#include /* for close() */
#define RCVBUFSIZE 32 /* Size of receive buffer */
void DieWithError(char *errorMessage); /* Error handling function */
int main(int argc, char *argv[])
{
int sock; /* Socket descriptor */
struct sockaddr_in echoServAddr; /* Echo server address */
unsigned short echoServPort; /* Echo server port */
char *servIP; /* Server IP address (dotted quad) */
char *echoString; /* String to send to echo server */
char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */
unsigned Int echoStringLen; /* Length of string to echo */
int bytesRcvd, totalBytesRcvd; /* Bytes read in single recv()
and total bytes read */
if ((argc < 3) || (argc > 4)) /* Test for correct number of arguments */
{
fprintf(stderr, "Usage: %s []\n",
argv[0]);
exit(1);
}
servIP = argv[1]; /* First arg: server IP address (dotted quad) */
echoString = argv[2]; /* Second arg: string to echo */
if (argc == 4)
echoServPort = atoi(argv[3]); /* Use given port, if any */
else
echoServPort = 7; /* 7 is the well-known port for the echo service */
/* Create a reliable, stream socket using TCP */
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");
/* Construct the server address structure */
memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */
echoServAddr.sin_family = AF_INET; /* Internet address family */
echoServAddr.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */
echoServAddr.sin_port = htons(echoServPort); /* Server port */
/* Establish the connection to the echo server */
if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
DieWithError("connect() failed");
echoStringLen = strlen(echoString); /* Determine input length */
/* Send the string to the server */
if (send(sock, echoString, echoStringLen, 0) != echoStringLen)
DieWithError("send() sent a different number of bytes than expected");
/* Receive the same string back from the server */
totalBytesRcvd = 0;
printf("Received: "); /* Setup to print the echoed string */
while (totalBytesRcvd < echoStringLen)
{
/* Receive up to the buffer size (minus 1 to leave space for
a null terminator) bytes from the sender */
if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)
DieWithError("recv() failed or connection closed prematurely");
totalBytesRcvd += bytesRcvd; /* Keep tally of total bytes */
echoBuffer[bytesRcvd] = '\0'; /* Terminate the string! */
printf(echoBuffer); /* Print the echo buffer */
}
printf("\n"); /* Print a final linefeed */
close(sock);
exit(0);
}
void DieWithError(char *errorMessage)
{
perror(errorMessage);
exit(1);
}
```
</div>
**Server.c**
```
#include /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), bind(), and connect() */
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include /* for atoi() and exit() */
#include /* for memset() */
#include /* for close() */
#define MAXPENDING 5 /* Maximum outstanding connection requests */
#define RCVBUFSIZE 32 /* Size of receive buffer */
void DieWithError(char *errorMessage); /* Error handling function */
void HandleTCPClient(int clntSocket); /* TCP client handling function */
int main(int argc, char *argv[])
{
int servSock; /* Socket descriptor for server */
int clntSock; /* Socket descriptor for client */
struct sockaddr_in echoServAddr; /* Local address */
struct sockaddr_in echoClntAddr; /* Client address */
unsigned short echoServPort; /* Server port */
unsigned int clntLen; /* Length of client address data structure */
if (argc != 2) /* Test for correct number of arguments */
{
fprintf(stderr, "Usage: %s \n", argv[0]);
exit(1);
}
echoServPort = atoi(argv[1]); /* First arg: local port */
/* Create socket for incoming connections */
if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");
/* Construct local address structure */
memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */
echoServAddr.sin_family = AF_INET; /* Internet address family */
echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
echoServAddr.sin_port = htons(echoServPort); /* Local port */
/* Bind to the local address */
if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
DieWithError("bind() failed");
/* Mark the socket so it will listen for incoming connections */
if (listen(servSock, MAXPENDING) < 0)
DieWithError("listen() failed");
for (;;) /* Run forever */
{
/* Set the size of the in-out parameter */
clntLen = sizeof(echoClntAddr);
/* Wait for a client to connect */
if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr,
&clntLen)) < 0)
DieWithError("accept() failed");
/* clntSock is connected to a client! */
printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr));
//fork this process into a child and parent
processid = fork();
if (processid == 0){
/*Child Process*/
close(servSock);
HandleTCPClient(clntSock);
}
close(clntSock);
}
}
void DieWithError(char *errorMessage)
{
perror(errorMessage);
exit(1);
}
void DieWithError(char *errorMessage); /* Error handling function */
void HandleTCPClient(int clntSocket)
{
char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */
int recvMsgSize; /* Size of received message */
while(1)
{
/* Receive message from client */
if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
DieWithError("recv() failed");
/* Send received string and receive again until end of transmission */
while (recvMsgSize > 0) /* zero indicates end of transmission */
{
/* Echo message back to client */
if (send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize)
DieWithError("send() failed");
/* See if there is more data to receive */
if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
DieWithError("recv() failed");
}
}
close(clntSocket); /* Close client socket */
}
```
</div>
**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
2. **Write an echo program with client and concurrent server using TCP.**
**Server:**```
#include
#include
#include
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include
#include
#include <sys/wait.h>
#include
void handler_sigchld(int signum)
{
int status;
// Wait for all terminated children
// Loop is required as Unix signals are not queued by default.
while (waitpid(-1, &status, WNOHANG) > 0) {
}
}
int handle_terminated_children(void)
{
struct sigaction sigact;
sigact.sa_handler = handler_sigchld;
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = SA_RESTART; // Make certain system calls restartable across signals
if (sigaction(SIGCHLD, &sigact, NULL)) {
return -1;
}
return 0;
}
#define SERVER_PORT 10060
/* The maximum length the queue of pending connections may grow to */
#define LISTEN_BACKLOG 16
int server(void)
{
/* Obtain a socket descriptor */
int listen_fd;
listen_fd = socket(AF_INET, SOCK_STREAM, 0); // TCP
if (listen_fd < 0) {
// errno is set appropriately
return -1;
}
/* Assign a local address to the socket */
struct sockaddr_in server_addr; // IPv4 socket address structure
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Wildcard address; Network byte order
server_addr.sin_port = htons(SERVER_PORT);
if (bind(listen_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
// errno is set appropriately
return -2;
}
/* Convert the socket into a passive listening socket */
if (listen(listen_fd, LISTEN_BACKLOG) < 0) {
// errno is set appropriately
return -3;
}
/* Arrange to handle terminated children */
if (handle_terminated_children() < 0) {
return -4;
}
for (;;) {
/* Get the descriptor of the next completed connection for the accepted socket */
int connection_fd;
struct sockaddr_in client_addr;
socklen_t client_addr_len;
client_addr_len = sizeof(client_addr);
connection_fd = accept(listen_fd, (struct sockaddr *) &client_addr, &client_addr_len);
if (connection_fd < 0) {
// errno is set appropriately
switch (errno) {
case EINTR:
// Interrupted by a signal. Restart the connection.
continue;
case EAGAIN:
case ENETDOWN:
case EPROTO:
case ENOPROTOOPT:
case EHOSTDOWN:
case ENONET:
case EHOSTUNREACH:
case EOPNOTSUPP:
case ENETUNREACH:
// Linux accept() passes already-pending network errors on the new
```
</div>
**Client:**
```
#include
#include
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include
#include
ssize_t write_safe(int fd, const void *p, size_t n)
{
ssize_t num_written;
while (n > 0) {
num_written = write(fd, p, n);
if (num_written <= 0) {
if (errno == EINTR)
num_written = 0; // Try again
else
return -1;
}
n -= num_written;
p += num_written;
}
return num_written;
}
ssize_t read_safe(int fd, void *p, size_t n)
{
size_t num_left;
ssize_t num_read;
num_left = n;
while (num_left > 0) {
num_read = read(fd, p, num_left);
if (num_read < 0) {
if (errno == EINTR)
num_read = 0; // Try again
else
return -1;
}
else if (num_read == 0) { // EOF
break;
}
num_left -= num_read;
p += num_read;
}
return n - num_left;
}
int client(const char *server_ip, int server_port)
{
/* Obtain a socket descriptor */
int socket_fd;
socket_fd = socket(AF_INET, SOCK_STREAM, 0); // TCP
if (socket_fd < 0) {
// errno is set appropriately
return -1;
}
/* Specify the address of the server */
struct sockaddr_in server_addr; // IPv4 socket address structure
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
int status;
if ((status = inet_pton(AF_INET, server_ip, &server_addr.sin_addr)) < 0) {
// status < 0: Does not contain a valid address family
// status == 0: Source address is invalid in the specified address family
return -2;
}
server_addr.sin_port = htons(server_port);
/* Initiate a connection on the socket */
if (connect(socket_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
// errno is set appropriately
return -3;
}
/* Interact with the server */
#define STR_MAX 100
// Get a string
char str[STR_MAX];
printf("Enter a few words: ");
if (fgets(str, STR_MAX, stdin)) {
// Send it to the server
if (write_safe(socket_fd, str, strlen(str)) < 0) {
// errno is set appropriately
return -4;
}
}
// Read from the server
ssize_t num_read;
if ((num_read = read_safe(socket_fd, str, STR_MAX)) < 0) {
// errno is set appropriately
return -5;
}
// Display the result returned
printf("Echo: [%*s]\n", num_read, str);
return 0;
}
#define SERVER_PORT 10060
int main(int argc, char *argv[])
{
int retval;
retval = client("127.0.0.1", SERVER_PORT);
printf("retval => %d (%s)\n", retval, strerror(errno));
return 0;
}
```
</div>3. **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);
}
}
4. **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;
}
5. **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>
6. **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>
</div>
Leave a comment