BASIC User Group > Code Challenges

Retrieve your External IP address

(1/5) > >>

AIR:
Typically, when one is looking to retrieve their external IP address programmatically, one resorts to making an html request to a website like https://myexternalip.com/raw

For this challenge, the task is to retrieve your external IP using a *** DNS Query *** to resolver1.opendns.com.

The request you will send to that DNS server is: "myip.opendns.com".  The server is configured to respond to that specific request by returning the EXTERNAL IP address of the machine making the request.

Libraries, third party included, are allowed but shelling to a command line utility (like dig) or another programming language is not allowed.  Neither is scraping a webpage.

Obviously, you should NOT post your IP Address.

To test whether you are retrieving the correct IP address, either check it with the link provided at the begining of this post, or just google "my ip".

You can also check locally at a shell prompt, using:

Windows: nslookup myip.opendns.com. resolver1.opendns.com

Linux/macOS: dig +short myip.opendns.com @resolver1.opendns.com

To summarize:

DNS SERVER:   resolver1.opendns.com
DNS REQUEST: myip.opendns.com

AIR.



AIR:
PYTHON:


--- Code: Python ---#!/usr/bin/env python import dns.resolver,socket res = dns.resolver.Resolver(configure=False)res.nameservers = [socket.gethostbyname("resolver1.opendns.com")]print res.query('myip.opendns.com')[0] 
AIR.

AIR:
GO:


--- Code: Go ---package main import (        "context"        "fmt"        "log"        "net") func customDialer(ctx context.Context, network, address string) (net.Conn, error) {        d := net.Dialer{}        return d.DialContext(ctx, network, net.JoinHostPort("resolver1.opendns.com", "53"))} func main() {         r := net.Resolver{                PreferGo: true,                Dial:     customDialer,        }         ipaddr, err := r.LookupHost(context.Background(), "myip.opendns.com")        if err != nil {                log.Fatal(err)        }         fmt.Println("External IP:", ipaddr[0])} 
AIR.

jalih:
8th:


--- Code: ---
net:INET4 net:DGRAM net:socket var, socket

[ 0xaa, 0xaa, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  "myip", "opendns", "com", 0x00, 0x00, 0x01, 0x00, 0x01 ] "12b1s1c1s1c1s1c5b" pack var, message


: address-info
  "resolver1.opendns.com" 53 net:getaddrinfo null? if
    t:err? . cr bye
  then ;


: app:main
  socket @ address-info message @ 0 net:sendto null? if
    2drop t:err? . cr bye
  else
    drop
  then

  100 b:new 0 net:recvfrom null? if
    2drop t:err? . cr bye
  then

  \ Last four bytes from the response are IP address.
  dup 4 n:- swap b:slice "4:1B" unpack drop
  ' >s a:map
  "." a:join
  "External IP: " . . cr
  2drop
  bye ;

--- End code ---

AIR:
Thanks, Jalih!

Works as expected on my Mac.

AIR.

Navigation

[0] Message Index

[#] Next page

Go to full version