Book Image

Learning Python Network Programming

By : Dr. M. O. Faruque Sarker, Samuel B Washington, Sam Washington
Book Image

Learning Python Network Programming

By: Dr. M. O. Faruque Sarker, Samuel B Washington, Sam Washington

Overview of this book

Table of Contents (17 chapters)
Learning Python Network Programming
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Working with TCP sockets


Creating a socket object in Python is very straightforward. You just need to import the socket module and call the socket() class:

from socket import*
import socket

#create a TCP socket (SOCK_STREAM)
s = socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0)
print('Socket created')

Traditionally, the class takes plenty of parameters. Some of them are listed in the following:

  • Socket 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, respectively.

  • Protocol: This specifies the variation of protocol within a socket family and type. Usually, it is left as zero.

For many reasons, socket operations may not be successful...