0

I have a Server (A) and a client (B), written in C, running on the same Linux machine. The server binds a port to INADDR_ANY, and the client binds another port to INADDR_ANY. When another client (C), which is running on another Linux machine, connects to the server, I want the server to get the IP address of client B and send it to client C.

When I'm using getpeername() from the server, it returns "127.0.0.1" which is correct, but I can't send this address to client C- it won't be able to connect to client B with that address.

Is there any smart way to get the actual IP of client B? If it is somewhat easier, I can make each client send it's IP to the server.

Thanks!

bomba6
  • 539
  • 1
  • 7
  • 21

2 Answers2

0

Use getifaddrs() to get the interface IP address, there's an example in the man page. Note that you can send the IP address of any interface since the server is bound using INADDR_ANY so it listens on all interfaces. From man ip(7)

When INADDR_ANY is specified in the bind call, the socket will be bound to all local interfaces.

If you want the public IP address then refer to this question:

Get public/external IP address?

Community
  • 1
  • 1
iabdalkader
  • 17,009
  • 4
  • 47
  • 74
  • mux- the problem with getifaddrs() is that a computer can have multiple IP addresses, so I just can't catch the first IP which is not 127.0.0.1. – bomba6 Jan 07 '13 at 12:42
  • @bomba6 I think anyone will do because the server is bound to `INADDR_ANY` it listens on all interfaces so it will receive the packet. – iabdalkader Jan 07 '13 at 12:49
  • Thanks for the clarification. But- client C is located on a different computer, on (another) network. I'm not in a risk to return an "internal" IP address? – bomba6 Jan 07 '13 at 13:02
  • 1
    @bomba6 yes it returns the internal IP address, in short you will need to connect to a service such as http://whatismyip.org/ refer to the linked question for details. – iabdalkader Jan 07 '13 at 13:12
0

What you actually want to know is the IP address of the interface, which would be used to route towards client C.
With the Linux command line, you can do this (assuming C is 10.0.0.1):

# ip route show match 10.0.0.1
default via 20.0.0.2 dev eth0
# ifconfig eth0
eth0        Link encap:Ethernet  HWaddr 00:00:00:00:00:00
            inet addr:20.0.0.3  Bcast:20.0.0.255  Mask:255.255.255.0

In this case, you'll want to use 20.0.0.3.

The question remains how to get all this in C. One way would be to connect to some service on C, and run getsockname on the resulting socket.

ugoren
  • 16,023
  • 3
  • 35
  • 65