简体   繁体   English

消息UDP中的文件名

[英]filename from the message UDP

I have simple program in C (client,server) UDP. 我在C(客户端,服务器)UDP中有简单的程序。 Client send message with filename or source to text file and server open this file and shows first line. 客户端将带有文件名或源的消息发送到文本文件,服务器打开该文件并显示第一行。 how to format buf so that the file can be opened correctly? 如何格式化buf,以便可以正确打开文件?

CLIENT 客户

bzero(buf,BUF_SIZE);
fgets(buf, BUF_SIZE-1, stdin);
n = sendto(sfd, buf, strlen(buf), 0, rp->ai_addr, rp->ai_addrlen);

SERVER 服务器

peer_addr_len = sizeof(struct sockaddr_storage);
n = recvfrom(sfd, buf, BUF_SIZE, 0,
            (struct sockaddr *) &peer_addr, &peer_addr_len);
FILE *fp;
char buff[255];
fp = fopen(buf,"r");

fgets(buff, 255, (FILE *)fp);
printf("First line: %s \n", buff);

fclose(fp);

Function fopen needs a nul-terminated string, so you have to make sure the file name from the received buffer is nul-terminated before passing it to fopen . 函数fopen需要一个以nul终止的字符串,因此在将其传递给fopen之前,必须确保来自接收缓冲区的文件名是以nul终止的。 With the implementation in your code snippets the file name may be followed by random data if you don't fill buf with '\\0' before calling recvfrom . 如果您在代码段中使用了该实现,则在调用recvfrom之前未在buf填充'\\0' ,文件名后可能会带有随机数据。

There are different options fulfill this requirement. 有不同的选项可以满足此要求。

Send the file name including the '\\0' : 发送包含 '\\0'的文件名:

/* use strlen(buf)+1 to include the terminating '\0' */
n = sendto(sfd, buf, strlen(buf)+1, 0, rp->ai_addr, rp->ai_addrlen);

In this case the receiver will get a buffer including the '\\0' . 在这种情况下,接收器将获得一个包含'\\0'的缓冲区。 But it might be good to check that the received string is actually terminated with '\\0' . 但是最好检查接收到的字符串是否实际上以'\\0'结尾。

Or append a '\\0' after receiving the string: 或在接收到字符串后附加'\\0'

/* use BUF_SIZE-1 to reserve at least 1 byte for '\0' */
n = recvfrom(sfd, buf, BUF_SIZE-1, 0,
        (struct sockaddr *) &peer_addr, &peer_addr_len);
if(n >= 0) {
    buf[n] = '\0';
}

Adding both modifications will make the program more robust. 添加这两个修改将使程序更强大。

In real code you should add error handling for all functions that may indicate an error with their return value. 在真实代码中,您应该为所有可能返回其错误的函数添加错误处理。

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

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