我正在尝试创建服务器/客户端通信,并且它使用errno 88来解决连接函数问题。我检查了socketfd是否有效(因为这个错误意味着我试图在非服务器上进行套接字操作)套接字对象)。
int main (int argc, char *argv[])
{
// Validity check
if (argc != VALID_ARG_NUM) {
std::cout << INVALID_ARG;
return 0; // todo - return 0 is correct??
}
int port;
struct sockaddr_in server_address;
// server_address initialization.
server_address.sin_family = AF_INET;
server_address.sin_port = htons((uint32_t)atof(argv[3]));
server_address.sin_addr.s_addr = inet_addr(argv[2]);
memset(&(server_address.sin_zero), '\0', sizeof(server_address));
// Create the client socket.
if (sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0) {
std::cout << "ERROR: socket " << errno << "." << std::endl;
exit(1);
}
// Connect to server.
if (connect(sockfd, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
std::cout << "ERROR: connect " << errno << "." << std::endl;
std::cout << CON_FAIL;
close(sockfd);
exit(1);
}
.......
谢谢。
答案 0 :(得分:1)
我认为这部分导致缓冲区溢出:
memset(&(server_address.sin_zero), '\0', sizeof(server_address));
在编写某些字段之前,你应该将整个结构归零:
struct sockaddr_in server_address;
// server_address initialization.
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
答案 1 :(得分:1)
声明的优先顺序
sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0
是
sockfd = ((socket(AF_INET, SOCK_STREAM, 0)) < 0)
因此您分配了一个布尔值,它被隐式转换为整数(或sockfd
所具有的任何类型)。你可能想要的是
(sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0
答案 2 :(得分:0)
管道损坏通常意味着远程对等关闭连接。你确定你的服务器代码没问题吗?也许它只是做这样的事情?
int main()
{
...
listen();
accept();
return 0;//procees exits and therefore brakes connection
}