In this Python article we are going to talk about Socket Programing for Beginners in Python, we will learn how you can create socket in Python, how you can get local machine IP Address, how you can get website IP Address in Python, how to connect TCP client to server and different topics.
What is Socket ?
network socket is a virtual end point where entities can perform inter-process communication. For example, one process sitting in a computer, exchanges data with another process sitting on the same or another computer. We typically label the first process which initiates the communication as the client and the another one as the server. ok now let’s make our first example.
- How to Download YouTube Videos in Python
- Working with Python Pyglet Library
- Python Speech Recognition For Beginners
- PyQtGraph Tutorial in Python
- Convert Python PY File to EXE
How to Create Socket in Python -Python Socket Programing for Beginners
You can use socket.socket() for creating socket in Python, and you need to give some parameters.
Family : This is the domain of socket, such as AF_INET (about 90 percent of the sockets of the Internet fall under this category) or AF_UNIX, which is sometimes used as well. In Python 3, you can create a Bluetooth socket using AF_BLUETOOTH.
Socket type: Depending on your need, you need to specify the type of socket. For example, TCP and UDP-based sockets are created by specifying SOCK_STREAM and SOCK_DGRAM.
Protocol: This specifies the variation of protocol within a socket family and type. Usually, it is left as zero.
1 2 3 4 |
import socket s = socket.socket(family=socket.AF_INET, type = socket.SOCK_STREAM, proto = 0) print("Socket Created {} ".format(s)) |
Run the code and this is the result.
How to Get Local Machine IP Address Using Socket
Sometimes, you need to quickly discover some information about your machine, for example, the host name, IP address, number of network interfaces, and so on. this is very easy to achieve using Python and Socket. so this is the complete code for this example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import socket def main(): hostName = socket.gethostname() ipaddr = socket.gethostbyname(hostName) print(" Host Name Is : {} " .format(hostName)) print(" IP Address Is : {} " .format(ipaddr)) if __name__ == "__main__": main() |
We call the gethostname() method from the socket library for the host name and for IP Address we use gethostbyname().
1 2 |
hostName = socket.gethostname() ipaddr = socket.gethostbyname(hostName) |
In the above code we have imported socket one of Python’s core networking libraries. then, we have used the two utility functions, gethostname() and gethostbyname(host_name). You can type help(socket.gethostname) to see the online help information from within the command line.
Run the complete code and this is the result.
How to Get Website IP Address in Python Socket
Sometimes, you need to translate a machine’s hostname into its corresponding IP Address, for example, a quick domain name lookup. this section introduces a simple function to do that. If you need to know the IP Address of a Website, you can use a built-in library function, gethostbyname(). In this case, you need to pass the remote hostname as its parameter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import socket def main(): remote_host = 'www.geekscoders.com' try: print("IP Address Of " + remote_host + " is " + socket.gethostbyname(remote_host)) except socket.error as e: print("Error " , e) if __name__ == "__main__": main() |
Run the complete code and this is the result.
How to Connect TCP Client Socket in Python
In this part we want to connect TCP client socket in Python, so now this is the complete code for this section. the following code is an example of TCP client socket that makes a connection to server socket.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import socket import sys def main(): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) except socket.error as e: print("Failed To Create A Scoket") print("Reason : ", str(e)) sys.exit() print("Socket Created Successfully") targetHost = input("Please enter target host name to connect: ") targetPort = input("Please enter target port : ") try: s.connect((targetHost, int(targetPort))) print("Socket connected to host " + targetHost + " on port " + targetPort) s.shutdown(2) except socket.error as e: print("Failed connection to host " + targetHost + " on port " + targetPort) print("Reason", str(e)) sys.exit() if __name__ == "__main__": main() |
This line of code is for creating socket in python programming language , also we are handling exceptions for this.
1 |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) |
Also in here we are going to get the input of host name and port from the user.
1 2 |
targetHost = input("Please enter target host name to connect: ") targetPort = input("Please enter target port : ") |
In here we are going to connect our target host to the port.
1 |
s.connect((targetHost, int(targetPort))) |
Run the code give host and port target, this will be the result.
How to Convert IP Address in Python
When you would like to deal with low-level network functions, sometimes, the usual string notation of IP addresses are not very useful. They need to be converted to the packed 32-bit binary formats. the Python socket library has utilities to deal with the various IP address formats. Here, we will use two of them, inet_aton() and inet_ntoa().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import socket from binascii import hexlify def convert_ip(): for ip_addr in ['127.0.0.1', '192.168.0.1']: packed_ip_addr = socket.inet_aton(ip_addr) unpacked_ip_addr = socket.inet_ntoa(packed_ip_addr) print("IP Address : {} => Packed: {}, Unpacked: {} " .format(ip_addr, hexlify(packed_ip_addr), unpacked_ip_addr)) convert_ip() |
The two IP addresses have been converted from a string to a 32-bit packed format using a for-in statement. Additionally, the Python hexlify function is called from the binascii module. This helps to represent the binary data in a hexadecimal format.
Run the code and this is the result
How to set Socket Timeout in Python
Sometimes, you need to manipulate the default values of certain properties of a socket library, for example, the socket timeout. You can make an instance of a socket object and call a gettimeout() method to get the default timeout value and the settimeout() method to set a specific timeout value. This is very useful in developing custom server applications. We first create a socket object inside a socket_time_out() function. Then, we can use the getter/setter instance methods to manipulate timeout values.
1 2 3 4 5 6 7 8 9 10 |
import socket def socket_time_out(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('Default Socket Timeout', s.gettimeout(), s.settimeout(100)) print('Current Socket Timeout', s.gettimeout()) socket_time_out() |
Run the code and this is the result.
So we can say that Python socket programming is powerful tool for network communication, and learning it is essential for any aspiring network programmer. this tutorial on Python socket programming for beginners covers the basics of socket programming in Python, including examples and concepts that are easy to understand. with this tutorial beginners can learn how to create simple socket programs in Python, implement socket clients and servers, and understand the underlying socket programming concepts.