Discussions
Categories
Groups
Advertisement
Child Item
Home
Topics
Technology & Internet
Software & Web Development
Development
C++ IP long conversion problem
ikoonman
Hi
I am trying to extract the long local and peer IP address from a socket connected to a remote peer. Below is my test code:
[PHP]
struct sockaddr_in addr_local={0};
int nlSize = sizeof(struct sockaddr);
int lres = getsockname(s, (struct sockaddr *) &addr_local, &nlSize);
in_addr lin = addr_local.sin_addr;
struct sockaddr_in addr_peer={0};
int npSize = sizeof(struct sockaddr);
int nres = getpeername(s, (struct sockaddr *) &addr_peer, &npSize);
in_addr pin = addr_peer.sin_addr;
u_long lip = lin.S_un.S_addr;
u_long pip = pin.S_un.S_addr;
u_short lpo = ntohs(addr_local.sin_port);
u_short ppo = ntohs(addr_peer.sin_port);
dbgprint("lip=(%d) %d:%d, pip=(%d) %d:%d",
lin.S_un.S_addr,lip, lpo, pin.S_un.S_addr, pip, ppo);[/PHP]
My problem is that, if I surf to say Microsoft.com, and look at all the socket connections my local machine is making to the remote server, some of the long ip's returns negative numbers. I don't understand why this happen. I thought it's a conversion problem from S_un.S_addr to u_long, but if I just do a dbgprint on S_un.S_addr, the it also returns a "negative" or signed ip-long address.
Can somebody explain if and what I am doing wrong?
TIA
Find more posts tagged with
Quick Links
All Categories
Recent Posts
Activity
Unanswered
Groups
Best Of
Advertisement
Advertisement
Comments
Martyr
[php]
int s;
struct sockaddr_in server, addr;
socklen_t len;
// make a socket
s = socket(PF_INET, SOCK_STREAM, 0);
// connect to a server
server.sin_family = AF_INET;
inet_aton("63.161.169.137", &server.sin_addr);
server.sin_port = htons(80);
connect(s, (struct sockaddr*)&server, sizeof server);
// get the peer name
// we know we just connected to 63.161.169.137:80, so this should print:
// Peer IP address: 63.161.169.137
// Peer port : 80
len = sizeof addr;
getpeername(s, (struct sockaddr*)&addr, &len);
printf("Peer IP address: %s\n", inet_ntoa(addr.sin_addr));
printf("Peer port : %d\n", ntohs(addr.sin_port));
[/php]
ikoonman
thanks for the response.
i think i've found the problem tho, the limitation seems to be in dbgprint. it "wraps" unsigned longs into signed longs. instead of using "%d" for the u_long, i used "%x", to monitor the hex values. when i manually convert the hex back to decimal the ip is the correct long value.
can anyone confirm this behaviour?
ianhobo
have you tried using %ld for long ints?
ikoonman
that did the trick, thank you.
wasn't dbgprint's fault at all! .... was my lack of knowledge
ianhobo
Your welcome