我有这个代码
Server:
//"sock" has already been created with no problem and binding as well
void Connection::bind_connection(int port){
cout << "Port " << port << endl;
server.sin_family = AF_INET ;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(port);
/* Bind socket to address */
struct sockaddr *serverptr = ( struct sockaddr *) &server;
if ( bind ( sock , serverptr , sizeof(server) ) < 0) {
perror("Binding error"); exit(BE);
}
cout << "Server binding completed!" << endl;
}
struct sockaddr_in client ;
socklen_t clientlen ;
struct sockaddr * clientptr =( struct sockaddr *) &client ;
if ( listen (sock , MAX_CONNECTIONS) < 0) {perror("listening error"); exit(LE);}
cout << "Listening for connections to port " << port << endl;
while (1) {
/* accept connection */
if (( newsock = accept ( sock , clientptr , &clientlen ) ) < 0) {
perror("Accepting error"); cout << "Errno = " << errno << endl; exit(AE);
}
//Code
....
}
和
Client:
//struct sockaddr_in server; <--- declared as data member of class "Connection"
//"sock" has already been created with no problem
void Connection::do_connect(){
struct sockaddr *serverptr = ( struct sockaddr *) &server;
if ( connect ( sock , serverptr , sizeof (server) ) < 0)
perror("client connect"); exit(CE);
cout << "Client connecting to the server" << endl;
}
我收到了上面的消息。大部分代码是从类(class)幻灯片中复制的,但根据我的需要进行了修改。谷歌搜索问题似乎我在系统调用中给出了错误的大小。知道问题到底出在哪里吗?提前致谢。
最佳答案
那些行总是退出:
if ( connect ( sock , serverptr , sizeof (server) ) < 0)
perror("client connect"); exit(CE);
您可能会开始考虑使用不同的缩进方案。通常每行不使用超过一个语句。
对于上面的代码,indent
之类的工具会将其格式化为:
if (connect (sock, serverptr, sizeof (server)) < 0)
perror("client connect");
exit(CE);
这种格式使编程错误很明显。
关于c++ - 连接错误 : Invalid argument at sockets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24577950/