Sie sind auf Seite 1von 51

COMPUTER NETWORKS LAB

B.TECH COMPUTER ENGINEERING


SEMESTER : FIFTH (5 TH)
CODE : CEN-593

SUBMITTED BY: SUBMITTED TO:


Name : NEWTAN KUMAR RAI DR. MD. AMJAD
Roll No.: 17BCS086 MR. MUMTAZ AHMAD
MR. HANNAN MANSOOR

DEPARTMENT OF COMPUTER ENGINEERING

FACULTY OF ENGINEERING AND TECHNOLOGY

JAMIA MILLIA ISLAMIA, NEW DELHI

SESSION : 2019-20
1. Write a program to implement Caesar Cipher.

Encryption:

#include<iostream>
#include<string>
using namespace std;
int main(){
cout<<“ Name : NEWTAN KUMAR RAI”<<endl;
cout<<"Roll No : 17BCS086"<<endl;
int i,j,k;
string s,t;
int key;
cout<<"Enter the key\n";
cin>>key;
cout<<"Enter the message\n";
cin>>s;
for(i=0;i<s.size();i++){
t+=(s[i]-'A'+key)%26+'A';
}
cout<<"\nEncrypted message is "<<t<<'\n';
return 0;
}

Decryption:

#include<iostream>
#include<string>
using namespace std;
int main(){
cout<<"Name : NEWTAN KUMAR RAI<<endl";
cout<<"Roll No : 17BCS086"<<endl;
int i,j,k;
string s,t;
int key;
cout<<"Enter the key\n";
cin>>key;
cout<<"Enter the message to decrypt\n";
cin>>s;
for(i=0;i<s.size();i++){
t+=(s[i]-'A'-key+26)%26+'A';
}
cout<<"\nDecrypted message is "<<t<<'\n';
return 0;
}

2. Write a program to implement Vernam Cipher.

Encryption:
#include<bits/stdc++.h>
using namespace std;

int main(){
cout<<“ Name : NEWTAN KUMAR RAI”<<endl;
cout<<"Roll No : 17BCS086"<<endl;
int t,n,i,j,k,sum=0;
string m;
cout<<"Enter the message"<<'\n';
cin>>m;
string key;
cout<<"Enter the key"<<'\n';
cin>>key;
int mod = key.size();
j=0;
for(i=key.size();i<m.size();i++){
key+=key[j%mod];
j++;
}
string ans="";
for(i=0;i<m.size();i++){
ans += (key[i]-'A'+m[i]-'A')%26+'A';
}
cout<<"Encrypted message: "<<ans<<'\n';

return 0;
}

Decryption:
#include<bits/stdc++.h>
using namespace std;

int main(){
cout<<"Name : NEWTAN KUMAR RAI"<<endl;
cout<<"Roll No : 17BCS086"<<endl;
int t,n,i,j,k,sum=0;
string m;
cout<<"Enter the message"<<'\n';
cin>>m;
string key;
cout<<"Enter the key"<<'\n';
cin>>key;
int mod = key.size();
j=0;
for(i=key.size();i<m.size();i++){
key+=key[j%mod];
j++;
}
string ans="";
for(i=0;i<m.size();i++){
ans += (m[i]-key[i]+26)%26+'A';
}
cout<<"Decrypted message: "<<ans<<'\n';

return 0;
}

3. Write a program to implement Vigenère Cipher.

Encryption:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main(){
cout<<"Name : NEWTAN KUMAR RAI"<<endl;
cout<<"Roll No : 17BCS086"<<endl;
int i,j,k,n;
vector<vector<char>> a(26,vector<char>(26));
k=0;
n=26;
for(i=0;i<n;i++){
k=i;
for(j=0;j<n;j++){
a[i][j]='A'+k;
k++;
if(k==26)
k=0;
}
}
cout<<"Enter the message\n";
string s;
cin>>s;
cout<<"Enter the key\n";
string key;
cin>>key;
k=0;
int mod = key.size();
for(i=key.size();i<s.size();i++){
key+=key[k%mod];
k++;
}
string encrypt;
for(i=0;i<s.size();i++){
encrypt+= a[s[i]-'A'][key[i]-'A'];
}
cout<<"Encrypted message: "<<encrypt<<'\n';
return 0;
}

