我正在为一个简单的工作项目做准备,并尝试熟悉Unix开发环境下套接字编程的基础知识。目前,我已经设置了一些基本的服务器端代码和客户端代码来进行通信。目前,我的客户端代码成功连接到服务器端代码,并且服务器端代码发送了一个测试消息,然后两者都退出了。完美!这正是我想要实现的。现在,我正在尝试使用用于获取有关两个环境(服务器和客户端)信息的函数。我想获取客户端的本地IP地址和动态分配的TCP端口。我找到的执行此操作的函数是getsockname()
...
//setup the socket
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
{
perror("client: socket");
continue;
}
//Retrieve the locally-bound name of the specified socket and store it in the sockaddr structure
sa_len = sizeof(sa);
getsock_check = getsockname(sockfd,(struct sockaddr *)&sa,(socklen_t *)&sa_len) ;
if (getsock_check== -1) {
perror("getsockname");
exit(1);
}
printf("Local IP address is: %s\n", inet_ntoa(sa.sin_addr));
printf("Local port is: %d\n", (int) ntohs(sa.sin_port));
但是输出总是零...
Local IP address is: 0.0.0.0
Local port is: 0
有没有人看到我可能做错或肯定做错的事情?
非常感谢您提前提供的所有帮助!