You almost certainly don't need to call htons and then copy the 2 bytes into a buffer—see Keith's answer for why.

However, if you do need to do this (maybe you're crafting IP packets to compare to captured wire packets as a test or something?), you can.

First, if you're using a bytearray (or anything else that meets the writable buffer protocol), you just use normal list-style slice assignment:

# like C's memcpy(buf+i, foo, 2)
buf[i:i+2] = foo

You don't have that two-byte string foo; you have a short integer. In C, you can turn that into a pointer to two bytes just by using the & operator to get its address, but Python can't do that. Fortunately, there's a standard library module called struct designed for exactly this kind of thing:

t = socket.htons(int(port))
buf[i:i+2] = struct.pack('h', t)

Or, because struct can handle endianness for you:

t = int(port)
buf[i:i+2] = struct.pack('!h', t)

However, often you don't even need the buffer copying; you can define the entire structure all at once inside struct. For example, if you're trying to pack an IP address and port into a 6-byte array, you could 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 this 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've just defined a structure that's in network order, with four bytes followed by a short, 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, the ctypes module is another option. It's made specifically for interacting with C code, so in general it's pretty low-level (and the only module in the standard library that lets you segfault your code), but it let you build some nice mid-level stuff that looks a little more like C:

class ADDRPORT(ctypes.BigEndianStructure):
    _fields_ = [("addr", ctypes.c_char*4),
                ("port", ctypes.c_short)]

addrport = ADDRPORT(addrbytes, portshort)

Since your C code is progressively filling up a buffer, rather than setting elements of a struct, this probably isn't what you want. But it's worth being aware of, because it probably will be what you want at some point.

Answer from abarnert on Stack Overflow
Top answer
1 of 2
7

You almost certainly don't need to call htons and then copy the 2 bytes into a buffer—see Keith's answer for why.

However, if you do need to do this (maybe you're crafting IP packets to compare to captured wire packets as a test or something?), you can.

First, if you're using a bytearray (or anything else that meets the writable buffer protocol), you just use normal list-style slice assignment:

# like C's memcpy(buf+i, foo, 2)
buf[i:i+2] = foo

You don't have that two-byte string foo; you have a short integer. In C, you can turn that into a pointer to two bytes just by using the & operator to get its address, but Python can't do that. Fortunately, there's a standard library module called struct designed for exactly this kind of thing:

t = socket.htons(int(port))
buf[i:i+2] = struct.pack('h', t)

Or, because struct can handle endianness for you:

t = int(port)
buf[i:i+2] = struct.pack('!h', t)

However, often you don't even need the buffer copying; you can define the entire structure all at once inside struct. For example, if you're trying to pack an IP address and port into a 6-byte array, you could 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 this 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've just defined a structure that's in network order, with four bytes followed by a short, 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, the ctypes module is another option. It's made specifically for interacting with C code, so in general it's pretty low-level (and the only module in the standard library that lets you segfault your code), but it let you build some nice mid-level stuff that looks a little more like C:

class ADDRPORT(ctypes.BigEndianStructure):
    _fields_ = [("addr", ctypes.c_char*4),
                ("port", ctypes.c_short)]

addrport = ADDRPORT(addrbytes, portshort)

Since your C code is progressively filling up a buffer, rather than setting elements of a struct, this probably isn't what you want. But it's worth being aware of, because it probably will be what you want at some point.

2 of 2
7

It looks like you are trying to get a port number from user input or a string.

In Python:

port = int(port)

Then you can pass that directly to a socket instantiation:

socket = socket.socket(("127.0.0.1", port))

Python does the htons translation for you. You only need to supply an address to a socket (in the case of TCP) as a tuple of a string and integer.

🌐
HotExamples
python.hotexamples.com › examples › sdl › - › memcpy › python-memcpy-function-examples.html
Python memcpy Examples, sdl.memcpy Python Examples - HotExamples
def _resize(self): if self._size >= 0 and self._size <= 100: self._reserve += 1 elif self._size > 100 and self._size <= 10000: self._reserve += 100 elif self._size > 10000 and self._size <= 1000000: self._reserve += 10000 else: self._reserve += 100000 temp = x86.MemData(self._item_size * self._reserve) memcpy(temp.ptr(), self._address.ptr(), self._size * self._item_size) self._address = temp ... def read_bytes(self, offset=0, nbytes=-1): buff_size = self._size * self._item_size n = nbytes if n == -1: n = buff_size - offset n = min(n, buff_size - offset) n = max(n, 0) arr = array('B', [0]*n) address = arr.buffer_info()[0] off_addr = self._address.ptr() + offset memcpy(address, off_addr, n) return arr
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › write-memcpy
Write your own memcpy() and memmove() - GeeksforGeeks
February 18, 2026 - Interview Questions · Examples · Quizzes · Projects · Cheatsheet · OOP · Exception Handling · STL · DSA C++ Last Updated : 18 Feb, 2026 · The memcpy function is used to copy a block of data from a source address to a destination address. It assumes the memory regions do not overlap.
🌐
Python
wiki.python.org › moin › ctypes
ctypes - Python Wiki
You change the byte length that you use, not the byte length that ctypes.sizeof reports. For example: class MaxByteString(ctypes.Structure): _fields_ = [('bytes', 0xFF * ctypes.c_ubyte)] FAQ: How do I say memcpy? ctypes.memmove · (Remember the difference in argument order between memmove and memcpy.) FAQ: How do I say offsetof?
🌐
Bytes
bytes.com › home › forum › topic › python
memcpy - Python
September 10, 2007 - ArgumentError: argument 1: <type ... enough information so we have to guess. For example I guess the `ones()` function comes from one of the packages `numeric`, `numarray` or `numpy`!? > This function returns a Python object. You can't use arbitrary Python objects with `ctypes`. `memcpy` expects a ...
🌐
Python.org
discuss.python.org › python help
Copying an array of PyObject* - Python Help - Discussions on Python.org
October 1, 2020 - Excuse me for the stupid question in advance. Is it possible to copy a PyObject** objects doing memcpy(new_objects, objects, length * sizeof(PyObject)) instead of using the classical for loop?
🌐
CodeProject
codeproject.com › Questions › 861708 › cplusplus-memcpy-To-Python-memcpy
c++ memcpy To Python memcpy - CodeProject
January 6, 2015 - Internet of Things · C / C++ / MFC> ATL / WTL / STL · Managed C++/CLI · C# Free Tools · Objective-C and Swift · Database · Hardware & Devices> System Admin · Hosting and Servers · Java · Linux Programming · Python · .NET (Core and Framework) Android ·
🌐
Python
bugs.python.org › issue28126
Issue 28126: Py_MEMCPY: Use memcpy on Windows? - Python tracker
September 13, 2016 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/72313
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 60056485 › python-high-speed-memcpy › 60056927
c - Python high speed memcpy - Stack Overflow
I'm trying to do a high speed memcpy in Python. I use the ctypes library which allows me to interact with C programms. I follow this steps: I get the memory address I get the length of the dat...
🌐
Blender Artists
blenderartists.org › coding › python support
Memcpy into image.pixels - Python Support - Blender Artists Community
September 17, 2020 - Hello there, I wrote a bit on lossy compression. So I shove a big block of packed data into my decoder, it spits out an array of floats, now how do I copy these into the pixel array for a Blender image? I know I can just read from a buffer but that’s going to take forever in python.
🌐
GitHub
github.com › python › cpython › issues › 72313
Py_MEMCPY: Use memcpy on Windows? · Issue #72313 · python/cpython
September 13, 2016 - assignee = None closed_at = <Date 2016-09-13.18:23:10.765> created_at = <Date 2016-09-13.12:32:23.695> labels = ['3.7', 'OS-windows', 'performance'] title = 'Py_MEMCPY: Use memcpy on Windows?' updated_at = <Date 2018-04-17.23:39:13.884> user = 'https://github.com/tiran'
Author   tiran
🌐
Stack Overflow
stackoverflow.com › questions › 76516420 › pybind11-memcpy-array-of-values-to-numpy-array
python - pybind11 - memcpy array of values to numpy array - Stack Overflow
June 20, 2023 - /// Mutable pointer access to the ... return &operator()(ssize_t(ix)...); } ... for (std::size_t i = 0; i < num_rows; ++i) std::memcpy(mu.mutable_data(i,0), rows[i].data(), num_cols);...
🌐
Stack Overflow
stackoverflow.com › questions › 41937220 › getting-data-from-c-into-python-with-memcpy
Getting data from C++ into Python with memcpy - Stack Overflow
void RetrieveData::GetData( long FAR* Data ){ memcpy( Data, m_pMeasureData, m_MeasureDataSize * sizeof( long ) ); } This is the C++ function in question which I call in python like so:
🌐
W3Schools
w3schools.com › cpp › ref_cstring_memcpy.asp
C++ cstring memcpy() Function
The memcpy() function is defined in the <cstring> header file. Note: The memcpy() function is generalized for memory of any type.
🌐
FROMDEV
fromdev.com › home › 2026 › april
Memcpy in Data Compression and Deduplication - FROMDEV
3 weeks ago - When it comes to data management, particularly in the realm of data compression and deduplication, efficiency is of paramount importance. One instrumental function that plays a key role in enhancing this efficiency is Memcpy. Memcpy, short for memory copy, is a standard function in most programming languages that is used to copy a block of memory from one location to another.
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › c_function_memcpy.htm
C library - memcpy() function
Python TechnologiesDatabasesComputer ProgrammingWeb DevelopmentJava TechnologiesComputer ScienceMobile DevelopmentBig Data & AnalyticsMicrosoft TechnologiesDevOpsLatest TechnologiesMachine LearningDigital MarketingSoftware QualityManagement Tutorials View All Categories ... The C library memcpy() function is also known as Copy Memory Block function / Memomy to Memory Copy.