读书人

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

发布时间: 2012-02-26 20:19:45 作者: rapoo

关于通过TCP/IP方式获得客户端对外ip和端口的问题
大家好,
我在公网上以端口映射的方式架了一个服务器,采用TCP/IP方式接收数据

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

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

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

请各位知道的大侠们一定给帮个忙啊,不胜感激。。。

[解决办法]
当然可以获取对方的公网IP了,recvfrom可以获取对端IP
[解决办法]
tcp连接的话,你服务端不是得accept来接受连接的么?
accept的第二个参数不就是客户端的地址了。

recvfrom也可以
[解决办法]
accept函数的第二个参数就是用来获取对端的IP地址的,还有
int getpeername(int fd, struct sockaddr *name, socklen_t *namelen);
这个函数也可以获取fd的IP地址
[解决办法]
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.


[解决办法]
不应该的,映射出去得到的地址就应该是对方公网地址,好好检查下你的IP和网络提供商给你的Ip一样不,如果你用的不是电信或联通的网的话,有可能是提供商租用他们的,然后分给你的,它会跟据你访问的服务器是哪种网络来判断你对外用对应的哪种网,所以你在网上查到的IP大多数是电信的IP,而你服务器得到的IP有可能是联通的IP,因为你服务器是架在联通机房的。

跨网通讯费用是很高的,网络提供商为了避免这个,才会租用多种网络,跟据情况分配的

读书人网 >C++

热点推荐