Getting ip address from a socket fd (not duplicate) [duplicate] - c

This question already has an answer here:
getpeername always gives bad file descriptor
(1 answer)
Closed 8 years ago.
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?

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)

Related

Raw sockets in C, isn't connect redundant?

I'm writing a simple program that creates an ethernet I frame and sends it through an interface to the specified MAC.
As i have read, the process for connecting to a socket in UNIX goes a bit like:
int sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
struct sockaddr_ll sll;
/* populate sll with the target and interface info */
connect(sockfd, (struct sockaddr*)&sll, sizeof(sll));
write(sockfd, stuff, sizeof(stuff));
close(sockfd)
The thing is, for me, stuff is a valid eth frame already containing everything needed to send a packet to its destination. Isn't the connect step redundant then? What am I missing?
Have a nice day.
Not only is the connect "redundant", it is an error -- according to the Linux man page:
The connect(2) operation is not supported on packet sockets.
So the connect is probably failing but not actually doing anything. Since you ignore the return value of connect, you don't notice the failure.
As stated above, the connection step was wrong.
I will give the details of how i solved it in this post in case anyone in need sees this: (this is as i understood it, feel free to correct me)
For a trully raw communication in userspace you have to understand three concepts:
Sockets are analogous to file descriptors.
Binding a socket is like opening a file.
You can not read or write to a socket, just kindly ask the kernel to do it for you.
The process i followed is as follows:
int sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
struct sockaddr_ll sll;
sll.sll_family = AF_PACKET;
sll.sll_ifindex = index; //This is the index of your network card
//Can be obtained through ioctl with SIOCGIFINDEX
sll.sll_protocol = htons(ETH_P_ALL);
bind(sockfd, (struct sockaddr*)&sll, sizeof(sll));
size_t send_len = write(sockfd, data, size);
As you can see, we dont really use connect, as it was, indeed, a mistake.
p.s. for a full example: https://github.com/TretornESP/RAWRP

Get Local Port used by Socket

I need to get the local port used by a (client) socket.
It was my understanding that Windows Sockets performs an implicit bind function call, therefore getsockname() after sendto() should provide the assigned port. However, it always sets 0 as the port number. Am I missing something?
ex:
if (sendto(sockfd, ...) != SOCKET_ERROR)
printf("Sent\n");
if (getsockname(sockfd, (struct sockaddr*)&sin, &sinlen) != SOCKET_ERROR)
printf("port = %u\n", ntohs(sin.sin_port);
else
printf("Error");
//result: Sent, port = 0
Problem solved with a restart of the computer. Still unknown as to the actual cause, but at this point I'm just happy it's working.
If anyone has an idea for fixing the issue without a restart (for future readers), feel free to post.
The only ambiguity I can see in your example code is what size you assigned to sinlen before calling. (you do not show it) If you are using winsock, it should be defined, and assigned int sinlen = sizeof(sin);
I used this code on my system, and it returns a non-zero value for the port I am connecting through:
struct sockaddr_in sin;
int len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
//handle error
else
printf("port number %d\n", ntohs(sin.sin_port));
By the way, The ntohs function function returns the value in host byte order. If [ sin.sin_port ] is already in host byte order, then this function will reverse it. It is up to [your] application to determine if the byte order must be reversed. [text in brackets are my emphasis]
In answer to comment question ( getsockname() ):
The function prototype for getsockname():
int getsockname(
_In_ SOCKET s,
_Out_ struct sockaddr *name,
_Inout_ int *namelen //int, not socklen_t
);
For more discussion on socklen_t
Edit (address possible approach to re-setting sockets without rebooting PC.)
If winsock API calls cease to work predictably, you can re-start sockets without rebooting the PC by using WSAStartup and WSACleanup (see code example at bottom of link for WSAStartup)
You say you want to know the LOCAL port, but your line
sendto(sockfd, ...)
implies sockfd is the REMOTE descriptor. Your later code may therefore give you info about the REMOTE port, not the LOCAL one. 'sockets' are not both ends, meaning one connection. A socket is one end, meaning the IP and port number of one end of the connection. The first parameter of your getsockname() is not a reference or a pointer, it is therefore not an output from the function, but an input. You're telling the function to use the same socket descriptor that you just sent to, ie. the remote one.
Formatting error. ntohs() returns unsigned short so the format should be %hu, not %u or %d. If you grab too many bytes they are not the port.
Answer. After using sendto() try using gethostname() then getaddrinfo() on the name that comes back. Note: the addrinfo structures you get back will give you struct sockaddr pointers which you will need to re-cast to struct sockaddr_in pointers to access the local port number.
To find the local port number the kernel dreamed up when you issued a sendto() function perhaps you could write a routine to parse the output from the (gnu linux) commands 'ss' or 'netstat'. (Not sure if these are POSIX compatible.) Or maybe you could access /proc/net if you have the privilege.

How to find out IP address of a given process connected through TCP

So I want to obtain the address of the machine a process (subscriber) is working on, so I can send it in a message to the server (intermediary), next to a specific port, so the server can answer on that other port.
That is, they are going to be connected, but I want the answer in another port. So I want to forward the port next to the address of the suscriber so the server can connect.
I believe ONE way of doing it would be similar to an example found
http://beej.us/guide/bgnet/output/html/multipage/getaddrinfoman.html
so I would use getaddrinfo to do something like this
if ((rv = getaddrinfo(NULL, "3490", &hints, &servinfo)) != 0) {
and then I would look in the linked list for the address in
dir_tcp_srv.sin_addr.s_addr
But I think this is in fact not the correct use. I don't fully understand but I believe this is not quite the way of doing it.
I guess there are many ways of doing this but essentially I want to obtain the data (I already have the port number) so that the client and server roles switch, and the server makes a connection to the client
Edit: Ok so I'm reading time and time again how the server knows the address of the client once it's connected. I'm re-reading man pages to know how to obtain that info but can't find it yet.
Also, I found this:
https://suite.io/guy-lecky-thompson/7sd21g
But I can't say I quite get it.
Edit2: I think I've had a concept wrong for a long time.
In my code I make accept like this:
fdSocketDevuelto = accept(sock_tcp, (struct sockaddr )&dir_tcp_srv, (socklen_t) &sizeSock);
Which I now believe is overwriting the info previously stored in the struct, that I used to bind, listen, all that, with the client's info. If someone can confirm this I can comment to my own question with this as the answer or delete the whole thing since it was something I never fully understood/used.
I understand the question as you are wanting to have server find the client's IP address and Port. Take a look at getpeername():
From Beej's guide:
http://beej.us/guide/bgnet/output/html/multipage/getpeernameman.html
// assume s is a connected socket
socklen_t len;
struct sockaddr_storage addr;
char ipstr[INET6_ADDRSTRLEN];
int port;
len = sizeof addr;
getpeername(s, (struct sockaddr*)&addr, &len);
// deal with both IPv4 and IPv6:
if (addr.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
port = ntohs(s->sin_port);
inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr);
} else { // AF_INET6
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
port = ntohs(s->sin6_port);
inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr);
}
printf("Peer IP address: %s\n", ipstr);
printf("Peer port : %d\n", port);

