Python Socket Programming

0x00 For Server

​ Firstly , you should start a TCP/IP socket.So,what’s the Socket?

​ A socket is an endpoint of a two-way communication link between two programs running on the network. It’s bound to a port number and TCP or IP protocol. It means every process has only one port and tranport layer protocols .When there are two different computers, it also need to know the IP adress of the other host .the socket is an interface that one program communicate with another program. For upper layer, they don’t need to know how it works ,you don’t need to know how TCP establish connection by three-way handshake and terminate connection by four waves,if they want to send or receive messages ,they only need to import socket. Python provides an api for developers to use a socket.

1
2
3
import socket
#Create a TCP/IP socket
sock = socket .socket(socket.AF_INET, socket.SOCK_STREAM)

socket format :socket.socket(family, type[,potocal])

socket type:

socket.AF_UNIX: Is used to communicate between processes on the same machine efficiently

socket.AF_INET: Is used to communicate between processes over a IPV4 network

socket.AF_INET6: Is used to communicate between processes over a IPV6 network

socket.SOCK_STREAM: Connection which is based on the TCP

socket.SOCK_DGRAM: Connection which is based on the UDP

sock.SOCK_RAM: Receive or send the raw datagram not including link level headers

sock.SOCK_SEQPACKET: It will guarantee that message emission would correspond to a single and complete message reception.

After that ,you need to use bind() to associate the socket with the service address (For TCP ,you need an IP adress and port number)

1
2
3
# bind the socket to your port
server_adress = ('localhost',9876)
socket.bind(server_adress) #use bind() method

​ With us build a socket ,we need to use listen(int backlog) method to monitor passive data.

​ For the parameter in the listen(),it means the max connection for this operating system at the same time.(at least use 1,most use 5)

1
2
sock.listen(1)
# listen for incoming connections

​ Accept() method is used to accept the data after you listen a connection.However ,you need to keep accept state,for the data is sent continuously.Therefore, there is supposed to use while True to keep accept().

​ As for why I use two while True,for the first one ,it’s used to keep TCP connection, after one connection close ,it will keep accept for other TCP connection.For the second one ,it’s used to keep accepting message,after one message received, it will keep receiving other message until no message is sent.

​ At last , using close() method to close the socket connection.

C/S

Server code:

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
import socket


def connect(address, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a TCP socket
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)#reuse the port, avoid to waiting
server_address = (address, port)
sock.bind(server_address) #Bind in server adress
sock.listen(5) #Keep listening
print("server is running")
while True:
conn, addr = sock.accept() #Keep accepting,it will return a tuple
print('connected by ', addr)
while True:
data = conn.recv(1024) # Recive message
if not data:
break
print(data.decode())
reply = input('reply:')
conn.send(reply.encode()) #Send message
sock.close()


if __name__ == '__main__':
address = '192.168.3.57' #Which IP adress you want to monitor
port = 9876
print('starting.....')
connect(address, port)

0x01 For Client

​ Just like the server, the client also needs to use a socket .But it doesn’t have to be so complicated ,you only need to use connect() method to connect to the server.

Client:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import socket

def connect(adress,port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a TCP socket
server_adress = (adress, port)
sock.connect(server_adress) #Connect to server
while True:
data = input('Please input you message:')
if not data:
break
sock.send(data.encode())
data = sock.recv(1024)
print(data.decode())
if not data:
break
sock.close()


if __name__ == '__main__':
adress = '192.168.3.57' #Server IP adress
port = 9876
connect(adress, port)

0x02 Summary

For server:

socket.socket()–>bind()–>listen()–>while True–>accept()–>while True–>recv–>send()

For client:

socket.socket()–>connect()while True–>send()–>recv()