Decryption:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main(){
cout<<"Name : NEWTAN KUMAR RAI"<<endl;
cout<<"Roll No : 17BCS086"<<endl;
int i,j,k,n;
vector<vector<char>> a(26,vector<char>(26));
k=0;
n=26;
for(i=0;i<n;i++){
k=i;
for(j=0;j<n;j++){
a[i][j]='A'+k;
k++;
if(k==26)
k=0;
}
}
cout<<"Enter the encrypted message\n";
string s;
cin>>s;
cout<<"Enter the key\n";
string key;
cin>>key;
k=0;
for(i=key.size();i<s.size();i++){
key+=key[k];
k++;
}
string decrypt;
for(i=0;i<s.size();i++){
for(j=0;j<n;j++){
if(a[j][key[i]-'A']==s[i]){
decrypt += 'A'+j;
break;
}
}
}
cout<<"Decrypted message: "<<decrypt<<'\n';
return 0;
}

4. Write a program to implement Hill Cipher.

Encryption:
#include<iostream>
#include<vector>
using namespace std;
int main(){
cout<<“ Name : NEWTAN KUMAR RAI”<<endl;
cout<<"Roll No : 17BCS086"<<endl;
int x,y,i,j,k,n;
cout<<"Enter the size of key matrix\n";
cin>>n;
cout<<"Enter the key matrix\n";
int a[n][n];
for(i=0;i<n;i++){
for(j=0;j<n;j++){
cin>>a[i][j];
}
}
cout<<"Enter the message to encrypt\n";
string s;
cin>>s;
int temp = (n-s.size()%n)%n;
for(i=0;i<temp;i++){
s+='x';
}
k=0;
string ans="";
while(k<s.size()){
for(i=0;i<n;i++){
int sum = 0;
int temp = k;
for(j=0;j<n;j++){
sum += (a[i][j]%26*(s[temp++]-'a')%26)%26;
sum = sum%26;
}
ans+=(sum+'a');
}
k+=n;
}
cout<<ans<<'\n';

return 0;
}

Decryption:
#include<iostream>
#include<vector>
using namespace std;
int modInverse(int a, int m){
a=a%m;
for(int x=-m;x<m;x++)
if((a*x)%m==1)
return x;
}

void getCofactor(vector<vector<int>>&a, vector<vector<int>>&temp, int p, int q,


int n){
int i=0,j=0;
for(int row=0;row<n;row++){
for(int col=0;col<n;col++){
if(row!=p&&col!=q){
temp[i][j++] = a[row][col];
if (j==n-1){
j=0;
i++;
}
}
}
}
}

int determinant(vector<vector<int>>&a, int n, int N){


int D = 0;
if(n==1)
return a[0][0];
vector<vector<int>> temp(N, vector<int>(N));
int sign = 1;
for(int f=0;f<n;f++){
getCofactor(a, temp, 0, f, n);
D += sign * a[0][f] * determinant(temp, n - 1, N);
sign = -sign;
}
return D;
}

void adjoint(vector<vector<int>>&a,vector<vector<int>>&adj,int N){


if(N == 1){
adj[0][0] = 1;
return;
}
int sign = 1;
vector<vector<int>> temp(N, vector<int>(N));
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
getCofactor(a, temp, i, j, N);
sign = ((i+j)%2==0)? 1: -1;
adj[j][i] = (sign)*(determinant(temp, N-1 , N));
}
}
}

bool inverse(vector<vector<int>>&a, vector<vector<int>>&inv, int N){


int det = determinant(a, N, N);
if(det == 0){
cout << "Inverse does not exist";
return false;
}
int invDet = modInverse(det,26);
cout<<det%26<<' '<<invDet<<'\n';
vector<vector<int>> adj(N, vector<int>(N));
adjoint(a, adj, N);
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
inv[i][j] = (adj[i][j]*invDet)%26;
return true;
}

int main(){
cout<<“ Name : NEWTAN KUMAR RAI”<<endl;
cout<<"Roll No : 17BCS086"<<endl;
int x,y,i,j,k,n;
cout<<"Enter the size of key matrix\n";
cin>>n;
cout<<"Enter the key matrix\n";
vector<vector<int>> a(n, vector<int>(n));
vector<vector<int>> adj(n, vector<int>(n));
vector<vector<int>> inv(n, vector<int>(n));

for(i=0;i<n;i++){
for(j=0;j<n;j++){
cin>>a[i][j];
}
}
if(inverse(a,inv,n)){
cout<<"Inverse exist\n";
}

cout<<"Enter the message to decrypt\n";


string s;
cin>>s;
k=0;
string ans;
while(k<s.size()){
for(i=0;i<n;i++){
int sum = 0;
int temp = k;
for(j=0;j<n;j++){
sum += ((inv[i][j] + 26)%26*(s[temp++]-'a')
%26)%26;
sum = sum%26;
}
ans+=(sum+'a');
}
k+=n;
}

int f=ans.size()-1;
while(ans[f]=='x'){
f--;
}

for(i=0;i<=f;i++){
cout<<ans[i];
}
cout<<'\n';
return 0;
}
5. Write a program to implement Rail Fence Cipher.

