How to get IP addr of Client?

How to get IP addr of Client?

Post by Richard Jone » Wed, 07 Oct 1998 04:00:00

: Hello,

: I have a socket based server.  It works fine but, now I'd like to
: find out the IP address of my client so that I can do some
: authentication on incomming connections.  I tried what I thought
: should work.  Right after I call "accept" I looked at the "struct
: sockaddr".  I guess I don't know how to interpet the data in there.
: It is an AF_INET/SOCK_STREAM socket.


        struct sockaddr_in peeraddress;
        int len = sizeof (peeraddress);

        ns = accept (s, (struct sockaddr *) &peeraddress, &len);

        printf ("client address = %s, client port = %d\n",
                inet_ntoa (peeraddress.sin_addr),
                ntohs (peeraddress.sin_port));

You should really also check that peeraddress.sin_family == AF_INET
but it's very rare (maybe even impossible?) that a client would be
connecting from a non-Internet address domain.

If you've ``lost'' the address returned by accept(2), then you
can get the information from the getpeername(2) socket call
which works for any connected socket.

By the way, address based authentication is very insecure - in
fact, don't use it, unless your data is totally unimportant.
Use a crypto-secure authentication mechanism instead. Check
out, for instance, SSL (SSLeay is a free implementation of

: Would anyone have a code example?

Do an Altavista search for the ``sockets FAQ'' (or socket FAQ?).
I don't have the URL right now, but it's extremely handy
for this sort of thing.


-      Richard Jones. Linux contractor London and SE areas.        -
-    Very boring homepage at:      -
- You are currently the 1,991,243,100th visitor to this signature. -
-    Original message content Copyright (C) 1998 Richard Jones.    -