| | | | Browse by category |
Article ID: 916
Last updated: 02 Feb, 2008
Problem
How can I get the port number from an RWSocket?
Cause
Action
Not all RWSockets have port numbers associated with them: Only sockets constructed using an RWInetAddr have a port. An RWSocketListener can be constructed without knowing the local port, so it will serve as an example of how to recover the port information from an RWSocket:
#include <rw/toolpro/sockport.h>
#include <rw/toolpro/inetaddr.h>
How can I get the port number from an RWSocket?
Cause
Action
Not all RWSockets have port numbers associated with them: Only sockets constructed using an RWInetAddr have a port. An RWSocketListener can be constructed without knowing the local port, so it will serve as an example of how to recover the port information from an RWSocket:
#include
#include
int main() {
RWInetAddr local;
cout << 'initial local port #:' << local.port() << endl;// ** Note 1 **
RWSocketListener listen(local);
if( RWInetAddr::is(listen.socket().getsockname()))//** Note 2 **
{
RWInetAddr check = RWInetAddr::as(listen.socket().getsockname()); // ** Note 3 **
cout << 'RWInetAddr port # is' << check.port() << endl; // ** Note 4 **
}
else {
cout << 'The RWSockAddr was no RWInetAddr!' << endl;
}
cout << 'final local port #:' << local.port() << endl; // ** Note 5 **
return 0;
}
NOTES:
- Default InetAddr has no port associated with it (yet), so this line will print a zero.
- getsockname returns an RWSockAddr. Using the static method RWInetAddr::is(const RWSockAddr&), we can be sure we have an RWInetAddr. (In real code, this might not be as obvious as it is here!)
- RWInetAddr::as(const RWSockAddr&) returns an RWInetAddr if it can legally do so.
- From an RWInetAddr, we can discover the port number. This one should not be zero.
- Just as a final check, note that the original RWInetAddr was not altered: RWSocketListener makes its own copy.
This article was:
Helpful |
Not helpful
Report an issue
Article ID: 916
Last updated: 02 Feb, 2008
Revision: 1
Views: 2920
Posted: 11 Dec, 1998 by
Dean J.
Updated: 02 Feb, 2008 by
Dean J.
Also listed in
Others in this category
Powered by KBPublisher (Knowledge base software)