Encryption:
#include<bits/stdc++.h>
using namespace std;

int main(){
cout<<“ Name : NEWTAN KUMAR RAI”<<endl;
cout<<"Roll No : 17BCS086"<<endl;

int t,n,m,i,j,k,sum=0;
string s;
cout<<"Enter the message"<<'\n';
cin>>s;
cout<<"Enter key"<<'\n';
cin>>n;
vector<vector<char>> a(n,vector<char>(s.size(),' '));
j=0;
int flag=0;
for(i=0;i<s.size();i++){
a[j][i] = s[i];
if(j==n-1){
flag=1;
}
else if(j==0)
flag=0;

if(flag==0){
j++;
}
else j--;
}
for(i=0;i<n;i++){
for(j=0;j<s.size();j++){
if(a[i][j]!=' ')
cout<<a[i][j];
}
}
cout<<'\n';
return 0;
}
Decryption:
#include<bits/stdc++.h>
using namespace std;

int main(){
cout<<“ Name : NEWTAN KUMAR RAI”<<endl;
cout<<"Roll No : 17BCS086"<<endl;
int t,n,m,i,j,k,sum=0;
string s;
cout<<"Enter the message to decrypt"<<'\n';
cin>>s;
cout<<"Enter key"<<'\n';
cin>>n;

vector<vector<char>> a(n,vector<char>(s.size(),' '));

j=0;
int flag=0;
for(i=0;i<s.size();i++){
a[j][i] = '0';
if(j==n-1){
flag=1;
}
else if(j==0)
flag=0;

if(flag==0){
j++;
}
else j--;
}
int temp =0;
for(i=0;i<n;i++){
for(j=0;j<s.size();j++){
if(a[i][j]=='0')
a[i][j]= s[temp++];
}
}
flag=0;
j=0;
for(i=0;i<s.size();i++){
cout<<a[j][i];
if(j==n-1){
flag=1;
}
else if(j==0)
flag=0;

if(flag==0){
j++;
}
else j--;
}
cout<<'\n';
return 0;
}
6. Write a program to implement Play Fair Cipher using Client-
Server.

Server:
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include<unistd.h>
using namespace std;
#define MAX 80
#define PORT 8080
#define SA struct sockaddr

string decrypt(string s,string key){


int i,j,k,n;

vector<vector<char>> a(5,vector<char>(5,' '));


n=5;
map<char,int> mp;
k=0;
int pi,pj;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
while(mp[key[k]]>0&&k<key.size()){
k++;
}
if(k<key.size()){
a[i][j]=key[k];
mp[key[k]]++;
pi=i;
pj=j;
}
if(k==key.size())
break;
}
if(k==key.size())
break;
}
k=0;
for(;i<n;i++){
for(;j<n;j++){
while(mp[char(k+'a')]>0&&k<26){
k++;
}
if(char(k+'a')=='j'){
j--;
k++;
continue;
}
if(k<26){
a[i][j]=char(k+'a');
mp[char(k+'a')]++;
}
}
j=0;
}

string ans;
if(s.size()%2==1)
s+="x";
for(i=0;i<s.size()-1;i++){
if(s[i]==s[i+1])
s[i+1]='x';
}

map<char,pair<int,int>> mp2;

for(i=0;i<n;i++){
for(j=0;j<n;j++){
mp2[a[i][j]] = make_pair(i,j);
}
}
for(i=0;i<s.size()-1;i+=2){
int y1 = mp2[s[i]].first;
int x1 = mp2[s[i]].second;
int y2 = mp2[s[i+1]].first;
int x2 = mp2[s[i+1]].second;
if(y1==y2){
ans+=a[y1][(x1-1)%5];
ans+=a[y1][(x2-1)%5];
}
else if(x1==x2){
ans+=a[(y1-1)%5][x1];
ans+=a[(y2-1)%5][x2];
}
else {
ans+=a[y1][x2];
ans+=a[y2][x1];
}
}

if(ans[ans.size()-1]=='x')
ans[ans.size()-1]='\0';

for(i=1;i<ans.size();i++){
if(ans[i]=='x')
ans[i]=ans[i-1];
}

return ans;
}

