套接字程序文件传输

时间:2013-04-02 09:30:29

标签: c linux sockets

当我使用以下代码传输二进制文件时,只传输了一半的文件。当我使用具有相同二进制文件的环回地址检查相同的代码时,它正常工作,即整个文件被传输。

以下代码或我的网络是否有任何问题?

Client.c:

#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/wait.h>
#include<sys/socket.h>
#include<signal.h>
#include<ctype.h>          
#include<arpa/inet.h>
#include<netdb.h>
#define PORT 20000
#define LENGTH 512

void error(const char *msg)
{
    perror(msg);
    exit(1);
}

int main(int argc, char *argv[])
{
    /* Variable Definition */
    int sockfd, nsockfd;
    char revbuf[LENGTH]; 
    struct sockaddr_in remote_addr;

    /* Get the Socket file descriptor */
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor! (errno = %d)\n",errno);
        exit(1);
    }

    /* Fill the socket address struct */
    remote_addr.sin_family = AF_INET; 
    remote_addr.sin_port = htons(PORT); 
    inet_pton(AF_INET, "192.168.103.190", &remote_addr.sin_addr); 
    //inet_pton(AF_INET, "192.168.103.179", &remote_addr.sin_addr);
    bzero(&(remote_addr.sin_zero), 8);

    /* Try to connect the remote */
    if (connect(sockfd, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr)) == -1) {
        fprintf(stderr, "ERROR: Failed to connect to the host! (errno = %d)\n",errno);
        exit(1);
    }
    else
        printf("[Client] Connected to server at port %d...ok!\n", PORT);

    /*send to server*/
    char* fs_name = "/usr/local/context.2848";
    char sdbuf[LENGTH]; 
    printf("[Client] Sending %s to the Server... ", fs_name);
    FILE *fs = fopen(fs_name, "r");
    if(fs == NULL) {
        printf("ERROR: File %s not found.\n", fs_name);
        exit(1);
    }
    bzero(sdbuf, LENGTH); 
    int fs_block_sz,i=0; 
    while((fs_block_sz = fread(sdbuf, sizeof(char), LENGTH, fs)) > 0) {
        printf("Data Sent %d = %d\n",i,fs_block_sz);
        if(send(sockfd, sdbuf, fs_block_sz, 0) < 0) {
            fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n", fs_name,     errno);
            exit(1);
        }
        bzero(sdbuf, LENGTH);
        i++;
    }
    close (sockfd);
    printf("[Client] Connection lost.\n");
    return (0);
}

Server.c

#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/wait.h>
#include<sys/socket.h>
#include<signal.h>
#include<ctype.h>          
#include<arpa/inet.h>
#include<netdb.h>
#define PORT 20000 
#define BACKLOG 5
#define LENGTH 512 

void error(const char *msg)
{
    perror(msg);
    exit(1);
}

int main ()
{
    /* Defining Variables */
    int sockfd, nsockfd; 
    int num;
    int sin_size; 
    struct sockaddr_in addr_local; /* client addr */
    struct sockaddr_in addr_remote; /* server addr */
    char revbuf[LENGTH]; // Receiver buffer

    /* Get the Socket file descriptor */
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ) {
        fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor. (errno = %d)\n", errno);
        exit(1);
    }
    else 
        printf("[Server] Obtaining socket descriptor successfully.\n");

    /* Fill the client socket address struct */
    addr_local.sin_family = AF_INET; // Protocol Family
    addr_local.sin_port = htons(PORT); // Port number
    addr_local.sin_addr.s_addr = INADDR_ANY; // AutoFill local address
    bzero(&(addr_local.sin_zero), 8); // Flush the rest of struct

    /* Bind a special Port */
    if( bind(sockfd, (struct sockaddr*)&addr_local, sizeof(struct sockaddr)) == -1 ) {
        fprintf(stderr, "ERROR: Failed to bind Port. (errno = %d)\n", errno);
        exit(1);
    }
    else 
        printf("[Server] Binded tcp port %d in addr 127.0.0.1 sucessfully.\n",PORT);

    /* Listen remote connect/calling */
    if(listen(sockfd,BACKLOG) == -1) {
        fprintf(stderr, "ERROR: Failed to listen Port. (errno = %d)\n", errno);
        exit(1);
    }
    else
        printf ("[Server] Listening the port %d successfully.\n", PORT);

    int success = 0;
    while(success == 0)
    {
        sin_size = sizeof(struct sockaddr_in);

        /* Wait a connection, and obtain a new socket file despriptor for single connection */
        if ((nsockfd = accept(sockfd, (struct sockaddr *)&addr_remote, &sin_size)) == -1) {
            fprintf(stderr, "ERROR: Obtaining new Socket Despcritor. (errno = %d)\n", errno);
            exit(1);
        }
        else 
            printf("[Server] Server has got connected from %s.\n", inet_ntoa(addr_remote.sin_addr));
        /*Receive File from Client */
        char* fr_name = "/home/ankita/context.2848";
        FILE *fr = fopen(fr_name, "a");
        if(fr == NULL)
            printf("File %s Cannot be opened file on server.\n", fr_name);
        else {
            bzero(revbuf, LENGTH); 
            int fr_block_sz = 0;
            int i=0;
            while((fr_block_sz = recv(nsockfd, revbuf, LENGTH, 0)) > 0) {
                printf("Data Received %d = %d\n",i,fr_block_sz);
                int write_sz = fwrite(revbuf, sizeof(char), fr_block_sz, fr);
                if(write_sz < fr_block_sz)
                    error("File write failed on server.\n");
                bzero(revbuf, LENGTH);
                i++;
            }
            if(fr_block_sz < 0) {
                if (errno == EAGAIN)
                    printf("recv() timed out.\n");
                else {
                    fprintf(stderr, "recv() failed due to errno = %d\n", errno);
                    exit(1);
                }
            }
            printf("Ok received from client!\n");
            fclose(fr); 
        }
        success = 1;
    }
}   

3 个答案:

答案 0 :(得分:2)

发送不保证发送您要求的所有数据,它可能发送更少。您只检查发送时的错误,而不是发送的数据少于预期。 recv是一样的。因此,在实现的两个方面都存在相同的错误。你可能会为localhost侥幸逃脱,因为内核可以很聪明地将数据传输给自己。

答案 1 :(得分:0)

您应该查看recv循环中的if语句。首先,条件是

fr_block_sz == 0

永远不会发生,因为while循环检查&gt;其次,如果recv没有得到512字节,我不明白你为什么要打破。 (如果你真的需要它,你应该把它改为LENGTH。)你应该继续recv直到返回代码为0(在这种情况下套接字关闭)或否定(在这种情况下你有一个错误)。使用流套接字时,接收方不一定会收到发送方为每个IO请求发送的相同数据量。

答案 2 :(得分:0)

正如Joe在回​​答中指出的,send并不总是发送所有数据。您可以按this guideline正确使用send

只有当您尝试发送到另一台计算机上的服务器时才会注意到此行为,因为您正在点击MTU(即物理介质可以处理的最大数据大小)。如果我没记错的话,使用环回地址时,MTU为8K - 16K。我猜你的二进制文件大小恰好小于这个,这就是为什么你在尝试发送到真实服务器之后才观察到这一点。然而,以太网介质的MTU是1500字节,相对低得多。