这是通过 C 语言中的套接字进行通信的服务器端代码。我遇到了分段错误,但我可以理解为什么会发生。这是代码:
int server_sd ; // The socket descriptor
server_sd = socket(PF_INET, SOCK_STREAM, 0);
if (server_sd == -1) {
cout << "Could not create socket";
} else {
cout << "Socket created" << endl;
}
struct protoent *proto;
proto = getprotobyname("http");
struct sockaddr_in addr;
cout << "sockaddr is created" << endl;
memset((void *)&addr, 0, sizeof(addr));
cout << "memset is done";
addr.sin_family = AF_INET;
addr.sin_port = proto->p_proto;
addr.sin_addr.s_addr = INADDR_ANY; /* any interface */
cout << "Binding server now:" << endl;
if( bind(server_sd,(sockaddr *)&addr , sizeof(addr)) < 0) {
//print the error message
perror("bind failed. Error");
} else {
cout << "bind done" << endl;
}
listen(server_sd, 10); /* make into listener with 10 slots */
cout << "Waiting for incoming connections..." << endl;
我正在使用 cout 语句来跟踪问题发生的位置。这是程序的输出:
Socket created
sockaddr is created
Segmentation fault (core dumped)
你可能在这里崩溃了:
addr.sin_port = proto->p_proto;
proto
可能为空。
您看不到打印memset is done
的原因是那里没有任何<< endl
,cout
将缓冲数据,直到看到换行符或显式刷新。