string encrypt(string origin,string key){


int i,j,k,n;
string s;
for(i=0;i<origin.size();i++){
if(origin[i]!=' ')
s+= origin[i];
}
vector<vector<char>> a(5,vector<char>(5,' '));
n=5;
map<char,int> mp;
k=0;
int pi,pj;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
while(mp[key[k]]>0&&k<key.size()){
k++;
}
if(k<key.size()){
a[i][j]=key[k];
mp[key[k]]++;
pi=i;
pj=j;
}
if(k==key.size())
break;
}
if(k==key.size())
break;
}
k=0;
for(;i<n;i++){
for(;j<n;j++){
while(mp[char(k+'a')]>0&&k<26){
k++;
}
if(char(k+'a')=='j'){
j--;
k++;
continue;
}
if(k<26){
a[i][j]=char(k+'a');
mp[char(k+'a')]++;
}
}
j=0;
}

string ans;
if(s.size()%2==1)
s+="x";
for(i=0;i<s.size()-1;i++){
if(s[i]==s[i+1])
s[i+1]='x';
}
map<char,pair<int,int>> mp2;

for(i=0;i<n;i++){
for(j=0;j<n;j++){
mp2[a[i][j]] = make_pair(i,j);
}
}
for(i=0;i<s.size()-1;i+=2){
int y1 = mp2[s[i]].first;
int x1 = mp2[s[i]].second;
int y2 = mp2[s[i+1]].first;
int x2 = mp2[s[i+1]].second;
if(y1==y2){
ans+=a[y1][(x1+1)%5];
ans+=a[y1][(x2+1)%5];
}
else if(x1==x2){
ans+=a[(y1+1)%5][x1];
ans+=a[(y2+1)%5][x2];
}
else {
ans+=a[y1][x2];
ans+=a[y2][x1];
}
}
return ans;
}

// Function designed for chat between client and server.


void func(int sockfd)
{
char buff[MAX];
int n;
// infinite loop for chat
for (;;) {
bzero(buff, MAX);
// read the message from client and copy it in buffer
read(sockfd, buff, sizeof(buff));
// print buffer which contains the client contents
cout<<"From client: "<<buff<<endl;
string s;
for(int i=0;i<buff[i]!='\0';i++){
s+=buff[i];
}
cout<<"Enter the key to decrpyt"<<endl;
string key;
cin>>key;
string ans = decrypt(s,key);
cout<<ans<<endl;
cout<<"To client"<<endl;
cin>>ws;

bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n');

// and send that buffer to client


write(sockfd, buff, sizeof(buff));

// if msg contains "Exit" then server exit and chat ended.


if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
}

// Driver function
int main(){
cout<<"Name : NEWTAN KUMAR RAI"<<endl;
cout<<"Roll No : 17BCS086"<<endl;
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;

// socket create and verification


sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));

// assign IP, PORT


servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);

// Binding newly created socket to given IP and verification


if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");

// Now server is ready to listen and verification


if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);

// Accept the data packet from client and verification


connfd = accept(sockfd, (SA*)&cli, (socklen_t*)&len);
if (connfd < 0) {
printf("server acccept failed...\n");
exit(0);
}
else
printf("server acccept the client...\n");

// Function for chatting between client and server


func(connfd);

// After chatting close the socket


close(sockfd);
}

Client:
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <iostream>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <vector>
#include <map>
#include<bits/stdc++.h>
#include<unistd.h>

using namespace std;


#define MAX 80
#define PORT 8080
#define SA struct sockaddr

string encrypt(string origin,string key){


int i,j,k,n;
string s;
for(i=0;i<origin.size();i++){
if(origin[i]!=' ')
s+= origin[i];
}
vector<vector<char>> a(5,vector<char>(5,' '));
n=5;
map<char,int> mp;
k=0;
int pi,pj;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
while(mp[key[k]]>0&&k<key.size()){
k++;
}
if(k<key.size()){
a[i][j]=key[k];
mp[key[k]]++;
pi=i;
pj=j;
}
if(k==key.size())
break;
}
if(k==key.size())
break;
}
k=0;
for(;i<n;i++){
for(;j<n;j++){
while(mp[char(k+'a')]>0&&k<26){
k++;
}
if(char(k+'a')=='j'){
j--;
k++;
continue;
}
if(k<26){
a[i][j]=char(k+'a');
mp[char(k+'a')]++;
}
}
j=0;
}

string ans;
if(s.size()%2==1)
s+="x";
for(i=0;i<s.size()-1;i++){
if(s[i]==s[i+1])
s[i+1]='x';
}

map<char,pair<int,int>> mp2;

