Socket Programming with Python | All you should know about socket Programming

Socket programming is an important concept in the world of computer programming. When we are sending or receiving data between two communication links, we need to use socket programming. 

What is Socket Programming?

Socket programming tells us how to create a link between the local and remote processes by using the sockets. Now you might be thinking what do you mean by sockets, will socket is a communications endpoint that you can name and address in a network. To learn more about socket Programming in general you can visit the IBM Article on Socket Programming. It is super informative.

Socket-programming

Socket Programming with Python 

Although there is a high-level library in python which makes it easy for us to do Socket programming. for example, the requests module, which can help us communicate to the endpoints very easily than we can think of. 

Python Socket Library

The socket library is one of the python standard libraries for socket programming, which makes it easy to do socket programming, in a few lines. although you do not have the control over all the sockets that one can have with a low-level programming language as c and c++, where you have complete access to the low level of sockets. although there are certain limitations in socket programming with the python programming language, still we have a socket that makes networking very easy for us.

In the next few lines, I will introduce you, how we can actually write code that can help us create communications to a remote server. 

How to get the IP Address of a domain with socket python?

To get the IP address of a domain with the socket we can use the following code snippets.



    import socket
    ip = socket.gethostbyname('www.alixaprodev.com')
    print (ip)
    # output 
    # 142.250.180.51

The above is a simple program that gives us the ip address of a domain. this is not the basic purpose of socket programming. Socket programming is used to create a connection between the two processes, whether on the same computer or on the remote computer. We will see what we can do with socket programming in the next sections and we will create a server-client application where the client will send the data to the server. to make things simple we will just send a text but you can send files and whatever data you have. 

Create a server and client to send data with Python?

We can create a server and a client locally on our computer for testing purposes that can send and receive the data. we can do so by creating one program for the client and one program for the server. 

On our server-side, we will be waiting for the connection and when we receive the connection we will send a text to our client and print it on a terminal.

Creating our server that will wait for the connection.

The service will keep waiting for the connection unless one process is connected to this server.

We can do so by using the while loop once a clint is connected it will just send the text data and will exit the while loop and the server will be shut down.



    import socket
    s = socket.socket()
    port = 34541
    host = socket.gethostname()
    ip = socket.gethostbyname(host)
    
    s.bind(('', port))
    print (f"sever create on {ip}:{port}")
    s.listen(2)
    
    while True:
        clirn, addr = s.accept()
        print ('Connected to', addr )
        clirn.send('Data from the server'.encode())
        clirn.close()
        break
    

Creating Clint Program with Socket using Python. 


    import socket
    s = socket.socket()
    port = 34541
    s.connect(('10.48.57.254', port))
    print(s.recv(1024).decode())
    s.close()
    
    
    

A few Important methods in Python socket Library

  1. socket.accept()

    Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.
  2. socket.bind(address)

    Bind the socket to address. The socket must not already be bound.
  3. socket.close()

    Mark the socket closed. The underlying system resource (e.g. a file descriptor) is also closed when all file objects from makefile() are closed. Once that happens, all future operations on the socket object will fail. The remote end will receive no more data (after queued data is flushed). Sockets are automatically closed when they are garbage-collected, but it is recommended to close() them explicitly or to use a with statement around them. Changed in version 3.6: OSError is now raised if an error occurs when the underlying close() call is made.
  4. socket.connect(address)

    Connect to a remote socket at the address. (The format of address depends on the address family — see above.) If the connection is interrupted by a signal, the method waits until the connection completes, or raise a TimeoutError on timeout, if the signal handler doesn’t raise an exception and the socket is blocking or has a timeout. For non-blocking sockets, the method raises an InterruptedError exception if the connection is interrupted by a signal (or the exception raised by the signal handler).
  5. socket.connect_ex(address)

    Like connect(address), but return an error indicator instead of raising an exception for errors returned by the C-level connect() call (other problems, such as “host not found,” can still raise exceptions). The error indicator is 0 if the operation succeeded, otherwise the value of the errno variable. This is useful to support, for example, asynchronous connects.
  6. socket.detach()

    Put the socket object into closed state without actually closing the underlying file descriptor. The file descriptor is returned, and can be reused for other purposes.
  7. socket.getpeername()

    Return the remote address to which the socket is connected. This is useful to find out the port number of a remote IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.) On some systems this function is not supported.
  8. socket.getsockname()

    Return the socket’s own address. This is useful to find out the port number of an IPv4/v6 socket, for instance.
  9. socket.listen([backlog])

    Enable a server to accept connections. If the backlog is specified, it must be at least 0 (if it is lower, it is set to 0); it specifies the number of unaccepted connections that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen.

Post a Comment

0 Comments