0

I have two questions...

1.)Is it possible to get my external IP address with a c function?

2.) If a device is listen() to a port (with struct sockaddr_in servAddr; servAddr.sin_addr.s_addr=htonl(INADDR_ANY);) would the external IP address be the IP address to connect() from another device ?

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
  • 1
    What if the system have *multiple* "external IP addresses"? Many systems today can have multiple interface-cards. The only reliable way is to already have a connection, and call `getsockname` on the connected socket to see what interface IP address the connection is using. Also `INADDR_ANY` means to listen to *all* interfaces, local or external, no matter how many. – Some programmer dude Jul 21 '16 at 22:54

1 Answers1

0

Is it possible to get my external IP address with a c function?

This may be an XY problem. The short answer to your question, is "no".

The chances are if you are trying to get an external IP address it is because you are behind a nat and you want to run a server. Assuming you know what port forwarding is and can set it up on your nat box, you'll need to know your external IP address so you can actually connect to your server.

There are a number of public services that you can use to get your external IP address. One idea is to set up free dynamic dns. Another idea is to fetch your external IP from a service on the internet.

If you send an HTTP get request to http://ip-api.com/json, you'll get back a json structure that you can parse:

A successful request will return, by default, the following:

{
    "status": "success",
    "country": "COUNTRY",
    "countryCode": "COUNTRY CODE",
    "region": "REGION CODE",
    "regionName": "REGION NAME",
    "city": "CITY",
    "zip": "ZIP CODE",
    "lat": LATITUDE,
    "lon": LONGITUDE,
    "timezone": "TIME ZONE",
    "isp": "ISP NAME",
    "org": "ORGANIZATION NAME",
    "as": "AS NUMBER / NAME",
    "query": "IP ADDRESS USED FOR QUERY"
}

C isn't the best language for this. A python implementation could be:

import urllib2,json
j=json.load(urllib2.urlopen('http://ip-api.com/json'))
print(j['query'])

If you really want to hand code this in C, then take a look at Jerry's excellent post on writing a small program to do an HTTP get/post. You'll also want to look at some of the C json parsers on json.org.

If a device is listen() to a port (with struct sockaddr_in servAddr; servAddr.sin_addr.s_addr=htonl(INADDR_ANY);) would the external IP address be the IP address to connect() from another device ?

Yes, if the other device is on the far side of your nat box and you have port forwarding set up.

Community
  • 1
  • 1
evaitl
  • 1,365
  • 8
  • 16