what ip address does accept return
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 <<开发者_如何学C; 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
You are missing the 4th parameter in your call to inet_ntop()
. Here's a working example:
int sockfd, fd;
struct sockaddr_in saddr;
socklen_t len = sizeof( saddr );
char addr_buf[INET_ADDRSTRLEN]; /* defined in <netinet/in.h> */
/* ... socket(), bind(), listen() */
bzero( &saddr, len );
if (( fd = accept( sockfd, ( struct sockaddr* )&saddr, &len )) == -1 )
{ perror( "accept" ); exit( 1 ); } /* watch out for EINTR */
if ( inet_ntop( AF_INET, &saddr.sin_addr, addr_buf,
INET_ADDRSTRLEN ) == NULL )
{ perror( "inet_ntop" ); exit( 1 ); }
printf( "accepted connection from [%s:%d]\n",
addr_buf, ntohs( saddr.sin_port ));
...
Always check for errors when talking to network.
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.
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?
精彩评论