Linux Socket Programming,
File transfer application using Sockets
Code for Client
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<fcntl.h>
int main(int argc,int *argv[])
{
char buffer[100];
int fd=open("abc.txt",O_RDONLY);
read(fd,buffer,100);
int sock_id=socket(AF_INET,SOCK_STREAM,0);
if(sock_id<0)
{
printf("Error in getting socket\n");
return 0;
}
struct sockaddr_in clientstruct;
clientstruct.sin_family=AF_INET;
clientstruct.sin_addr.s_addr=inet_addr("127.0.0.1");
clientstruct.sin_port=10125;
int ret=connect(sock_id,(struct sockaddr *)&clientstruct,sizeof(clientstruct));
write(sock_id,buffer,100);
close(sock_id);
return 0;
}
Code for Server
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<fcntl.h>
int main()
{
char buffer[100];
int session_id;
int server_id=socket(AF_INET,SOCK_STREAM,0);
if(server_id<0)
{
printf("Error in getting socket\n");
return 0;
}
struct sockaddr_in serverstruct,clientstruct;
serverstruct.sin_family=AF_INET;
serverstruct.sin_addr.s_addr=inet_addr("127.0.0.1");
serverstruct.sin_port=10125;
int i=bind(server_id,(struct sockaddr*)&serverstruct,sizeof(serverstruct));
if(i<0)
{
printf("Error in bind\n");
return 0;
}
i=listen(server_id,10);
if(i<0)
{
printf("Error in listening\n");
return 0;
}
int client_len=sizeof(serverstruct);
while(1)
{
int fd=open("target.txt",O_WRONLY);
if(fd<0)
{
printf("file cant be iopened\n");
}
printf("Waiting for the client\n");
session_id=accept(server_id,(struct sockaddr*)&serverstruct,&client_len);
read(session_id,buffer,sizeof(buffer));
write(fd,buffer,100);
printf("From CLIENT:%s\n",buffer);
close(fd);
close(session_id);
}
close(server_id);
return 0;
}
No comments:
Post a Comment