2

I am attaching my process (with root privileges) to a browser process to intercepts its system calls using ptrace. To decode the parameters of the connect() system call i got the sockfd. But i have been trying from days to get the ip address of the other end of that socket but with no success.

i came accross these 2 questions while looking around

1)Get IP address from socket descriptor?

2)Getting IP address, port and connection type from a socket fd

I followed the suggestion of the 1st question, but somehow it was giving error. something error: ‘struct sockaddr_in’ has no member named ‘sa_data’. I digged deeper into the internet and got another hint, which i used to write this code

temp = getpeername(regs.rdi, (struct sockaddr *)&ip_addr_struct, &ip_addr_structlen);
struct sockaddr_in *s = (struct sockaddr_in *)&ip_addr_struct;
int port = ntohs(s->sin_port);
inet_ntop(AF_INET, &s->sin_addr, ip_addr, 1024);
printf("%d-%s\n", port, ip_addr);

here regs.rdi is the sockfd. But even with this code everytime i get 0-0.0.0.0 as output. please help anyone. Is there any other way to get the ip addrres or am i doing something wrong?

Community
  • 1
  • 1
Haris
  • 12,120
  • 6
  • 43
  • 70
  • Try getaddrinfo(). http://linux.die.net/man/3/getaddrinfo in_addr should be the field you should try to access using the sockaddr_in variable/pointer. Use pton() or ntop() to convert its format. http://msdn.microsoft.com/en-us/library/zx63b042.aspx – anurag-jain Oct 13 '14 at 17:19
  • @a4anurag: i am accessing `sin_addr` using sockaddr_in pointer, that is `s`. i didnt quite understand what `pton()` or `ntop()` would do. please explain a little more – Haris Oct 13 '14 at 17:27
  • @a4anurag: `getaddrinfo()` is for dns name resolution.. – Haris Oct 13 '14 at 17:34
  • I believe `getnameinfo`, with `NI_NUMERICHOST`, is what you want. – R.. GitHub STOP HELPING ICE Oct 13 '14 at 18:01
  • @R..: can you plz give me an example.. – Haris Oct 13 '14 at 18:01

1 Answers1

0

If your requirement is to get the IP address of the connecting client, use this :)

struct sockaddr_in their_addr;

if ((*cli_fd = accept(listener, (struct sockaddr *)&their_addr,&sin_size)) == -1)
{
    close (*cli_fd);
    return -1;
}

This is the client ip address ==> inet_ntoa(their_addr.sin_addr)
Ankit Tripathi
  • 374
  • 1
  • 8