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.