Unable to Create Tcp Socket: Address Family Not Supported by Protocol Godaddy Hosting
Python Socket Advice
What is a socket?
A socket is one endpoint of a 2-manner advice link between two programs running on ( a node in) a computer network. I socket (the server) listens on a particular port on and IP accost, while another socket(the client) connects to the listening server to accomplish communication.
Primarily, the mode sockets send data is controlled by two properties — the address family, which determines the network layer protocol used and the socket type which determines the transport layer protocol used.
In this article, we will be learning how to apply Python's socket module (socket
) — which is an interface to the Berkey sockets API, a low-level socket interface implemented past most modern operating systems. All examples and code samples in this commodity are written in Python 3.six.
Socket Types
Depending on the transport layer protocol used, sockets tin can either be:
-
SOCK_DGRAM
for message-oriented datagram transport. These sockets are commonly associated with the User Datagram Protocol (UDP) which provides an unreliable delivery of individual letters. Datagram sockets are commonly used when the order of messages is not important, such equally when sending out the same data to multiple clients. -
SOCK_STREAM
for stream-oriented transport frequently associated with the Transmission Control Protocol (TCP). TCP provides a reliable and ordered delivery of byte between two host, with error handling and control, making it useful for implementing applications that involve transfer of large amounts of data.
An Overview of The Sockets Module
To utilize sockets in Python we volition need to import the socket
module.
>>> import socket
The principal way of using the sockets module is through the sockets()
function which returns a socket object with methods to implement diverse arrangement socket calls. Python sockets supports a number of address families nether the network layer protocol, mainly:
-
AF_INET
— this is the most common, and uses IPv4 for network addressing. Most of the internet networking is presently done using IPv4. -
AF_INET6
— this is the next generation of the internet protocol using IPv6 and provides a number of features not available under IPv4. -
AF_UNIX
— finally, this is the accost family unit for Unix Domain Sockets (UDS), an inter-process advice protocol available on POSIX-compliant systems. This implementation allows passing of data between processes on an operating system without going through the network.
Network related services
In this section we will look at some socket
functions and methods that provide access to network related tasks.
-
gethostname()
to get the official name of the electric current host.
>>> import socket
>>> print(socket.gethostname())
rodgers-PC
-
gethostbyname()
converts the name of a server into its numerical address by consulting the operating system's DNS configuration.
>>> import socket
>>> print(socket.gethostbyname("google.com"))
216.58.223.78
-
gethostbyname_ex()
to become more naming data about a server.
>>> import socket
>>> proper noun, aliases, addresses = socket.gethostbyname_ex("google.com")
>>> impress("Name: ",name)
Name: google.com
>>> impress("Aliases: ",aliases)
Aliases: []
>>> print("Addresses: ",addresses)
Addresses: ['216.58.223.78']
-
gethostbyaddr()
to perform a reverse lookup for a domain's name. -
getfqdn()
to convert a partial domain into a fully qualified domain name.
More network-related functions can be accessed from the python documentation referenced in the conclusion section below.
TCP/IP client-server communication
Equally we have established, sockets tin either exist configured to act as a server or customer, to achieve bi-directional communication over TCP using the SOCK_STREAM
family. In this example, we shall implement a elementary echo application that receives all incoming information and sends them back to the sender. For that nosotros will implement both customer and server sockets. Furthermore, we volition use the local loopback address 127.0.0.ane
or localhost
for our connections.
Echo Server
To ready a server, information technology must perform the sequence of methods socket()
, bind()
, listen()
, and accept()
.
-
socket()
creates a new socket given the accost family and a socket type. -
bind()
binds our socket object to a detail address composed of a host and port number. -
listen()
allows the server to get-go accepting connections and takes in an statement,backlog
, which is the number of unaccepted connections that the organisation can allow earlier refusing all new connections. -
accept()
accepts incoming connections and returns a a tuple of(conn, accost)
whereconn
is a new socket that can exist used to send and receive messages from the connectedness andaddress
is the address bound to the socket on the other end of the connectedness. -
shut()
marks the socket every bit closed and can no longer have connections.
Nosotros initialize a socket object, sock
by passing in the address family unit ( socket.AF_INET
) and socket type ( socket.SOCK_STREAM
) to the socket.socket()
function.
- Adjacent, we bind the socket object to an address of the class
('localhost',10000)
— bind tolocalhost
on port10000
, using thebind()
method. - Listen for incoming connections with a excess of i.
- Continuously wait for and accept connections by calling
sock.take()
and unpacking the return value intoconnection
andclient_address
. - Call
recv(xvi)
on the returned connection to receive the data on chunks of 16. - If data as been received, then we transmit the received data back to the sender by calling the method
sendall(information)
on the connection, otherwise we print out a argument indicating no information has been received. - Finally when advice with the client is complete — all the chunks of the message accept been transmitted, nosotros call
close()
on the connection object. We employ atry/finally
cake to ensure thatclose()
is called even in the issue of an error when transmitting messages.
Echo Customer
Unlike a server, a client only needs to execute the sequence of socket()
and connect()
.
-
connect()
connects the socket to an address.
In this case:
- Nosotros initialize a socket object as in the server.
- Next nosotros connect the socket to the same address that the server is listening on, in this instance,
('localhost',10000)
, using theconnect(address)
method. - In a
endeavour/finally
block, we compose our message as a byte string and employsendall()
method on the socket object with the bulletin as an argument. - We and so ready upward variables
amount_received
with an initial value of 0 andamount_expected
which is simply the length of our message, to keep rails of the message chunks equally we receive them. - Calling
recv(16)
on the socket object allows usa to receive the message from our server in chunks of 16, and nosotros proceed receiving untilamount_received
is equal toamount_expected
. - Finally nosotros mark the socket equally closed.
Running out server and customer scripts on separate terminal windows, this is the output from the server;
$ python3 echo_server.py Starting up on localhost port 10000
waiting for a connectedness
connection from ('127.0.0.1', 49964)
received b'This is our mess'
sending information back to the client
received b'age. It is very '
sending data back to the client
received b'long but will on'
sending information back to the client
received b'ly exist transmitte'
sending data dorsum to the client
received b'd in chunks of i'
sending data back to the client
received b'6 at a time'
sending information dorsum to the client
received b''
no information from ('127.0.0.i', 49964)
Closing current connection
waiting for a connection
And the client;
$ python3 echo_client.py connecting to localhost port 10000
sending b'This is our message. It is very long but will simply be transmitted in chunks of sixteen at a fourth dimension'
received b'This is our mess'
received b'age. It is very '
received b'long simply will on'
received b'ly be transmitte'
received b'd in chunks of 1'
received b'6 at a fourth dimension'
closing socket
UDP client-server communication
Unlike the example with TCP manual which streams messages in an ordered manner, UDP is message oriented and does not require a long-lived connection. A message in this case has to fit within a unmarried datagram and delivery is non assured.
Repeat Server
Here, we'll but execute the socket()
and bind()
sequence since, there isn't really a connectedness to listen for. Instead nosotros only need to bind the socket to a particular address and await for incoming letters. Nosotros volition then read the incoming messages using the recvfrom()
method and send them back with sendto()
.
-
recvfrom()
receives data from a socket and return a tuple of(bytes, address)
wherebytes
is a bytes object containing the received data andaccost
is the accost of the sender. -
sendto(bytes,address)
sends information(given bybytes
) to a socket jump to the address every bit defined byaccost
.
In the example above:
- We create a socket object using
socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
. Please notation that here nosotros use thesocket.socket_DGRAM
socket type since we are using UDP. - Adjacent we bind the socket to the
('localhost',10000)
and wait for incoming messages. - When a message arrives, nosotros proceed to read it with
recvfrom(4096)
, where 4096 is the number of bytes to exist read, and unpack the return value in todata
andaccost
.At this bespeak we tin can print out the length ofinformation
. - If some information has been received, nosotros send information technology back to the sender using the
sendto()
method and impress out the length of the return value — which is the sent data.
Repeat Client
This client is similar to the server above, only that it doesn't bind the socket to whatsoever address. Instead, the it uses sendto()
to send messages to the server'due south address.
In the script:
- We instantiate a sock object as in the server above.
- We and so compose a message every bit a byte string, and define a
server_address
every bit a tuple of the host and the port number jump to the server we wish to send messages to. - Inside a
endeavor/finally
block, we send the bulletin and wait for a response, printing the the information in both cases. - Finally we mark the socket as closed.
This is the output when the customer and server scripts are run on the server:
$ python3 echo_server_udp.py starting up on localhost port 10000 waiting to receive bulletin
received 48 bytes from ('127.0.0.1', 34351)
b'This is our message. It volition exist sent all at once'
sent 48 bytes dorsum to ('127.0.0.1', 34351) waiting to receive message
And the customer:
$ python3 echo_client_udp.py sending b'This is our bulletin. It will be sent all at once'
waiting to receive
received b'This is our message. It will exist sent all at once'
closing socket
Unix Domain Sockets
These are largely similar to TCP sockets with basically 2 exceptions:
- The socket address in this case is a path on the file system such equally
./socket_file
unlike in the TCP sockets where the accost was a tuple of a host name and a port number. - Since the node created to represent the socket is a file, information technology persists even after the socket is closed, and as such it's supposed to be removed whenever the server starts up.
To implement a similar client-server communication setup with UDS, nosotros would demand to slightly modify the example of TCP above.
Echo Server
Here we modify the server_address
variable in the script to a file system path, in this case ./socket_file
.
Since nosotros likewise need to brand sure the node doesn't already exist when starting the server, we use a try/except
block to delete the file using os.unlink()
if it exists.
Echo Customer
In this case, we also supersede the server_address
variable to the file path that has been spring to the server.
Running the client and server results in an output nearly similar to the TCP example. For the server we get:
$ python3 echo_server_uds.py Starting up on ./socket_file
waiting for a connection
connection from
received b'This is our mess'
sending data back to the customer
received b'age. It is very '
sending information back to the customer
received b'long just will on'
sending data back to the client
received b'ly be transmitte'
sending data dorsum to the customer
received b'd in chunks of ane'
sending data back to the client
received b'six at a fourth dimension'
sending data back to the client
received b''
no data from
Closing current connection
waiting for a connectedness
And the customer:
$ python3 echo_client.uds.py connecting to ./socket_file
sending b'This is our message. It is very long but will only be transmitted in chunks of 16 at a time'
received b'This is our mess'
received b'age. Information technology is very '
received b'long but will on'
received b'ly be transmitte'
received b'd in chunks of 1'
received b'half-dozen at a time'
endmost socket
Permissions
Since UDS sockets are represented by nodes on the the file system, this implies that standard file system permissions can exist used to control access to the server. For instance, lets attempt to change the buying of the existing node to a root user.
$ ls -la ./socket_file
srwxr-xr-ten 1 rodgers rodgers 0 Nov 1 15:24 ./socket_file
$ sudo chown root ./socket_file
$ ls -la ./socket_file srwxr-xr-ten ane root rodgers 0 Nov 1 xv:24 ./socket_file
$ python3 echo_client.uds.py
connecting to ./socket_file
[Errno 13] Permission denied
As nosotros can encounter, connecting to the server as a regular user fails, meaning only a user with the correct permissions (in this instance the root user), can access the server.
Dealing with Multiple connections — Multicast
When dealing with multiple clients, maintaining several point-to-indicate connections can exist cumbersome for applications due to the increases bandwidth and processing needs. This is where multicast messages come in. With multicast, messages are delivered to multiple endpoints simultaneously. This method achieves increased efficiency since commitment of messages to all recipients is delegated to the network infrastructure.
Multicast messages are sent using UDP, since TCP assumes a pair of communicating endpoints. The addresses for multicast messages, identified as multicast groups, are a subset of IPv4 addresses, usually between the range of 224.0.0.0 to 239.255.255.255. Network routers and switches treat addresses in this range as special since they are reserved for multicast, ensuring messages sent to the grouping are distributed to all clients that join the group.
Ship Multicast Messages
To send letters we utilise an ordinary sento()
method with a multicast grouping as the address. Moreover, we besides need to specify a Fourth dimension To Live(TTL) value which determines how far the letters should be broadcast from the sender. The default TTL of one, will issue in messages beingness sent just to hosts within the local network. Nosotros shall use setsockopt()
with the IP_MULTICAST_TTL
option to set the TTL, which should be packed into a single byte.
We shall also set up a timeout value on the socket, to prevent it from waiting indefinitely for responses, since we accept no idea how many responses nosotros expect to become from the network.
In this instance:
- We create a socket of type
socket.SOCK_DGRAM
, etch or message equally a byte string and bind our socket to the multicast group address('224.x.10.10', 10000)
. - Nosotros and so set a timeout of
0.2
usingsock.settimeout(0.two)
. - Using the
struct
module, nosotros pack the number i into a byte and assign the byte tottl
. - Using
setsockopt()
we ready theIP_MULTICAST_TTL
option of the socket to thettl
we just created above and send the message usingsendto()
. - We then wait for responses from other hosts on the network, every bit long as the look hasn't timed out and print out the responses.
Receiving Multicast Letters
To receive messages, after creating our ordinary socket and bounden it to a port, we would demand to add it to the multicast group. This can be washed by using the setsockopts()
to set the IP_ADD_MEMBERSHIP
option, which should be packed into an 8-byte representation of the multicast group, and the network interface on which the server should heed for connections. We shall use socket.inet_aton()
to convert the multicast group IPv4 accost from dotted-quad cord format ('224.ten.10.10'
) to 32-fleck packed binary format.
In this example:
- To add the socket to the multicast group, we utilize
struct
to pack the group address given bysocket.inet_aton(multicast_group)
and the network interface given pastsocket.INADDR_ANY
into an 8-byte representation, which nosotros then ready to the socket'due southIP_ADD_MEMBERSHIP
. - As the socket receives letters, we use
recvfrom(1024)
to unpack the response intoinformation
andaccost
, and transport out an acknowlegement to theaccost
usingsendto()
.
On running both scripts, on dissimilar hosts (A and B), this is the output of the multicast sender on Host A:
[A]$ python3 multicast_sender.py sending b'very of import data'
waiting to receive
received b'ack' from ('192.168.100.2', 10000)
waiting to receive
received b'ack' from ('192.168.100.13', 10000)
waiting to receive
timed out, no more responses
closing socket
And receiver on Host B:
[B]$ python3 multicast_receiver.py waiting to receive message
received 19 bytes from ('192.168.100.2', 48290)
b'very important data'
sending acknowledgement to ('192.168.100.ii', 48290) waiting to receive bulletin
Sending Binary Information
And then far we have been transmitting streams of text data encoded as bytes through our sockets. Sockets tin can also transmit binary data every bit streams of bytes. Nosotros can utilise struct
to pack the binary data to prepare it for transmission. However, when sending multi-byte data, it is important that both sender and recipient know the order in which the bytes are. This is useful in reconstructing the bytes at the recipient's end.
Binary Client
Nosotros shall at present implement a binary client that sends an integer, a cord and a floating point number past packaging the data into a serial of bytes.
Here nosotros ready a socket of blazon socket.SOCK_STREAM
and connect information technology to our server address. We and then use a struct.Struct('I 2s f')
specifier to pack the data before sending with sendall()
.
Binary Server
On the other hand nosotros have a server, that listens on the server address for incoming connections. Later accepting a connectedness and receiving data nosotros then proceed to unpack the data using a struct.Struct('I 2s f')
specifier. Annotation that we apply the same specifier on both ends of the advice and then that the received bytes are interpreted in the same order they were packed.
The output nosotros go from the client:
$ python3 binary_client.py values = (1, b'ab', 2.vii)
sending b'0100000061620000cdcc2c40'
endmost socket
And the server:
$ python3 binary_serverr.py waiting for a connexion
received b'0100000061620000cdcc2c40'
unpacked: (ane, b'ab', 2.700000047683716) waiting for a connection
From the server output, the floating point numbers loses some precision as a issue of packing and unpacking. Otherwise everything else is transmitted as is.
Blocking and Timeouts
By default, sockets operate in a blocking mode. This means that sending or receiving data pauses execution of the program until the the socket that'southward receiving or sending information is ready. Sometimes, this mode of operation can result in a dreadlock whereby both endpoints are waiting for the other to send or receive data.
To try and overcome this challenge, sockets take an choice to unset blocking, using the method socket.setblocking()
, which has a default value of 1, i.east blocking is on. To disable blocking nosotros call socket.setblocking(0)
. Withal, this presents notwithstanding another challenge; if a socket is not gear up for an performance with blocking disabled, then a socket.error
is raised.
Another solution therefore, involves setting a timeout, using socket.settimeout(float)
to a number(float
) of seconds during which blocking is on before evaluating whether the socket is ready or non. This timeout method is applicable in most cases since it acts every bit a compromise between blocking and not blocking.
Troubleshooting
As we tin can all attest to, some times things don't work and more often than not, information technology's never obvious why. It could be a issue with the code in which instance looking at the errors and traceback could bespeak usa in the right management. In such cases, referring to the official documentation would exist the first option.
However, sometimes it could exist configuration troubles on the client, server, or fifty-fifty the network infrastructure. To probe such problems nosotros could use ping
or netstat
to identify the source of problems.
-
ping
— works directly with the TCP/IP stack, independent of any other application running on a host, to decide the condition of the host, whether information technology's upwards or not.ping
works by sending ICMP echo request packets to the target host and waiting for an ICMP echo reply.
Below is an case of ping running on Ubuntu:
$ ping -c iv 127.0.0.1 PING 127.0.0.i (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.055 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=three ttl=64 time=0.077 ms
64 bytes from 127.0.0.one: icmp_seq=4 ttl=64 time=0.067 ms --- 127.0.0.1 ping statistics ---
4 packets transmitted, four received, 0% packet loss, time 3057ms
rtt min/avg/max/mdev = 0.055/0.066/0.077/0.011 ms
-
netstat
—gives information sockets and their electric current states. Permit'due south fire up the TCP echo server and observe the output ofnetstat
. From this we tin can tell that our server is presently using thetcp
protocol, listening (state ofLISTEN
) on port10000
and host127.0.0.1
.
$ netstat -an Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:10000 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.53:53 0.0.0.0:* Mind
Decision
Nosotros have covered quite a number of concepts in this article. Notwithstanding sockets and networking are very broad and it is not possible to cover everything in a single article. To have a ameliorate understanding of these concepts, information technology is imperative that nosotros practise more. The socket
module in item has and so many methods, functions and attributes that nosotros haven't covered, please feel free to refer to the official documentation. The internet also besides a lot of information on socket programming and networking in general.
Thanks for your time!
Source: https://medium.com/python-pandemonium/python-socket-communication-e10b39225a4c
Post a Comment for "Unable to Create Tcp Socket: Address Family Not Supported by Protocol Godaddy Hosting"