简体   繁体   English

使用套接字编程的FTP

[英]FTP using Socket Progarmming

So I was trying to implement a basic file read program using socket programming. 因此,我试图使用套接字编程来实现基本的文件读取程序。 I am using TCP to connect to a server. 我正在使用TCP连接到服务器。 The client sends the name of file and server reads it and sends its contents back to the client. 客户端发送文件名,服务器读取文件名并将其内容发送回客户端。 The problem is I am getting an error in server program as: 问题是我在服务器程序中遇到错误,如下所示:

Segmentation fault: 11 细分错误:11

Here are the programs: 以下是程序:

Server.c 服务器

#include<stdio.h>
#include<unistd.h>
#include<netdb.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<strings.h>
#include <netinet/in.h>
int main()
{
    int s=socket(AF_INET,SOCK_STREAM,0);

    struct sockaddr_in saddr;
    saddr.sin_family=AF_INET;
    saddr.sin_port=htons(1999);
    saddr.sin_addr.s_addr=htonl(INADDR_ANY);

    socklen_t slen=sizeof(saddr);

    bind(s,(struct sockaddr*)&saddr,slen);
    printf("Server Running..\n");

    listen(s,5);

    struct sockaddr_in caddr;
    socklen_t clen=sizeof(caddr);
    int ad=accept(s,(struct sockaddr*)&caddr,&clen);
    printf("Client Connected\n");

    FILE *fp;
    char buff[1024],file[1000];
    while(1)
    {
    bzero(&buff,sizeof(buff));
    bzero(&file,sizeof(file));

    recv(ad,buff,sizeof(buff),0);
    fp=fopen(buff,"r");
    fread(file,sizeof(file),1,fp);
    send(ad,file,sizeof(file),0);
    }
    close(s);
}

Client.c 客户端

#include<stdio.h>
#include<unistd.h>
#include<netdb.h>
#include<sys/types.h>
#include<sys/socket.h>
#include <netinet/in.h>
#include<strings.h>
int main()
{
    int s=socket(AF_INET,SOCK_STREAM,0);

    struct sockaddr_in saddr;
    saddr.sin_family=AF_INET;
    saddr.sin_port=htons(1999);
    saddr.sin_addr.s_addr=inet_addr("127.0.0.1");

    socklen_t slen=sizeof(saddr);

    connect(s,(struct sockaddr*)&saddr,slen);
    char b[1024],f[1000];

    while(1)
    {
        bzero(&b,sizeof(b));
        bzero(&f,sizeof(f));
        printf("Enter the name of file : ");
        fgets(b,sizeof(b),stdin);

        send(s,b,sizeof(b),0);
        recv(s,f,sizeof(f),0);

        printf("The contents are : %s", f);

    }
}

Can anyone tell me the possible error I am doing here? 谁能告诉我我在这里可能发生的错误?

You never check the result of fopen(). 您永远不会检查fopen().的结果fopen(). It is probably failing because the client is using fgets() and that leaves the newline char in the input buffer. 可能由于客户fgets()在使用fgets()而失败,这将换行符留在输入缓冲区中。 So the filename has an extra \\n at the end. 因此,文件名末尾有一个\\n Also, you never close the file. 另外,您永远不会关闭文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM