Skip to content

Networking

Socket

Creating a socket

from socket import *

s = socket(socket.AF_INET, socket.SOCK_STREAM) #SOCK_STREAM for TCP, SOCK_DGRAM for UDP

Creating a TCP socket connection

Server

from socket import *

s = socket(AF_INET, SOCK_STREAM)
s.bind(('0.0.0.0', 8080))
s.listen(5) # 5 is the maximum number of queued connections
while True:
    conn, addr = s.accept()
    data = conn.recv(1024).decode()
    print(data)
    conn.send('Hello from server'.encode())
    conn.close()

Client

s = socket(AF_INET, SOCK_STREAM)
s.connect(('0.0.0.0', 8080))
s.send('Hello from client'.encode())
data = s.recv(1024).decode()
print(data)
s.close()

Creating a UDP socket connection

Server

from socket import *

s = socket(AF_INET, SOCK_DGRAM)
s.bind(('0.0.0.0', 8080))
while True:
    data, addr = s.recvfrom(1024)
    print(data.decode())
    s.sendto('Hello from server'.encode(), addr)

Client

s = socket(AF_INET, SOCK_DGRAM)
s.sendto('Hello from client'.encode(), ('0.0.0.0', 8080))
data, addr = s.recvfrom(1024)
print(data.decode())

SMTP

Sending an email

import smtplib
s = smtplib.SMTP('smtp.gmail.com', 587) # connecting to the server
s.starttls()
s.login("sender_email_id", "sender_email_id_password")

message = "Message_you_need_to_send"
s.sendmail("sender_email_id", "receiver_email_id", message)

s.quit()