关于通过TCP/IP方式获得客户端对外ip和端口的问题

jinsehongfeng 2011-12-01 11:03:04
大家好,
我在公网上以端口映射的方式架了一个服务器,采用TCP/IP方式接收数据

现在有个问题是,我从收到的数据包sockaddr_in里解析出来的IP地址怎么是服务器网关对外的公网地址,而不是客户端的公网地址,有了解这个的大哥请帮个忙解答一下,谢谢了

我怎么能得到客户端对外的公网地址呢?

难道服务器只能得到最后一个网关转发的地址,不能得到对方的公网地址吗?

请各位知道的大侠们一定给帮个忙啊,不胜感激。。。
...全文
181 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
jinsehongfeng 2011-12-09
  • 打赏
  • 举报
回复
经过测试的确如楼上分析这样,是我搞错了,哎提供商差死人啊
TygerZH 2011-12-09
  • 打赏
  • 举报
回复
不应该的,映射出去得到的地址就应该是对方公网地址,好好检查下你的IP和网络提供商给你的Ip一样不,如果你用的不是电信或联通的网的话,有可能是提供商租用他们的,然后分给你的,它会跟据你访问的服务器是哪种网络来判断你对外用对应的哪种网,所以你在网上查到的IP大多数是电信的IP,而你服务器得到的IP有可能是联通的IP,因为你服务器是架在联通机房的。

跨网通讯费用是很高的,网络提供商为了避免这个,才会租用多种网络,跟据情况分配的
赵4老师 2011-12-02
  • 打赏
  • 举报
回复
inet_ntoa
The Windows Sockets inet_ntoa function converts an (Ipv4) Internet network address into a string in Internet standard dotted format.

char FAR * inet_ntoa (
struct in_addr in
);

Parameters
in
[in] A structure that represents an Internet host address.
Remarks
The inet_ntoa function takes an Internet address structure specified by the in parameter and returns an ASCII string representing the address in ".'' (dot) notation as in "a.b.c.d''. The string returned by inet_ntoa resides in memory that is allocated by Windows Sockets. The application should not make any assumptions about the way in which the memory is allocated. The data is guaranteed to be valid until the next Windows Sockets function call within the same thread, but no longer. Therefore, the data should be copied before another Windows Sockets call is made.
Return Values
If no error occurs, inet_ntoa returns a char pointer to a static buffer containing the text address in standard ".'' notation. Otherwise, it returns NULL.

jinsehongfeng 2011-12-02
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 seucs 的回复:]

accept函数的第二个参数就是用来获取对端的IP地址的,还有
int getpeername(int fd, struct sockaddr *name, socklen_t *namelen);
这个函数也可以获取fd的IP地址
[/Quote]
我就是用的第二个参数得到的ip和port,但是得到的这个ip是服务器公网的地址,而不是客户端公网地址,因为服务器是映射到外网的,得到的最后一个包应该是服务器网关发过来的,我得到的是网关对应的公网地址
jinsehongfeng 2011-12-02
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 et214721856 的回复:]

tcp连接的话,你服务端不是得accept来接受连接的么?
accept的第二个参数不就是客户端的地址了。

recvfrom也可以
[/Quote]

我就是用的第二个参数得到的ip和port,但是得到的这个ip是服务器公网的地址,而不是客户端公网地址,因为服务器是映射到外网的,得到的最后一个包应该是服务器网关发过来的,我得到的是网关对应的公网地址
seucs 2011-12-02
  • 打赏
  • 举报
回复
accept函数的第二个参数就是用来获取对端的IP地址的,还有
int getpeername(int fd, struct sockaddr *name, socklen_t *namelen);
这个函数也可以获取fd的IP地址
周晓荣 2011-12-02
  • 打赏
  • 举报
回复
tcp连接的话,你服务端不是得accept来接受连接的么?
accept的第二个参数不就是客户端的地址了。

recvfrom也可以
bEst_02 2011-12-02
  • 打赏
  • 举报
回复
当然可以获取对方的公网IP了,recvfrom可以获取对端IP

3,882

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