for(i=0;i<n;i++){
for(j=0;j<n;j++){
mp2[a[i][j]] = make_pair(i,j);
}
}
for(i=0;i<s.size()-1;i+=2){
int y1 = mp2[s[i]].first;
int x1 = mp2[s[i]].second;
int y2 = mp2[s[i+1]].first;
int x2 = mp2[s[i+1]].second;
if(y1==y2){
ans+=a[y1][(x1+1)%5];
ans+=a[y1][(x2+1)%5];
}
else if(x1==x2){
ans+=a[(y1+1)%5][x1];
ans+=a[(y2+1)%5][x2];
}
else {
ans+=a[y1][x2];
ans+=a[y2][x1];
}
}
return ans;
}

string decrypt(string s,string key){


int i,j,k,n;

vector<vector<char>> a(5,vector<char>(5,' '));


n=5;
map<char,int> mp;
k=0;
int pi,pj;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
while(mp[key[k]]>0&&k<key.size()){
k++;
}
if(k<key.size()){
a[i][j]=key[k];
mp[key[k]]++;
pi=i;
pj=j;
}
if(k==key.size())
break;
}
if(k==key.size())
break;
}
k=0;
for(;i<n;i++){
for(;j<n;j++){
while(mp[char(k+'a')]>0&&k<26){
k++;
}
if(char(k+'a')=='j'){
j--;
k++;
continue;
}
if(k<26){
a[i][j]=char(k+'a');
mp[char(k+'a')]++;
}
}
j=0;
}

string ans;
if(s.size()%2==1)
s+="x";
for(i=0;i<s.size()-1;i++){
if(s[i]==s[i+1])
s[i+1]='x';
}

map<char,pair<int,int>> mp2;

for(i=0;i<n;i++){
for(j=0;j<n;j++){
mp2[a[i][j]] = make_pair(i,j);
}
}
for(i=0;i<s.size()-1;i+=2){
int y1 = mp2[s[i]].first;
int x1 = mp2[s[i]].second;
int y2 = mp2[s[i+1]].first;
int x2 = mp2[s[i+1]].second;
if(y1==y2){
ans+=a[y1][(x1-1)%5];
ans+=a[y1][(x2-1)%5];
}
else if(x1==x2){
ans+=a[(y1-1)%5][x1];
ans+=a[(y2-1)%5][x2];
}
else {
ans+=a[y1][x2];
ans+=a[y2][x1];
}
}

if(ans[ans.size()-1]=='x')
ans[ans.size()-1]='\0';

for(i=1;i<ans.size();i++){
if(ans[i]=='x')
ans[i]=ans[i-1];
}

return ans;
}

void func(int sockfd)


{
char buff[MAX];
int n;
for (;;) {
bzero(buff, sizeof(buff));
cout<<"Enter the message"<<endl;
n = 0;
cin>>ws;
while ((buff[n++] = getchar()) != '\n');

string s;
for(int i=0;i<n-1;i++){
s+=buff[i];
}
//cout<<s<<'\n';
string key;
cout<<"Enter the key\n";
cin>>key;
string ans = encrypt(s,key);
bzero(buff, sizeof(buff));
for(int i=0;i<ans.size();i++){
buff[i]=ans[i];
}

write(sockfd, buff, sizeof(buff));


bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff));
printf("From Server : %s", buff);

if ((strncmp(buff, "exit", 4)) == 0) {


printf("Client Exit...\n");
break;
}
}
}

int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;

// socket create and varification


sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);

// connect the client socket to server socket


if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) {
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");

// function for chat


func(sockfd);

// close the socket


close(sockfd);
}

SERVER:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#define IP_PROTOCOL 0
#define PORT_NO 15050
#define NET_BUF_SIZE 32
#define cipherKey 'S'
#define sendrecvflag 0
#define nofile "File Not Found!"

// function to clear buffer


void clearBuf(char* b)
{
int i;
for (i = 0; i < NET_BUF_SIZE; i++)
b[i] = '\0';
}
// function to encrypt
char Cipher(char ch)
{
return ch ^ cipherKey;
}

// function sending file


int sendFile(FILE* fp, char* buf, int s)
{
int i, len;
if (fp == NULL) {
strcpy(buf, nofile);
len = strlen(nofile);
buf[len] = EOF;
for (i = 0; i <= len; i++)
buf[i] = Cipher(buf[i]);
return 1;
}

char ch, ch2;


for (i = 0; i < s; i++) {
ch = fgetc(fp);
ch2 = Cipher(ch);
buf[i] = ch2;
if (ch == EOF)
return 1;
}
return 0;
}

