You almost certainly don't need to call htons and then copy 2 bytes to the buffer - see Keith's answer for why.
However, if you need it (perhaps you are creating IP packets for comparison with captured wire packets as a test or something like that), you can.
First, if you use bytearray (or something else that conforms to the write buffer protocol), you simply use the usual list style slice assignment:
You do not have this double-byte string foo ; you have a short integer. In C, you can turn this into a pointer to two bytes, simply using the & operator to get its address, but Python cannot do this. Fortunately, there is a standard library module called struct , designed for this kind of thing:
t = socket.htons(int(port)) buf[i:i+2] = struct.pack('h', t)
Or, because a struct can handle the content for you:
t = int(port) buf[i:i+2] = struct.pack('!h', t)
However, often you do not even need to copy the buffer; you can immediately define the whole structure inside a struct . For example, if you are trying to pack the IP address and port into a 6-byte array, you can do this:
buf = bytearray(6) i = 0 addrbytes = [int(part) for part in addr.split('.')] buf[i:i+4] = struct.pack('4B', addrbytes[0], addrbytes[1], addrbytes[2], addrbytes[3]) i += 4 portshort = int(port) buf[i:i+2] = struct.pack('!h', portshort)
But it is much simpler:
addrbytes = [int(part) for part in addr.split('.')] portshort = int(port) buf = struct.pack('!4Bh', addrbytes[0], addrbytes[1], addrbytes[2], addrbytes[3], portshort)
I just defined a structure that is in network order, with four bytes, followed by a short one, and packed my data into it.
One last thing to mention: if you really want to deal with C-style variables using C-style code, ctypes is another option. It is specifically designed to interact with C-code, so in general it is rather low-level (and the only module in the standard library that allows you to segfault your code), but it allows you to create some nice mid-level materials that look a bit more like C:
class ADDRPORT(ctypes.BigEndianStructure): _fields_ = [("addr", ctypes.c_char*4), ("port", ctypes.c_short)] addrport = ADDRPORT(addrbytes, portshort)
As your C code gradually fills the buffer rather than setting struct elements, this is probably not what you want. But it is worth knowing, because it will probably be what you want at some point.