我制作了一个接受4个参数的客户端服务器程序。输入文件,输出文件,IP添加,端口号。但是我在尝试发送结束字符时遇到了分段错误。
server.cpp
/*
Authors: Manoj Parihar
Description: This program
*/
#include <unistd.h>
#include <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include <fstream>
#include <iomanip>
#include <netdb.h>
using namespace std;
int main (int argc, char *argv[])
{
int sockfd, numbytes;
char *buf_msg;
struct sockaddr_in server_add;
struct hostent *he;
char *end = "_EOF_";
ifstream fin;
if(argc != 5)
{
perror("Credentials Incomplete... Try again");
exit(1);
}
/*if ((he = gethostbyname(argv[1])) == NULL) {
cout << "Cannot get hostname" << endl;
exit(1);
}*/
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
cout << "Socket Failure..." << endl;
close(sockfd);
exit(1);
}
memset(&server_add, 0, sizeof(server_add));
server_add.sin_family = AF_INET;
server_add.sin_port = htons(atoi(argv[4]));
server_add.sin_addr.s_addr = inet_addr(argv[3]);
bzero(&server_add.sin_zero, 0);
cout << "Trying to connect\n";
if(connect(sockfd, (struct sockaddr *)&server_add, sizeof(struct sockaddr)) == -1)
{
perror("Connect Error");
close(sockfd);
exit(1);
}
else
cout << "sending filename...\n";
send(sockfd, argv[2], strlen(argv[2]), 0);
cout << "opening: " << argv[1] << strlen(argv[1]) << endl;
fin.open (argv[1], ios::in | ios::app | ios::binary);
if(!fin)
{
cout << "Client: Error opening file" << endl;
close(sockfd);
exit(1);
}
while(!(fin.eof()))
{
fin.read(buf_msg, 10);
cout << buf_msg << sizeof(buf_msg) << endl;
if(send(sockfd, buf_msg, sizeof(buf_msg), 0) == -1)
{
cout << "Failure Sending Msg";
close(sockfd);
exit(1);
}
}
cout << "Sending end character\n";
if(send(sockfd, "_EOF_", 5, 0) == -1)
{
cout << "Endpoint not sent\n";
close(sockfd);
exit(1);
}
//send(sockfd, -1, sizeof(int), 0)
cout << "Closing Client...";
close(sockfd);
return 0;
}
也是client.cpp
{{1}}
答案 0 :(得分:1)
分段错误意味着您的程序正在访问不适合访问的内存位置。这通常意味着您的指针未正确初始化或指向已返回操作系统的内存块。
在使用send_buff
和buf_msg
之前,您必须为其分配内存。
void * malloc(size_t size);
分配内存块
分配大小字节的内存块,返回指向块开头的指针。
类似的东西:
char *send_buff = malloc(1024);
char *buf_msg = malloc(1024);