我想做的是连接到远程服务器,从本地机器上的文件中读取内容并将其发送到服务器。然后捕获服务器响应并保存。我将 GET 命令放在一个文本文件中,并尝试获得相同的结果。这是代码的一部分。我使用套接字和 C 来做这件事。
if ( inet_pton(AF_INET,ip, &(nc_args->destaddr.sin_addr.s_addr)) <= 0 )
printf("\n\t\t inet_pton error");
if (connect(sockfd, (struct sockaddr *) &nc_args->destaddr, sizeof(&nc_args->destaddr)) < 0)
{
printf("\n\t\t Connection error");
exit(1);
}
puts("\n\t\t Connection successful to ...");
// file parameter is taken from command line and passéd to this function
fp = fopen(file,"rb");
if ( fp == NULL)
{
printf("\n\t\t File not found");
exit(3);
}
else
{
printf("\n\t\t Found file %s\n", file);
fseek(fp, 0, SEEK_END);
file_size = ftell(fp);
rewind(fp);
//allocate memory to the buffer dynamically
buffer = (char*) malloc (sizeof(char)*file_size);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
for (i=0 ; i<sizeof(buffer); i++)
{
printf("\n\t\t %s", buffer);
}
printf("\n\t\t File contains %ld bytes!\n", file_size);
printf("\n\t\t Sending the file now");
}
while (1)
{
bytes_read = fread(buffer,1, file_size, fp);
printf("\n\t\t The bytes read is %zd", bytes_read);
if (bytes_read == 0) // We're done reading from the file
{
printf("\n\t\t The bytes read is %zd", bytes_read);
break;
}
if (bytes_read < 0)
{
printf("\n\t\t ERROR reading from file");
}
void *p = buffer;
while (bytes_read > 0)
{
ssize_t bytes_written = send(sockfd, buffer, bytes_read,0);
if (bytes_written <= 0)
{
printf("\n\t\t ERROR writing to socket\n");
}
bytes_read -= bytes_written;
p += bytes_written;
printf("\n\t\t Bytes %zd written", bytes_written);
}
}
printf("\n\n\t\t Sending complete.");
这里发生的是我收到消息“连接成功”,然后显示“正在发送文件”,然后程序意外退出。如果我回显$?我得到 141 作为退出代码。我正在尝试从我的服务器连接到工作中的另一台服务器并获得结果。这两个可以正确通信,我可以从命令行运行 GET 命令而不会出现问题。它只是不能从代码中工作。有人可以让我知道可能是什么问题吗?