ACN

Published on February 2017 | Categories: Documents | Downloads: 42 | Comments: 0 | Views: 344
of 11
Download PDF   Embed   Report

Comments

Content

ACN PRACTICAL LIST
1.study of different network programming related UNIX C system call. 2.Implement UDP protocol based server in UNIX C.
#include <arpa/inet.h> 2 #include <netinet/in.h> 3 #include <stdio.h> 4 #include <sys/types.h> 5 #include <sys/socket.h> 6 #include <unistd.h> 7 8 #define BUFLEN 512 9 #define NPACK 10 10 #define PORT 9930 11 12 void diep(char *s) 13 { 14 perror(s); 15 exit(1); 16 } 17 18 int main(void) 19 { 20 struct sockaddr_in si_me, si_other; 21 int s, i, slen=sizeof(si_other); 22 char buf[BUFLEN]; 23 24 if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1) 25 diep("socket"); 26 27 memset((char *) &si_me, 0, sizeof(si_me)); 28 si_me.sin_family = AF_INET; 29 si_me.sin_port = htons(PORT); 30 si_me.sin_addr.s_addr = htonl(INADDR_ANY); 31 if (bind(s, &si_me, sizeof(si_me))==-1) 32 diep("bind"); 33 34 for (i=0; i<NPACK; i++) { 35 if (recvfrom(s, buf, BUFLEN, 0, &si_other, &slen)==-1) 36 diep("recvfrom()"); 37 printf("Received packet from %s:%d\nData: %s\n\n", 38 inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf); 39 } 40 41 close(s); 42 return 0; 43 }

ACN PRACTICAL LIST
UDP Server Client Implementation in C for Unix/Linux
Here's a simple UDP Server Client Implementation in C for Unix/Linux. As UDP is a connection-less protocol, it is not reliable or we can say that we don't send acknowledgements for the packets sent. Here is a concurrent UDP server which can accept packets from multiple clients simultaneously. The port mentioned here can be changed to any value between 1024 and 65535 (since upto 1024 are known ports).
//UDPServer.c /* * gcc -o server UDPServer.c * ./server */ #include <arpa/inet.h> #include <netinet/in.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #define BUFLEN 512 #define PORT 9930 void err(char *str) { perror(str); exit(1); } int main(void) { struct sockaddr_in my_addr, cli_addr; int sockfd, i; socklen_t slen=sizeof(cli_addr); char buf[BUFLEN]; if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1) err("socket"); else printf("Server : Socket() successful\n"); bzero(&my_addr, sizeof(my_addr)); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(PORT); my_addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sockfd, (struct sockaddr* ) &my_addr, sizeof(my_addr))==-1)

ACN PRACTICAL LIST
err("bind"); else printf("Server : bind() successful\n"); while(1) { if (recvfrom(sockfd, buf, BUFLEN, 0, (struct sockaddr*)&cli_addr, &slen)==-1) err("recvfrom()"); printf("Received packet from %s:%d\nData: %s\n\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port), buf); } close(sockfd); return 0; }

//UDPClient.c /* * gcc -o client UDPClient.c * ./client */ #include <arpa/inet.h> #include <netinet/in.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #define BUFLEN 512 #define PORT 9930 void err(char *s) { perror(s); exit(1); } int main(int argc, char** argv) { struct sockaddr_in serv_addr; int sockfd, i, slen=sizeof(serv_addr); char buf[BUFLEN]; if(argc != 2) { printf("Usage : %s <Server-IP>\n",argv[0]); exit(0); } if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)

ACN PRACTICAL LIST
err("socket"); bzero(&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); if (inet_aton(argv[1], &serv_addr.sin_addr)==0) { fprintf(stderr, "inet_aton() failed\n"); exit(1); } while(1) { printf("\nEnter data to send(Type exit and press enter to exit) : "); scanf("%[^\n]",buf); getchar(); if(strcmp(buf,"exit") == 0) exit(0); if (sendto(sockfd, buf, BUFLEN, 0, (struct sockaddr*)&serv_addr, slen)==-1) err("sendto()"); } close(sockfd); return 0; }

3.Implement UDP protocol based client in UNIX C.
#define 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 SRV_IP "999.999.999.999" /* diep(), #includes and #defines like in the server */ int main(void) { struct sockaddr_in si_other; int s, i, slen=sizeof(si_other); char buf[BUFLEN]; if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1) diep("socket"); memset((char *) &si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; si_other.sin_port = htons(PORT); if (inet_aton(SRV_IP, &si_other.sin_addr)==0) { fprintf(stderr, "inet_aton() failed\n"); exit(1); } for (i=0; i<NPACK; i++) { printf("Sending packet %d\n", i);

ACN PRACTICAL LIST
23 24 25 26 27 28 29 30 sprintf(buf, "This is packet %d\n", i); if (sendto(s, buf, BUFLEN, 0, &si_other, slen)==-1) diep("sendto()"); } close(s); return 0; }

4.Implement TCP protocol based server in UNIX C.
/ File name – server.c // Written and tested on Linux Fedora Core 12 VM #include #include #include #include #include #include #include <stdio.h> <unistd.h> <sys/socket.h> <sys/types.h> <netinet/in.h> <stdlib.h> <string.h>

