demic0de
demic0de

Reputation: 1313

Retrieve ip address of client who got a connection reset

I have this code which gets the ip of the client when the client closes or loses the connection.

char buffer[80]; 
ssize_t bread;
struct sockaddr_in peer;
socklen_t peer_len;

peer_len = sizeof(peer);

memset(&buffer, 0, sizeof(buffer));

bread = read(connectlist[listnum], buffer, 80);
if (bread < 0)
{

if(getpeername(connectlist[listnum],(struct sockaddr *) &peer, &peer_len) == -1){

        perror("getpeername() failed");
    }
            printf("Connection Reset From IP: %s\n", inet_ntoa(peer.sin_addr));

                _Print_To_File(inet_ntoa(peer.sin_addr));
                    close(connectlist[listnum]);
                        close(connectlist[listnum]);
                            connectlist[listnum] = 0;

}

if(bread == 0)
{
if(getpeername(connectlist[listnum],(struct sockaddr *) &peer, &peer_len) == -1){
        perror("getpeername() failed");
    }
            printf("Connection Closed From IP: %s\n", inet_ntoa(peer.sin_addr));

                _Print_To_File(inet_ntoa(peer.sin_addr));
                    close(connectlist[listnum]);
                            connectlist[listnum] = 0;
}

I can get the ip of the client when Connection Closed but When Connection Reset I don't get the ip of the client. I get 0.0.0.0 on connection reset. How can i fix this. thanks,

Upvotes: 0

Views: 128

Answers (2)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136385

getpeername() works only for connected sockets. Once the socket disconnected you'll get ENOTCONN error when invoking it. This is why getpeername() is sometimes used as a check whether the socket has/is connected.

Upvotes: 2

alk
alk

Reputation: 70971

You might like to use the struct sockaddr returned by the call to accept() done prior to read()ing.

Verbatim from man accept:

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

[...]

The argument addr is a pointer to a sockaddr structure. This structure is filled in with the address of the peer socket, as known to the communications layer. The exact format of the address returned addr is determined by the socket's address family (see socket(2) and the respective protocol man pages). When addr is NULL, nothing is filled in; in this case, addrlen is not used, and should also be NULL.

Upvotes: 1

Related Questions