Created
March 20, 2020 19:14
-
-
Save vsajip/0d1ff9d6e94561cc7f4466dbcf86748c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from ctypes import * | |
from ctypes.wintypes import (HANDLE, ULONG, DWORD, BOOL, LPCSTR, LPCWSTR, WORD, | |
USHORT) | |
import msvcrt | |
import platform | |
import sys | |
#------------------------------------------------------------------------------ | |
# WinSock2 definitions | |
#------------------------------------------------------------------------------ | |
WSADESCRIPTION_LEN = 256 | |
WSASYS_STATUS_LEN = 128 | |
class WSADATA(Structure): | |
_fields_ = [ | |
("wVersion", WORD), | |
("wHighVersion", WORD), | |
("szDescription", c_char * (WSADESCRIPTION_LEN+1)), | |
("szSystemStatus", c_char * (WSASYS_STATUS_LEN+1)), | |
("iMaxSockets", c_ushort), | |
("iMaxUdpDg", c_ushort), | |
("lpVendorInfo", c_char_p), | |
] | |
WSAStartup = windll.Ws2_32.WSAStartup | |
WSAStartup.argtypes = (WORD, POINTER(WSADATA)) | |
WSAStartup.restype = c_int | |
def MAKEWORD(bLow, bHigh): | |
return (bHigh << 8) + bLow | |
def init_winsock(): | |
wsaData = WSADATA() | |
LP_WSADATA = POINTER(WSADATA) | |
ret = WSAStartup(MAKEWORD(2, 2), LP_WSADATA(wsaData)) | |
if ret != 0: | |
raise Exception('WSAStartup failed: %s' % ret) | |
GROUP = c_uint | |
SOCKET = c_uint | |
WSASocket = windll.Ws2_32.WSASocketA | |
WSASocket.argtypes = (c_int, c_int, c_int, c_void_p, GROUP, DWORD) | |
WSASocket.restype = SOCKET | |
AF_INET = 2 | |
SOCK_STREAM = 1 | |
IPPROTO_TCP = 6 | |
WSA_FLAG_OVERLAPPED = 0x01 | |
INVALID_SOCKET = ~0 | |
def make_socket(): | |
result = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, None, 0, | |
WSA_FLAG_OVERLAPPED) | |
if result == INVALID_SOCKET: | |
raise Exception('Socket creation failed') | |
return result | |
closesocket = windll.Ws2_32.closesocket | |
closesocket.argtypes = (SOCKET,) | |
closesocket.restype = c_int | |
def main(): | |
print(sys.version) | |
print(platform.platform()) | |
init_winsock() | |
sock = make_socket() | |
for i in (0, 1, 2): | |
print('fd %s -> handle %s' % (i, msvcrt.get_osfhandle(i))) | |
try: | |
msvcrt.get_osfhandle(sock) | |
except Exception as e: | |
print('open socket %s: %s' % (sock, e)) | |
closesocket(sock) | |
try: | |
msvcrt.get_osfhandle(sock) | |
except Exception as e: | |
print('closed socket %s: %s' % (sock, e)) | |
print('Trying bad integer handle values to see if we can get a crash:') | |
for i in range(-8192, 8192): | |
try: | |
msvcrt.get_osfhandle(i) | |
except Exception: | |
pass | |
print('No crash.') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment