简体   繁体   English

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

[英]How can I obtain the local TCP port and IP Address of my client program?

I'm prepping for a simple work project and am trying to familiarize myself with the basics of socket programming in a Unix dev environment. 我正准备一个简单的工作项目,并试图熟悉Unix开发环境中套接字编程的基础知识。 At this point, I have some basic server side code and client side code setup to communicate. 此时,我有一些基本的服务器端代码和客户端代码设置进行通信。 Currently, my client code successfully connects to the server code and the server code sends it a test message, then both quit out. 目前,我的客户端代码成功连接到服务器代码,服务器代码向它发送测试消息,然后退出。 Perfect! 完善! That's exactly what I wanted to accomplish. 这正是我想要完成的。 Now I'm playing around with the functions used to obtain info about the two environments (server and client). 现在,我正在使用用于获取有关两个环境(服务器和客户端)的信息的函数。 I'd like to obtain the local IP address and dynamically assigned TCP port of the client. 我想获取本地IP地址并动态分配客户端的TCP端口。 The function I've found to do this is getsockname() ... 我发现这样做的函数是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));

but the output is always zero... 但输出始终为零......

Local IP address is: 0.0.0.0
Local port is: 0

does anyone see anything I might be or am definitely doing wrong? 有没有人看到我可能会做的事情或肯定做错了?

Thanks so much in advance for all your help! 非常感谢您的帮助!

From the looks of your code you are not doing connect or accept on the socket. 从代码的外观来看,您没有在套接字上进行connectaccept Until you have done this the data you get from getsockname is undefined. 在您完成此操作之前,您从getsockname获取的数据是未定义的。

在你调用connect()之前,我认为你不能在这个上下文中有意义地调用getsockname - 内核不会将它绑定到特定端口,直到它需要(或被告知明确地这样做),并且本地地址是根据路由表选择的,因此也是目的地。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM