I'm trying to write a (very) primitive "service discovery" module, and it seems 
"nativesockets.Hostent.addrList" is not what I would have expected.

Here the code I used:
    
    
    import nativesockets
    import net
    import strutils
    
    proc parseURL(hostport: string): tuple[ip: string, port: Port, url: string] 
=
      let idx = hostport.find(':')
      if (idx < 1) or (idx == high(hostport)):
        raise newException(Exception, "Bad URL: '" & hostport & "': port 
missing")
      let host = hostport.substr(0,idx-1)
      let portstr = hostport.substr(idx+1)
      var port = -1
      try:
        port = parseInt(portstr)
      except:
        discard
      if (port < 1) or (port > 65535):
        raise newException(Exception, "Bad URL: '" & hostport & "': bad port")
      var ip: IpAddress
      if isIpAddress(host):
        try:
          ip = parseIpAddress(host)
        except:
          raise newException(Exception, "Bad URL: '" & hostport & "': bad IP 
address")
      else:
        var hostent: Hostent
        try:
          hostent = getHostByName(host)
        except:
          raise newException(Exception, "Bad URL: '" & hostport & "': bad 
hostname")
        if hostent.addrList.len == 0:
          raise newException(Exception, "Bad URL: '" & hostport & "': no IP for 
hostname")
        let a = hostent.addrList[0]
        try:
          ip = parseIpAddress(a)
        except:
          raise newException(Exception, "Bad URL: '" & hostport & "': failed to 
parse IP of address: " & $len(a) & " " & a)
      result = ($ip, Port(port), hostport)
    
    echo("RESULT: " & $parseURL("google.com:80"))
    

This fails with the last "raise" line, like this:
    
    
    testgethostbyname.nim(40) testgethostbyname
    testgethostbyname.nim(37) parseURL
    Error: unhandled exception: Bad URL: 'google.com:80': failed to parse IP of 
address: 14 Ï:ð.google.com [Exception]
    Error: execution of an external program failed: '../bin/testgethostbyname '
    

Either there is something terribly wrong with my code, or "hostent.addrList[0]" 
is not something like "1.2.3.4", but something else entirely. In that case, 
since the type is "string", how am I meant to "interpret" it, to get something 
like "1.2.3.4"? Or is there an alternative call to getHostByName() that 
actually returns an IP in a "usable format"?

I wanted to use the "ip" to pass it to Socket.connect(ip, port), so I save the 
DNS query on repeated calls.

Reply via email to