// driver code
int main()
{
int sockfd, nBytes;
struct sockaddr_in addr_con;
int addrlen = sizeof(addr_con);
addr_con.sin_family = AF_INET;
addr_con.sin_port = htons(PORT_NO);
addr_con.sin_addr.s_addr = INADDR_ANY;
char net_buf[NET_BUF_SIZE];
FILE* fp;

// socket()
sockfd = socket(AF_INET, SOCK_DGRAM, IP_PROTOCOL);

if (sockfd < 0)
printf("\nfile descriptor not received!!\n");
else
printf("\nfile descriptor %d received\n", sockfd);

// bind()
if (bind(sockfd, (struct sockaddr*)&addr_con, sizeof(addr_con)) == 0)
printf("\nSuccessfully binded!\n");
else
printf("\nBinding Failed!\n");

while (1) {
printf("\nWaiting for file name...\n");

// receive file name


clearBuf(net_buf);

nBytes = recvfrom(sockfd, net_buf,


NET_BUF_SIZE, sendrecvflag,
(struct sockaddr*)&addr_con, &addrlen);

fp = fopen(net_buf, "r");
printf("\nFile Name Received: %s\n", net_buf);
if (fp == NULL)
printf("\nFile open failed!\n");
else
printf("\nFile Successfully opened!\n");

while (1) {

// process
if (sendFile(fp, net_buf, NET_BUF_SIZE)) {
sendto(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag,
(struct sockaddr*)&addr_con, addrlen);
break;
}

// send
sendto(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag,
(struct sockaddr*)&addr_con, addrlen);
clearBuf(net_buf);
}
if (fp != NULL)
fclose(fp);
}
return 0;
}
7. Write a program to implement message transfer using Client-
Server.

Server:
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr

// Function designed for chat between client and server.


void func(int sockfd)
{
char buff[MAX];
int n;
// infinite loop for chat
for (;;) {
bzero(buff, MAX);

// read the message from client and copy it in buffer


read(sockfd, buff, sizeof(buff));
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n')
;

// and send that buffer to client


write(sockfd, buff, sizeof(buff));
// if msg contains "Exit" then server exit and chat ended.
if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
}

// Driver function
int main() {
cout<<"Name : NEWTAN KUMAR RAI"<<endl;
cout<<"Roll No : 17BCS086"<<endl;
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;

// socket create and verification


sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));

// assign IP, PORT


servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);

// Binding newly created socket to given IP and verification


if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");

// Now server is ready to listen and verification


if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);

// Accept the data packet from client and verification


connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) {
printf("server acccept failed...\n");
exit(0);
}
else
printf("server acccept the client...\n");

// Function for chatting between client and server


func(connfd);

// After chatting close the socket


close(sockfd);
}

Client:
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for (;;) {
bzero(buff, sizeof(buff));
printf("Enter the string : ");
n = 0;
while ((buff[n++] = getchar()) != '\n')
;
write(sockfd, buff, sizeof(buff));
bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff));
printf("From Server : %s", buff);
if ((strncmp(buff, "exit", 4)) == 0) {
printf("Client Exit...\n");
break;
}
}
}

int main(){
cout<<"Name : NEWTAN KUMAR RAI"<<endl;
cout<<"Roll No : 17BCS086"<<endl;
int sockfd, connfd;
struct sockaddr_in servaddr, cli;

// socket create and varification


sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));

// assign IP, PORT


servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);

// connect the client socket to server socket


if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) {
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");

// function for chat


func(sockfd);

// close the socket


close(sockfd);
}

8. Write a program to implement multicast and broadcast using


Client-Server.

Server:
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr

// Function designed for chat between client and server.


void func(int sockfd)
{
char buff[MAX];
int n;
// infinite loop for chat
for (;;) {
bzero(buff, MAX);

// read the message from client and copy it in buffer


read(sockfd, buff, sizeof(buff));
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n')
;

// and send that buffer to client


write(sockfd, buff, sizeof(buff));

// if msg contains "Exit" then server exit and chat ended.


if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
}

// Driver function
int main() {
cout<<"Name : NEWTAN KUMAR RAI"<<endl;
cout<<"Roll No : 17BCS086"<<endl;
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;

// socket create and verification


sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));

// assign IP, PORT


servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);

// Binding newly created socket to given IP and verification


if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");

// Now server is ready to listen and verification


if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);

// Accept the data packet from client and verification


connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) {
printf("server acccept failed...\n");
exit(0);
}
else
printf("server acccept the client...\n");

