473,811 Members | 3,152 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Encoding.ASCII. GetBytes similar for Python ?

Rui
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
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\u 0000\u0001\u000 0\u0000\u0000\u 0000\u0000\u000 0"
trailer_string = "\u0000\u0000\u 0001\u0000\u000 1"

address = 'google.com'
url_name_start, domain_name = address.split(" .")

# Query format copied from the C# example.
#QueryString = TransactionID1 + TypeString + (char)URLNameSt art.Length
+ URLNameStart + (char)DomainNam e.Length + DomainName+ TrailerString;
query = (transaction_id + type_string + str(len(url_nam e_start)) +
url_name_start +
str(len(domain_ name)) + domain_name + trailer_string)
print query

sock = socket.socket(s ocket.AF_INET, socket.SOCK_DGR AM)
sock.settimeout (TIMEOUT)
sock.connect(se rver_host)

sock.send(query )
data = sock.recv(512)

for data_item in data:
try:
print chr(data_item)
except:
print data_item
But it just returns trash:
>python dns_checker.py
Q1\u0001\u0000\ u0000\u0001\u00 00\u0000\u0000\ u0000\u0000\u00 006google3com
\u0000\
u0000\u0001\u00 00\u0001
Q
1
Ï



Any advice ? Thanks!

Sep 22 '08 #1
1 5610
On Mon, 22 Sep 2008 04:23:09 -0700, 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 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\u 0000\u0001\u000 0\u0000\u0000\u 0000\u0000\u000 0"
trailer_string = "\u0000\u0000\u 0001\u0000\u000 1"
Are you sure you want normal byte strings with *that* content!?

In [90]: s = "\u0000\u0000\u 0001\u0000\u000 1"

In [91]: len(s)
Out[91]: 30

In [92]: print s
\u0000\u0000\u0 001\u0000\u0001

This is not 5 unicode characters but 30 ASCII characters. But why using
unicode anyway? I guess the DNS server expects bytes and not unicode
characters.
address = 'google.com'
url_name_start, domain_name = address.split(" .")

# Query format copied from the C# example. #QueryString = TransactionID1
+ TypeString + (char)URLNameSt art.Length + URLNameStart +
(char)DomainNam e.Length + DomainName+ TrailerString; query =
(transaction_id + type_string + str(len(url_nam e_start)) +
url_name_start +
str(len(domain_ name)) + domain_name + trailer_string)
print query

sock = socket.socket(s ocket.AF_INET, socket.SOCK_DGR AM)
sock.settimeout (TIMEOUT)
sock.connect(se rver_host)

sock.send(query )
data = sock.recv(512)

for data_item in data:
try:
print chr(data_item)
except:
print data_item
This will always end up in the ``except`` branch because `data` is a
string and `chr()` expects integers. Any chance you wanted `ord()`
instead?

When you print out "trash" please use `repr()` so we can see what trash
*exactly* you get.

Ciao,
Marc 'BlackJack' Rintsch
Sep 22 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
3538
by: Sebastian Meyer | last post by:
Hi newsgroup, i am trying to replace german special characters in strings like str = re.sub('', 'oe', str) When i work with this, i always get the message UniCode Error: ASCII decoding error : ordinal not in range(128) Yes i have googled, i searched the faq, manual and python library and searched all known soruces of information. I played with the python
10
687
by: Christopher H. Laco | last post by:
Long story longer. I need to get web user input into a backend system that a) only grocks single byte encoding, b) expectes the data transer to be 1 bytes = 1 character, and c) uses the HP Roman-6 codepage system wide. As much as it sounds good, UTF/Unicode encoding is not an option, nor is changing the codepage. Tackling the first is easy via Encoding.Default.GetBytes and shoving it over the network. However, Encoding.Default is the...
4
3352
by: Curt Fluegel | last post by:
I seem to be having a problem base64 encoding characters above 127. I can encode a sentence like "The big bad dog" without problems, but if I try to encode something like 0xFF I get different results than in Perl. For example I am using: byte binaryArray = System.Text.ASCIIEncoding.ASCII.GetBytes(binaryString); string pushString = System.Convert.ToBase64String(binaryArray);
13
6149
by: Dan V. | last post by:
How do I create a one line text file with these control codes? e.g.: 144 = 0x90 and 147 = 0x93? I am trying to create a one line text file with these characters all one one row with no spaces. 1. 144 = 0x90 2. 147 = 0x93 3. STX = (^B = 2 = 0x2) 4. NUL = (^@ = 0 = 0x0)
10
10107
by: Marc Jennings | last post by:
Hi there, Can anyone point out any really obvious flaws in the methodology below to determine the likely encoding of a file, please? I know the number of types of encoding is small, but that is only because the possibilities I need to work with is a small list. > private string determineFileEncoding(FileStream strm) > { > long originalSize = strm.Length;
1
9789
by: Emilio | last post by:
Question about Dim data As () = System.Text.Encoding.ASCII.GetBytes(message) Would it be the same to write: Dim data() As Byte = System.Text.Encoding.ASCII.GetBytes(message) ?
5
2501
by: Peter Romero | last post by:
All I want to do is write a simple app that takes a user-entered character and gives me the 1, 2, or 4 bytes that represent it in UTF-8. Common sense indicates that the active code should be about 1 line long. However, being new to dot net, I can't seem to figure out any way to do it, and everything I read about encodings and encoders suggests it must be at least 450,890 lines of code. I'm about ready to write my own conversion function. ...
1
12394
by: devgrt | last post by:
Checking if proper/best way to do this... I have to pass a C# string to a C++ DLL. The function in the DLL (gethostbyname) requires a null terminated string. It seems like when you do byte var = Encoding.ASCII.GetBytes(string); that it only loads the byte array with the chars and does not add a null at the end. I would like to know if the below is proper way to deal with this: byte var = Encoding.ASCII.GetBytes(string + '\0'); By...
9
4150
by: =?Utf-8?B?RGFu?= | last post by:
I have the following code section that I thought would strip out all the non-ascii characters from a string after decoding it. Unfortunately the non-ascii characters are still in the string. What am I doing wrong? Dim plainText As String plainText = "t═e" Dim plainTextBytes() As Byte Dim enc As Encoding = Encoding.ASCII plainTextBytes = enc.GetBytes(plainText)
0
9730
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
10651
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10136
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9208
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6893
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5555
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4341
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3868
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3020
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.