我怎样才能获得我的客户端程序的本地TCP端口和IP地址? [英] How can I obtain the local TCP port and IP Address of my client program?

查看:287
本文介绍了我怎样才能获得我的客户端程序的本地TCP端口和IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个简单的工作项目prepping,我试图用Socket编程在Unix开发环境的基本知识,熟悉自己。在这一点上,我有一些基本的服务器端code和客户端code设置通信。目前,我的客户code成功地连接到服务器,code和服务器code将它发送测试信息,那么这两个退出了。完善!这正是我想要完成的。现在我玩弄用来获取有关这两个环境(服务器和客户端)的信息功能。我想获取客户端的本地IP地址和动态分配的TCP端口。我发现这样做的作用是 getsockname() ...

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. 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. The function I've found to do this is 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!

推荐答案

从$ C $的外观c您没有做连接接受插座上。直到你已经这样做了,你从获取数据 getsockname 是不确定的。

From the looks of your code you are not doing connect or accept on the socket. Until you have done this the data you get from getsockname is undefined.

这篇关于我怎样才能获得我的客户端程序的本地TCP端口和IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