// Function for chatting between client and server


func(connfd);

// After chatting close the socket


close(sockfd);
}

Client:
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for (;;) {
bzero(buff, sizeof(buff));
printf("Enter the string : ");
n = 0;
while ((buff[n++] = getchar()) != '\n')
;
write(sockfd, buff, sizeof(buff));
bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff));
printf("From Server : %s", buff);
if ((strncmp(buff, "exit", 4)) == 0) {
printf("Client Exit...\n");
break;
}
}
}

int main(){
cout<<"Name : NEWTAN KUMAR RAI"<<endl;
cout<<"Roll No : 17BCS086"<<endl;
int sockfd, connfd;
struct sockaddr_in servaddr, cli;

// socket create and varification


sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));

// assign IP, PORT


servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);

// connect the client socket to server socket


if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) {
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");

// function for chat


func(sockfd);

// close the socket


close(sockfd);
}

9. Write a program to transfer text file using Client-Server.

Client:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netdb.h>
#define IP_PROTOCOL 0
#define IP_ADDRESS "127.0.0.1" // localhost
#define PORT_NO 15050
#define NET_BUF_SIZE 32
#define cipherKey 'S'
#define sendrecvflag 0

// function to clear buffer


void clearBuf(char* b)
{
int i;
for (i = 0; i < NET_BUF_SIZE; i++)
b[i] = '\0';
}

// function for decryption


char Cipher(char ch)
{
return ch ^ cipherKey;
}

// function to receive file


int recvFile(char* buf, int s)
{
int i;
char ch;
for (i = 0; i < s; i++) {
ch = buf[i];
ch = Cipher(ch);
if (ch == EOF)
return 1;
else
printf("%c", ch);
}
return 0;
}

// driver code
int main()
{
int sockfd, nBytes;
cout<<"Name : NEWTAN KUMAR RAI"<<endl;
cout<<"Roll No : 17BCS086"<<endl;
struct sockaddr_in addr_con;
struct hostent *server;
server = gethostbyname("Khan-2.local");
bzero((char *) &addr_con, sizeof(addr_con));
addr_con.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&addr_con.sin_addr.s_addr,
server->h_length);
int addrlen = sizeof(addr_con);
addr_con.sin_family = AF_INET;
addr_con.sin_port = htons(PORT_NO);
char net_buf[NET_BUF_SIZE];
FILE* fp;

// socket()
sockfd = socket(AF_INET, SOCK_DGRAM,
IP_PROTOCOL);

if (sockfd < 0)
printf("\nfile descriptor not received!!\n");
else
printf("\nfile descriptor %d received\n", sockfd);

while (1) {
printf("\nPlease enter file name to receive:\n");
scanf("%s", net_buf);
sendto(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag, (struct sockaddr*)&addr_con,
addrlen);

printf("\nData Received!!!\n");

while (1) {
// receive
clearBuf(net_buf);
nBytes = recvfrom(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag, (struct sockaddr*)&addr_con,
&addrlen);

// process
if (recvFile(net_buf, NET_BUF_SIZE)) {
break;
}
}
printf("\n-------------------------------\n");
}
return 0; }
10. Write
a program to transfer message using Client-Server between
Computers.

Client:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

void error(const char *msg)


{
perror(msg);
exit(0);
}

int main(int argc, char *argv[])


