我的 getaddrinfo 调用出现分段错误,无法弄清楚原因。它发生在我的服务器和客户端上。一些代码(服务器端)是 -
class TcpServer {
public:
TcpServer(int);
~TcpServer();
void launchServer();
void communicate();
private:
const char* port;
int fd;
int comm_fd;
};
在 tcpserver.cpp-
void TcpServer::launchServer() {
int status;
struct addrinfo hints;
struct addrinfo *servinfo; //will point to the results
//store the connecting address and size
struct sockaddr_storage their_addr;
socklen_t their_addr_size;
//socket infoS
memset(&hints, 0, sizeof hints); //make sure the struct is empty
hints.ai_family = AF_INET; //local address
hints.ai_socktype = SOCK_STREAM; //tcp
hints.ai_flags = AI_PASSIVE; //use local-host address
//get server info, put into servinfo
if ((status = getaddrinfo("127.0.0.1", port, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(1);
}
主要是
TcpServer server(4950);
server.launchServer();
int
传递给构造函数的值被强制转换为一个forconst char*
端口。
当我运行 gdb 时,它给了我一个回溯 -
#0 0xb7dca737 in getaddrinfo (name=0x8054824 "127.0.0.1",
service=0x1356 <Address 0x1356 out of bounds>, hints=0xbffff20c,
pai=0xbffff234) at ../sysdeps/posix/getaddrinfo.c:2080
#1 0x08050f79 in TcpServer::launchServer (this=0xbffff304) at tcpserver.cpp:25
#2 0x0804eae9 in main (argc=1, args=0xbffff3f4) at mainserver.cpp:47
所以“地址 0x1356 越界”让我相信端口有问题,但我不知道可能出了什么问题。如果有人能指出错误,我将不胜感激。谢谢你的帮助。