Create_connection() In Python

Function Name:



Function signature:

socket.create_connection(address[, timeout[, source_address]])


Function Overview:

  • create_connection() function only connects to a TCP socket and it cannot be used to connect to a Datagram socket or any other type.
  • This function is like a specialized wrapper over the socket.connect() function.
  • The address parameter of this function takes IPv4 , IPv6 addresses as well as host names. Remember that, you cannot connect to a server socket that was created using the address family AF_INET by passing an IPv6 address to create_connection().
  • To use create_connection() to connect to a IPv6 address the server socket also should have been created using the address family AF_INET6.


address: The destination address to which the socket wants to connect to. The address is a tuple of IP address and a port.

timeout: Timeout value in seconds. When not specified it takes the timeout value as returned by the method socket.getdefaulttimeout()

source_address: Timeout value in seconds


# Sample program for CreateConnection


import socket


# Create a socket to be used a client


timeout = socket.getdefaulttimeout()

print("System has default timeout of {} for create_connection".format(timeout))

socketInstance = socket.create_connection(("localhost",35491))


bytes2Send       = str.encode("Hello server system!")



# Receive the data


    data = socketInstance.recv(1024)




        print("Connection closed")





  • The above python program uses create_connection() to connect to the TCP server socket listed in the client-server example. The TCP server code has been modified so that the server socket is created using address family AF_INET6 and binds to the IPv6 address ::1 and port number 35491.
  • Using sendall() it sends a message to the TCP server
  • It receives the messages sent by the server in a while loop till the server socket closes the client connection and prints the messages to the console.


System has default timeout of 10.0 for create_connection

b'Hi Client! Read everything you sent'

b'Now I will close your connection'


Connection closed


Copyright 2023 ©