持续侦听端口并将数据转储到文本文件

时间:2016-10-18 20:49:11

标签: c linux sockets ubuntu

我有以下代码通过端口中的套接字监听调用,但是我错过了创建文本文件然后将数据转储到其中的函数,因为稍后我会解析它并显示它在其他地方。

/*
    Simple udp server
*/
#include<stdio.h> //printf
#include<string.h> //memset
#include <stdlib.h> //exit(0);
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUFLEN 512  //Max length of buffer
#define PORT 8888   //The port on which to listen for incoming data

void die(char *s)
{
    perror(s);
    exit(1);
}

int main(void)
{
    struct sockaddr_in si_me, si_other;

    int s, i, slen = sizeof(si_other) , recv_len;
    char buf[BUFLEN];

    //create a UDP socket
    if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
    {
        die("socket");
    }

    // zero out the structure
    memset((char *) &si_me, 0, sizeof(si_me));

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

    //bind socket to port
    if (bind(s, (struct sockaddr*)&si_me, sizeof(si_me) ) == -1)
    {
        die("bind");
    }

    //keep listening for data
    while(1)
    {
        printf("Waiting for data...");
        fflush(stdout);

        //try to receive some data, this is a blocking call
        if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1)
        {
            die("recvfrom()");
        }

        //print details of the client/peer and the data received
        printf("Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
        printf("Data: %s\n" , buf);

        //now reply the client with the same data
        if (sendto(s, buf, recv_len, 0, (struct sockaddr*) &si_other, slen) == -1)
        {
            die("sendto()");
        }
    }

    close(s);
    return 0;
}

2 个答案:

答案 0 :(得分:0)

查看函数fopen()fwrite()和(最后但并非最不重要的)fclose()来解决该问题。它们应该为您提供将数据写入文件所需的基础知识。

答案 1 :(得分:0)

你几乎就在那里,但只是对如何写一个文件进行一些研究就足够了。

while(1)循环中,只需在代码中添加以下代码(请参阅代码注释):

...

//print details of the client/peer and the data received
printf("Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
printf("Data: %s\n" , buf);

/* ----- Begin: write to file ------------------------------------- */
FILE *fp = fopen("/tmp/received_data", "a"); // open in append mode
if (NULL == fp) {
    // handle problem here
}

if (fwrite(buf, sizeof(char), recv_len, fp) != recv_len) { // write to file
    // handle problem here
}

if (fclose(fp) != 0) { // flush and close the file descriptor
    // handle problem here
}
/* ----- End: write to file ------------------------------------- */    

//now reply the client with the same data
if (sendto(s, buf, recv_len, 0, (struct sockaddr*) &si_other, slen) == -1)
{
    die("sendto()");
}

...

现在,每当您从客户端收到数据时,它都会被写入(*)received_data中的文件/tmp/。这意味着文件的内容将会增长,直到您停止程序。如果您想知道它是如何工作的以及如何处理可能的错误,您应该查看Striezel答案中的链接。

(*):由于a

中的fopen()选项而追加