getpeername Invalid argument after running a server several times

I've got this, taken from beej guide and slightly adapted:
socklen_t len;
struct sockaddr_storage addr;
char ipstr[INET6_ADDRSTRLEN];
char nombreSubscriptor[INET6_ADDRSTRLEN+sizeof(int)];
int port;
len = sizeof(addr);
if(getpeername(fdSocketDevuelto, (struct sockaddr*)&addr, &len)<0){
perror("GETPEERNAME error");
close(fdSocketDevuelto);
exit(1);
}
if (addr.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
port = ntohs(s->sin_port);
inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr);
} else { // AF_INET6
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
port = ntohs(s->sin6_port);
inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr);
}
printf("Peer IP address: %s\n", ipstr);
printf("Peer port : %d\n", port);
So I run the client and server and send messages to the server, everything works fine, showing like this
Peer IP address: 127.0.0.1
Peer port : 42639
But if I close and open several times (sometimes it's in the first 1-2 times I try it, but this has happened less), at some point I'm getting this:
GETPEERNAME error: Invalid argument
And before I used the perror and exit(1) in the getpeername I was getting stuff similar to this (it changed slightly in the numbers):
Peer IP address: 2325:2ec7:c37f::
Peer port : 20423
I had already asked here Recv gives Bad file descriptor only sometimes (run the program it works fine, sometimes it does not work) but the question is flat out wrong since it's not the recv that has the failure, it's the getpeername function. And I decided to ask again with proper data this time, which I'm unsure if it's the right thing to do.
The question is: why would this happen? Why sometimes it passes and Ip is fine and sometimes is not? It's two completly different runs of the code, I close and run again, and do not compile or do anything. When it gives me the failure, I wait some minutes (this also looks to be changing from time to time) and I can run again and it works just fine again.

Getting my own IP address using getsockname() [duplicate]

This question already has an answer here:
Getting my own IP address by connect()ing using UDP socket?
(1 answer)
Closed 8 years ago.
I'm trying to get my own IP address by trying to connect() to 8.8.8.8 using UDP socket and then calling getsockname() function.
I've written a function get_my_ip(), and the code worked when it was placed in my server program, but as a separate function, it fails. It prints some strange characters instead of my IP address.
The only thing I changed from the code in my server program was return NULL instead of return 1, or return 2, because it was inside int main().
Can anyone see why my program is not working?
Thank you.
You must initialize addrlen.
addrlen = sizeof remoteaddr;
getsockname(sockfd, (struct sockaddr*)&remoteaddr, &addrlen);
You must cast the sin_addr in your inet_ntop() call. It should be like this:
inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr), remoteIP, addrlen);
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr), remoteIP, addrlen);

Resources