{
int sockfd, portno, n;
cout<<"Name : NEWTAN KUMAR RAI"<<endl;
cout<<"Roll No : 17BCS086"<<endl;
struct sockaddr_in serv_addr;
struct hostent *server;

char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR connecting");
while(1){
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd, buffer, strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd, buffer, 255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n", buffer);}
close(sockfd);
return 0;
}
Server:
/* The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

void error(const char *msg)


{
perror(msg);
exit(1);
}

int main(int argc, char *argv[])


{
int sockfd, newsockfd, portno;
printf("Name:\t NEWTAN KUMAR RAI\n");
printf("Roll No:\t17BCS086\n");

socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
// create a socket
// socket(int domain, int type, int protocol)
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");

// clear address structure


bzero((char *) &serv_addr, sizeof(serv_addr));

portno = atoi(argv[1]);

/* setup the host_addr structure for use in bind call */


// server byte order
serv_addr.sin_family = AF_INET;

// automatically be filled with current host's IP address


serv_addr.sin_addr.s_addr = INADDR_ANY;

// convert short integer value for port must be converted into network byte order
serv_addr.sin_port = htons(portno);

// bind(int fd, struct sockaddr *local_addr, socklen_t addr_length)


// bind() passes file descriptor, the address structure,
// and the length of the address structure
// This bind() call will bind the socket to the current IP address on port, portno
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");

// This listen() call tells the socket to listen to the incoming connections.
// The listen() function places all incoming connection into a backlog queue
// until accept() call accepts the connection.
// Here, we set the maximum size for the backlog queue to 5.
listen(sockfd,5);

// The accept() call actually accepts an incoming connection


clilen = sizeof(cli_addr);

// This accept() function will write the connecting client's address info
// into the the address structure and the size of that structure is clilen.
// The accept() returns a new socket file descriptor for the accepted connection.
// So, the original socket file descriptor can continue to be used
// for accepting new connections while the new socker file descriptor is used for
// communicating with the connected client.
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");

//printf("server: got connection from %s port %d\n",


// inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));

// This send() function sends the 13 bytes of the string to the new socket
//send(newsockfd, "Hello, world!\n", 13, 0);
while(1)
{ bzero(buffer,256);

n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
bzero(buffer,256);
fgets(buffer,255,stdin);
send(newsockfd,buffer,strlen(buffer),0);
}
close(newsockfd);
close(sockfd);
return 0;
}
11.Write a program to implement chat using client-server.

Client:
import sys
import socket
import select

def chat_client():
if(len(sys.argv) < 3) :
print 'Usage : python chat_client.py hostname port'
sys.exit()

host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)

# connect to remote host


try :
s.connect((host, port))
except :
print 'Unable to connect'
sys.exit()

print 'Connected to remote host. You can start sending messages'


sys.stdout.write('[Me] '); sys.stdout.flush()

while 1:
socket_list = [sys.stdin, s]

# Get the list sockets which are readable


ready_to_read,ready_to_write,in_error = select.select(socket_list , [], [])

for sock in ready_to_read:


if sock == s:
# incoming message from remote server, s
data = sock.recv(4096)
if not data :
print '\nDisconnected from chat server'
sys.exit()
else :
#print data
if data.find("%")!=-1:
p=data.split("%")
x=sock.getsockname()
# print p
socket_ip=str(x[0])
data_ip=str(p[1])
socket_ip.strip(" ")
data_ip=data_ip[1:len(data_ip)-1]
# print(len(data_ip),len(socket_ip))
# print str(x[0])==str(p[1])
if data_ip==socket_ip:
# sys.stdout.write(data)
sys.stdout.write(p[0])
sys.stdout.write('\n[Me] '); sys.stdout.flush()
else:
sys.stdout.write(data)
sys.stdout.write('[Me] '); sys.stdout.flush()

else :
# user entered a message
print "who do you wish to send the mesage to?"
ip=raw_input()
msg = sys.stdin.readline()
msg=ip+" % "+msg
s.send(msg)
sys.stdout.write('[Me] '); sys.stdout.flush()

if __name__ == "__main__":

sys.exit(chat_client())

server:
import sys
import socket
import select

HOST = ''
SOCKET_LIST = []
RECV_BUFFER = 4096
PORT = 9007

def chat_server():

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)

# add server socket object to the list of readable connections


SOCKET_LIST.append(server_socket)

print "Chat server started on port " + str(PORT)

while 1:

# get the list sockets which are ready to be read through select
# 4th arg, time_out = 0 : poll and never block
ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0)

for sock in ready_to_read:


# a new connection request recieved
if sock == server_socket:
sockfd, addr = server_socket.accept()
SOCKET_LIST.append(sockfd)
print "Client (%s, %s) connected" % addr

broadcast(server_socket, sockfd, "[%s:%s] entered our chatting room\n" % addr)

# a message from a client, not a new connection


else:
# process data recieved from client,
try:
# receiving data from the socket.
data = sock.recv(RECV_BUFFER)
print data
if data:
# there is something in the socket
broadcast(server_socket, sock, "\r" + '[' + str(sock.getpeername()) + '] ' + data)
else:
# remove the socket that's broken
if sock in SOCKET_LIST:
SOCKET_LIST.remove(sock)

# at this stage, no data means probably the connection has been broken
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)

# exception
except:
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
continue

server_socket.close()

# broadcast chat messages to all connected clients


def broadcast (server_socket, sock, message):
for socket in SOCKET_LIST:
# send the message only to peer
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
# broken socket connection
socket.close()
# broken socket, remove it
if socket in SOCKET_LIST:
SOCKET_LIST.remove(socket)

if __name__ == "__main__":

sys.exit(chat_server())
******** THE END ********

Das könnte Ihnen auch gefallen