【发布时间】:2011-01-30 13:52:28
【问题描述】:
我正在为一个简单的工作项目做准备,并试图让自己熟悉 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
有没有人看到我可能做错或肯定做错了什么?
非常感谢您的所有帮助!
【问题讨论】:
-
也许这会有所帮助:serverfault.com/questions/447044