Re: How to find client's IP address (or name)

Abhijit Menon-Sen <[email protected]> Tue, 1 Mar 2005 23:11:32 +0530
Newsgroups gmane.user-groups.linux.delhi.devel,gmane.user-groups.linux.delhi
Message-ID <[email protected]>
At 2005-03-01 09:17:02 -0600, nishikant.x.kapoor-CDGYnrjxVPGpp/[email protected] wrote:
>
> I am trying to find the IP address of the client when the client
> attempts to make a connection. Does anyone know how to do that?
>
> [...]
> 
>    struct sockaddr     client;

This needs to be a sockaddr_in too.

>       rc = accept(msgSock, &client, &addrlen);

        addrlen = sizeof(struct sockaddr_in);
        rc = accept(msgSock, (struct sockaddr *)&client, &addrlen);
        if (rc < 0)
            ...

>       fprintf (stdout, "client.sa_data=%s \n", client.sa_data);
>       fprintf (stdout, "Client's IP address: %s \n", "???");

You can use inet_ntoa(client.sin_addr) in this case, since you've just
called accept(2). In the more general case, use getpeername(2) on the
connected socket. Use gethostbyaddr(3) to convert that into a name.

-- ams