Skip to content

Instantly share code, notes, and snippets.

@kurtbrose
Created June 9, 2013 07:31
Show Gist options
  • Select an option

  • Save kurtbrose/5742551 to your computer and use it in GitHub Desktop.

Select an option

Save kurtbrose/5742551 to your computer and use it in GitHub Desktop.
work in progress ctypes back-port of windows socket sharing from Python 3.3 to Python 2.7; eventual use case is cross-process socket pool; maybe even fancier things as well
import ctypes
import struct
import socket
WIN32 = True
if WIN32:
def pass_sock():
pass
def sock2share(sock, pid):
share = ctypes.create_string_buffer(256)
#being cautious on size
err = dup_sock(sock.fileno(), pid, share)
if err:
err = get_err()
raise Exception("WSADuplicateSocketA error: "+str(err))
return share
def share2sock(share, family=None, type=None, proto=None):
x = FROM_PROTOCOL_INFO
sockid = wsa_sock(x, x, x, share, 0, 1) # 1=WSA_FLAG_OVERLAPPED
if family is None:
family = INT.unpack_from(share, WSAPROTOCOL_INFO_FAMILY)[0]
if type is None:
type = INT.unpack_from(share, WSAPROTOCOL_INFO_TYPE)[0]
if proto is None:
proto = INT.unpack_from(share, WSAPROTOCOL_INFO_PROTO)
#everything but this last line works...
#how to convert windows socket id to python socket object?
return socket.socket(family, type, proto, sockid)
dup_sock = ctypes.windll.Ws2_32.WSADuplicateSocketA
get_err = ctypes.windll.Ws2_32.WSAGetLastError
wsa_sock = ctypes.windll.Ws2_32.WSASocketA
FROM_PROTOCOL_INFO = -1 # defined in winsock2.h
#offsets of some fields inside WSAPROTOCOL_INFO struct
WSAPROTOCOL_INFO_FAMILY = 73
WSAPROTOCOL_INFO_TYPE = 85
WSAPROTOCOL_INFO_PROTO = 89
INT = struct.Struct('>L')
def test():
import os
s = socket.socket()
s.connect(('google.com', 80))
s2 = share2sock(sock2share(s, os.getpid()))
return s2
else:
#IOU unix method as well
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment