2

Possible Duplicate:
Discovering public IP programatically

Is there a way to know my public IP address from a C program? I am using a DSL modem and working on Linux operating system.

I need to know the public IP, so that I can make the server-client socket program work while on Internet.

Community
  • 1
  • 1

2 Answers2

1

It's unclear from your question whether you're behind a router or not, but if not, I don't think this is a duplicate.

If you are behind a router, then unless the router is configured to forward to your machine already, knowing the public ip address of the router is mostly useless.

If you're not behind a router, the problem is simple. Just make a UDP socket and connect it to any non-local ip address, then call getsockname on the socket. The resulting sockaddr_in will contain the IP address which would be used to send to that address, i.e. your "public ip address". 8.8.8.8 would be a nice simple choice of an address to use, as would any of the dns "root servers". Remember you don't have to send any packets to it (this is why you're using UDP rather than TCP), just connect a connectionless socket to it.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
0

Yes, you can use the STUN protocol to ask a STUN server what IP address it sees your request originating from. There are several open STUN servers you could use, stunserver.org for example.

cdhowie
  • 158,093
  • 24
  • 286
  • 300