#define MAX_SIZE 50 int main() { // Two socket descriptors which are just integer numbers used to access a socket int sock_descriptor, conn_desc; // Two socket address structures - One for the server itself and the other for client struct sockaddr_in serv_addr, client_addr; // Buffer to store data read from client char buff[MAX_SIZE]; // Create socket of domain - Internet (IP) address, type - Stream based (TCP) and protocol unspecified // since it is only useful when underlying stack allows more than one protocol and we are choosing one. // 0 means choose the default protocol. sock_descriptor = socket(AF_INET, SOCK_STREAM, 0); // A valid descriptor is always a positive value if(sock_descriptor < 0) printf("Failed creating socket\n"); // Initialize the server address struct to zero bzero((char *)&serv_addr, sizeof(serv_addr)); // Fill server's address family serv_addr.sin_family = AF_INET;

ACN PRACTICAL LIST
// Server should allow connections from any ip address serv_addr.sin_addr.s_addr = INADDR_ANY; // 16 bit port number on which server listens // The function htons (host to network short) ensures that an integer is interpretted // correctly (whether little endian or big endian) even if client and server have different architectures serv_addr.sin_port = htons(1234); // Attach the server socket to a port. This is required only for server since we enforce // that it does not select a port randomly on it's own, rather it uses the port specified // in serv_addr struct. if (bind(sock_descriptor, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) printf("Failed to bind\n"); // Server should start listening - This enables the program to halt on accept call (coming next) // and wait until a client connects. Also it specifies the size of pending connection requests queue // i.e. in this case it is 5 which means 5 clients connection requests will be held pending while // the server is already processing another connection request. listen(sock_descriptor, 5); printf("Waiting for connection...\n"); int size = sizeof(client_addr); // Server blocks on this call until a client tries to establish connection. // When a connection is established, it returns a 'connected socket descriptor' different // from the one created earlier. conn_desc = accept(sock_descriptor, (struct sockaddr *)&client_addr, &size); if (conn_desc == -1) printf("Failed accepting connection\n"); else printf("Connected\n"); // The new descriptor can be simply read from / written up just like a normal file descriptor if ( read(conn_desc, buff, sizeof(buff)-1) > 0) printf("Received %s", buff); else printf("Failed receiving\n"); // Program should always close all sockets (the connected one as well as the listening one) // as soon as it is done processing with it close(conn_desc);

ACN PRACTICAL LIST
close(sock_descriptor); return 0; }

5. Implement TCP protocol based client in UNIX C.
// File name – client.c // Written and tested on Linux Fedora Core 12 VM #include #include #include #include #include #include #include #include <stdio.h> <unistd.h> <sys/socket.h> <sys/types.h> <netinet/in.h> <stdlib.h> <string.h> <netdb.h>

#define MAX_SIZE 50 int main() { // Client socket descriptor which is just integer number used to access a socket int sock_descriptor; struct sockaddr_in serv_addr; // Structure from netdb.h file used for determining host name from local host's ip address struct hostent *server; // Buffer to input data from console and write to server char buff[MAX_SIZE]; // Create socket of domain - Internet (IP) address, type - Stream based (TCP) and protocol unspecified // since it is only useful when underlying stack allows more than one protocol and we are choosing one. // 0 means choose the default protocol. sock_descriptor = socket(AF_INET, SOCK_STREAM, 0); if(sock_descriptor < 0) printf("Failed creating socket\n"); bzero((char *)&serv_addr, sizeof(serv_addr)); server = gethostbyname("127.0.0.1"); if(server == NULL) { printf("Failed finding server name\n"); return -1;

ACN PRACTICAL LIST
} serv_addr.sin_family = AF_INET; memcpy((char *) &(serv_addr.sin_addr.s_addr), (char *)(server>h_addr), server->h_length); // 16 bit port number on which server listens // The function htons (host to network short) ensures that an integer is // interpreted correctly (whether little endian or big endian) even if client and // server have different architectures serv_addr.sin_port = htons(1234); if (connect(sock_descriptor, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("Failed to connect to server\n"); return -1; } else printf("Connected successfully - Please enter string\n"); fgets(buff, MAX_SIZE-1, stdin); int count = write(sock_descriptor, buff, strlen(buff)); if(count < 0) printf("Failed writing rquested bytes to server\n"); close(sock_descriptor); return 0; }

6. Implement UDP protocol based server in java.
import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData,

ACN PRACTICAL LIST
receiveData.length); serverSocket.receive(receivePacket); String sentence = new String( receivePacket.getData()); System.out.println("RECEIVED: " + sentence); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } }

7.Implement UDP protocol based client in java.
import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } }

ACN PRACTICAL LIST
8.Implement TCP protocol based server in java.
import java.io.*; import java.net.*; class TCPServer { public static void main(String args[]) throws Exception { int firsttime = 1; while (true) { String clientSentence; String capitalizedSentence=""; ServerSocket welcomeSocket = new ServerSocket(3248); Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); //System.out.println(clientSentence); if (clientSentence.equals("set")) { outToClient.writeBytes("connection is "); System.out.println("running here"); //welcomeSocket.close(); //outToClient.writeBytes(capitalizedSentence); } capitalizedSentence = clientSentence.toUpperCase() + "\n"; //if(!clientSentence.equals("quit")) outToClient.writeBytes(capitalizedSentence+"enter the message or command: "); System.out.println("passed"); //outToClient.writeBytes("enter the message or command: "); welcomeSocket.close(); System.out.println("connection terminated"); } } }

9.Implement TCP protocol based client in java.
import java.io.*; import java.net.*; class TCPClient { public static void main(String args[]) throws Exception { String sentence; String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("127.0.0.1", 6789); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

ACN PRACTICAL LIST
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + "\n"); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } }

10.Implement TCP protocol based daytime server and client in UNIX C.

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close