views:

212

answers:

4

see the following code:

accept(sockfd, (struct sockaddr*)&cliaddr, &slen);
cout << inet_ntop(AF_INET, cliaddr.sin_addr, ipv4addr, 100);

my client connects from localhost. i get an absurd address in the output. this is not my ip address. everytime i run the code i get a different ip address. when i ping that ip address i don't get any response.

what is the reason.

i am running suse linux on a virtual machine in windows vista.

Update:

bzero(&cliaddr, sizeof(cliaddr));
int connfd = accept(sockfd, (struct sockaddr*)&cliaddr, &slen);

if (sem_wait(&mutex) < 0)
    err_sys("sem_init error");

char ipv4addr[100];
cout << inet_ntop(AF_INET, &cliaddr.sin_addr, ipv4addr, 100) << endl;

//const char* p = inet_ntop(AF_INET, &cliaddr.sin_addr, ipv4addr, 100);
//cout << p << endl;

//cout << (void*)p << " " << (void*)ipv4addr << endl;

this returns address as 0.0.0.0

if i uncomment the lines, i get the correct address in all the lines, 127.0.0.1

A: 

My unsubstantiated guess is that you're getting IP v6 addresses back instead of v4, so your conversion is off.

You might want to try using netstat to find out the client's port (you usually get a sort-of-random port number between 1025 and 65535) and see if the hex value of that appears somewhere in the hex representation of cliaddr. If there's a correlation between client port and what you believe to be the client address, then your conversion is incorrect.

Carl Smotricz
the client connects using a socket belonging to the AF_INET family and is running on localhost.
iamrohitbanga
also inet_ntop should return an error in this case.
iamrohitbanga
I may have another explanation. See my other answer.
Carl Smotricz
A: 

My next guess:

  On success, inet_ntop() returns a non-null pointer  to  dst.   NULL  is
       returned if there was an error, with errno set to indicate the error.

Is cout.<< clever enough to dereference the pointer that's being returned, or are you printing out the pointer?

Carl Smotricz
why else would it print232.76.213.191
iamrohitbanga
i think it has something to do with the virtual machine.
iamrohitbanga
OK, I give up. Good luck!
Carl Smotricz
+1  A: 
Nikolai N Fetissov
in my program len was not initialized. hence the error.
iamrohitbanga
A: 

I have same behavior for invalid value of 'slen' before 'accept(..)'.

basilk