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
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › write-memcpy
Write your own memcpy() and memmove() - GeeksforGeeks
February 18, 2026 - The memcpy function is used to copy a block of data from a source address to a destination address.
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.

🌐
CodeProject
codeproject.com › Questions › 861708 › cplusplus-memcpy-To-Python-memcpy
c++ memcpy To Python memcpy - CodeProject
January 6, 2015 - Free source code and tutorials for Software developers and Architects.; Updated: 7 Jan 2015
🌐
Python
wiki.python.org › moin › ctypes
ctypes - Python Wiki
FAQ: How do I say memcpy? ctypes.memmove · (Remember the difference in argument order between memmove and memcpy.) FAQ: How do I say offsetof?
🌐
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
🌐
W3Schools
w3schools.com › cpp › ref_cstring_memcpy.asp
C++ cstring memcpy() Function
memcpy(void * destination, void * source, size_t size); The size_t data type is a positive integer. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you ...
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › c_function_memcpy.htm
C library - memcpy() function
Home Whiteboard Practice Code Graphing Calculator Online Compilers Articles Tools ... 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.
🌐
Aticleworld
aticleworld.com › home › implementation of memcpy in c language
Implementation of memcpy in C language - Aticleworld
December 11, 2023 - The memcpy function copies n characters from the source object to the destination object. If the source and destination objects overlap, the behavior of memcpy is undefined.
Find elsewhere
🌐
Debian
sources.debian.org › src › glibc › 2.28-8 › string › memcpy.c
File: memcpy.c | Debian Sources
sources / glibc / 2.28-8 / string / memcpy.c · package info (click to toggle) glibc 2.28-8 · links: PTS, VCS · area: main · in suites: buster · size: 271,788 kB · sloc: ansic: 1,008,637; asm: 259,607; makefile: 11,271; sh: 10,477; python: 6,910; cpp: 4,992; perl: 2,258; awk: 2,005; yacc: ...
🌐
Post.Byes
post.bytes.com › home › forum › topic › python
memcpy - Post.Byes - Bytes
September 10, 2007 - How do I memcpy from a pointer to an array of floats in python? I get errors: NameError: global name 'row' is not defined I want to be able to get the row[i] array element. In C I would normally place the address of row as the first argument. cdll.msvcrt.memcpy( row, pData, 256 ) If I define row as the following I also get
🌐
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?
🌐
GitHub
github.com › nadavrot › memset_benchmark
GitHub - nadavrot/memset_benchmark: This repository contains high-performance implementations of memset and memcpy in assembly. · GitHub
This repository contains high-performance implementations of memset and memcpy in assembly. - nadavrot/memset_benchmark
Starred by 342 users
Forked by 18 users
Languages   Assembly 38.8% | C++ 32.1% | C 23.3% | CMake 5.8%
🌐
Cerebras
sdk.cerebras.net › csl › tutorials › gemv-03-memcpy
GEMV Tutorial 3: Memcpy — SDK Documentation (1.3.0)
The host code is largely similar to the previous tutorials, except we now must copy A, x, and b to the device after initializing them on the host. We do this with memcpy_h2d, which has similar syntax to the previously introduced memcpy_d2h. We include our modified run.py below. #!/usr/bin/env cs_python import argparse import numpy as np from cerebras.sdk.runtime.sdkruntimepybind import SdkRuntime, MemcpyDataType, MemcpyOrder # pylint: disable=no-name-in-module # Read arguments parser = argparse.ArgumentParser() parser.add_argument('--name', help="the test compile output dir") parser.add_argume
🌐
GitHub
github.com › python › cpython › issues › 72313
Py_MEMCPY: Use memcpy on Windows? · Issue #72313 · python/cpython
September 13, 2016 - activity = <Date 2018-04-17.23:39:13.884> actor = 'gitinit.py@gmail.com' assignee = 'none' closed = True closed_date = <Date 2016-09-13.18:23:10.765> closer = 'christian.heimes' components = ['Windows'] creation = <Date 2016-09-13.12:32:23.695> creator = 'christian.heimes' dependencies = [] files = [] hgrepos = [] issue_num = 28126 keywords = [] message_count = 15.0 messages = ['276262', '276271', '276306', '276309', '276310', '276313', '276314', '276317', '276413', '276426', '276433', '276435', '276436', '276464', '315427'] nosy_count = 9.0 nosy_names = ['paul.moore', 'vstinner', 'christian.h
Author   tiran
🌐
Linux Man Pages
man7.org › linux › man-pages › man3 › memcpy.3.html
memcpy(3) - Linux manual page
The memcpy() function copies n bytes from memory area src to memory area dest. The memory areas must not overlap.