如何获取客户端程序的本地TCP端口和IP地址?

Bea*_*red 3 c unix sockets

我正准备一个简单的工作项目,并试图熟悉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));
Run Code Online (Sandbox Code Playgroud)

但输出始终为零......

Local IP address is: 0.0.0.0
Local port is: 0
Run Code Online (Sandbox Code Playgroud)

有没有人看到我可能会做的事情或肯定做错了?

非常感谢您的帮助!

小智 7

从你的代码看起来你没有做connectaccept在套接字上.在您完成此操作之前,您获得的数据getsockname是未定义的.