Encoding.ASCII.GetBytes similar for Python ?

Tino Wildenhain tino at wildenhain.de
Mon Sep 22 14:20:50 CEST 2008


Hi,

Rui wrote:
> Hi, how can i do what Encoding.ASCII.GetBytes (in .net, c#) does with
> the strings. I am trying to query some dns server to check its

What would it do?

> response using udp sockets. Some of the source below:
> 
> # encoding: utf8
> import socket
> import sys
> import struct
> 
> IP_PORT = 53
> server_host = ('4.2.2.1', IP_PORT)
> transaction_id = "Q1"
> TIMEOUT = 5
> 
> type_string =
> "\u0001\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0000"
> trailer_string = "\u0000\u0000\u0001\u0000\u0001"
> 
> address = 'google.com'
> url_name_start, domain_name = address.split(".")
> 
> # Query format copied from the C# example.
> #QueryString = TransactionID1 + TypeString + (char)URLNameStart.Length
> + URLNameStart + (char)DomainName.Length + DomainName+ TrailerString;
> query =  (transaction_id + type_string + str(len(url_name_start)) +
> url_name_start +
>          str(len(domain_name)) + domain_name + trailer_string)
> print query

You should refrain from trying a 1:1 translation from one language
to another. This makes funny things with natural languages as well
as it is horribly with computer languages.

You should really read on string formatting in python.

Also, while indeed usefull to understand whats going on for production
use this is not recommended anymore, since you would have to randomize
ports for requests instead of using fixed 53UDP.

I'd recommend having a look on python adns - 
http://code.google.com/p/adns-python/




> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
> sock.settimeout(TIMEOUT)
> sock.connect(server_host)
> 
> sock.send(query)
> data = sock.recv(512)
> 
> for data_item in data:
>     try:
>         print chr(data_item) 

this is never going to work since recv() returns a string buffer, not
a list of integers.

HTH
Tino
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3241 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20080922/48caadb3/attachment.bin>


More information about the Python-list mailing list