Aim: Programs using Raw sockets (like packet capturing and filtering)
Progarmming
Server
#include<stdio.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<errno.h>
#define SIZE 256
int main()
{
intsrFd,CIFD,len;
structsockaddr_inserver,client;
charbuf[SIZE],buf1[SIZE];
intn,j;
FILE *fp,*fp1;
srFd=socket(AF_INET,SOCK_STREAM,0);
if(srFd<0)
{
printf(“\n Socket error”);
exit(0);
}
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(2200);
server.sin_addr.s_addr=htons(INADDR_ANY);
if(bind(srFd,(structsockaddr *)&server,sizeof(server))<0)
{
printf(“\n server : bind error”);
close(srFd);
exit(0);
}
if(listen(srFd,1)<0)
{
printf(“\n Listen Error”);
close(CIFD);
exit(0);
}
printf(“\n Server is ready to listen\n”);
len=sizeof(client);
CIFD=accept(srFd,(structsockaddr *)&client,&len);
if(CIFD<0)
{
printf(“\n Accept error”);
close(CIFD);
close(srFd);
exit(0);
}
printf(“Client gets connected\n”);
bzero(&buf,sizeof(buf));
if((n=recv(CIFD,&buf,SIZE,0))<0)
{
printf(“\n Receive Error in Server\n”);
close(srFd);
close(CIFD);
exit(0);
}
buf[n-1]=NULL;
printf(“\n File name %s”,buf);
if((n=send(CIFD,buf,strlen(buf),0))<0)
{
printf(“\n Error”);
close(CIFD);
exit(0);
}
close(srFd);
close(CIFD);
exit(0);
}
Client
#include<stdio.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<string.h>
#define SIZE 256
int main()
{
int CIFD;
structsockaddr_in client;
charbuf[SIZE];
int n;
if((CIFD=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf(“\n Client Socket Error”);
exit(0);
}
bzero(&client,sizeof(client));
client.sin_family=AF_INET;
client.sin_port=htons(2200);
inet_pton(AF_INET,”127.0.0.1″,&client.sin_addr);
if(connect(CIFD,(structsockaddr *)&client,sizeof(client))<0)
{
printf(“\n connection failed”);
close(CIFD);
exit(0);
}
printf(“\n connection enabled\n”);
printf(“\n Enter source file\n”);
bzero(&buf,sizeof(buf));
if(fgets(buf,SIZE,stdin)==NULL)
{
printf(“\n Failed to get source file name in client\n”);
close(CIFD);
exit(0);
}
if(send(CIFD,buf,strlen(buf),0)<0)
{
printf(“\n Send Error\n”);
close(CIFD);
exit(0);
}
printf(“\n Client message sent\n”);
bzero(&buf,sizeof(buf));
if((n=recv(CIFD,buf,SIZE,0))<0)
{
printf(“\n File name receiver error in client from server\n”);
close(CIFD);
exit(0);
}
printf(“\n Destination file name from server %s”,buf);
buf[n]=NULL;
close(CIFD);
exit(0);
}
OUTPUT
Client[student@localhost ~]$ ./a.out
Connection Enabled
Enter Source File
Tps.c
Client Message Sent
Destination Filename From Server tps.c
Server[student@localhost ~]$ ./a.out
Server is ready to listen
Client get connected
Tps.c
No comments:
Post a Comment