9.2 Socket programming

  Most remote management software and hacking software rely on Sockets to achieve specific functions, and the popular port bounce in previous years has brought this technology to the extreme.

  As mentioned above, UDP and TCP are two important protocols running at the transport layer of the network architecture. Among them, TCP is suitable for occasions where the requirements for efficiency are relatively low and the requirements for accuracy are relatively high, such as text transmission, e-mail, etc.; UDP is suitable for occasions with relatively high requirements for efficiency and relatively low requirements for accuracy, such as online video on demand, VoIP calls, etc. In Python, the socket module is mainly used to support TCP and UDP programming.

 

  9.2.1 UDP programming

  Many years ago, when ordinary families did not have mobile phones, telephones, and pagers, they mainly depended on correspondence. The sender mentioned the recipient's address and then sent the letter, but there was no guarantee that the other party would receive it. This letter (for example, the other party has changed the address) does not guarantee that several letters at different times will arrive at the destination in the order in which they were sent. The working process of UDP is similar to the mailing of ordinary letters. It belongs to a connectionless protocol. When programming UDP, it does not need to establish a connection first, but directly sends information to the receiver. UDP does not provide a response and retransmission mechanism, and there is no guarantee that the data will reach the destination. The biggest advantage of UDP is its high efficiency. Its header contains only a few fields such as double-send address and checksum, and the extra overhead is very small. The socket module methods often used in UDP programming are as follows.

  (1) socket([family[,type[,proto]]]: Create a Socket object, where family is socket.AF_INET means IPv4, AF_INET6 means IPv6; type is SOCK_STREAM means use TCP, SOCK_DGRAM means use UDP.

  (2) sendto(string, address): Send the content specified by string to the address specified by address, where address is a tuple of the application process terminal number containing the IP address of the recipient host, in the format (IP address, port number) .

  (3) recvfrom(bufsize[,flags]): Receive data.

 

  The following is an example to briefly understand how to use UDP for network communication.

  The sender sends a string, assuming that the receiver is listening on port 5000 of the local machine, and displays the accepted content. If the string 'bye' (ignoring case) is received, the monitoring ends.

  Receiver code:

1  import socket
 2  
3  #Use IPv4 protocol, use UDP to transmit data 
4 s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
 5  
6  #Bind the port and port well, empty string means any available IP address of the machine 
7 s.bind( '' ,5000 )
 8  
9  while True:
 10      data,addr = s.recvfrom(1024 )
 11  
12      #Display the received content 
13      print ( ' received message:{0} from PORT{1} on { 2} ' .format(data.decode(),addr[1 ],addr[0]))
 14  
15      if data.decode().lower() == 'bye':
16         break
17 
18 s.close()

 

  sender code:

import socket
import sys

s = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)

#Assume 192.168.1.103 is the IP address of the receiver machine 
s.sendto(sys.argv[1].encode(),( ' 192.168.1.103 ' ,5000 ))

s.close()

 

  Save the above codes as receiver.py and sender.py respectively, then first start a command prompt environment and run the receiver program, then the receiver program is blocked, then start a new command calligraphy environment and Run the sender program, you will see that the receiver program continues to run and displays the received content and the IP address of the computer where the sender program is located and the port number occupied. When the sender sends the string 'bye', the receiving single program ends, and after that, when the sender program is run again, the receiver does not respond, but the sender program does not report an error. That's the peculiarity of UDP, "best effort transmission", and doesn't guarantee a very good quality of service.

 

  You can use the following Python code to get the IP address of the machine and the physical address of the network card.

 1 ip = socket.gethostbyname(socket.gethostname())  #本机IP地址
 2 node = uuid.getnode()
 3 print('node:',node)
 4 
 5 macHex = uuid.UUID(int=node).hex[-12:]
 6 mac = []
 7 print(macHex)
 8 for i in range(len(macHex))[::2]:
 9     mac.append(macHex[i:i+2])
10 
11 mac1 = ':'.join(mac)                          #网卡的物理地址
12 
13 print('IP:',ip)
14 print('MAC:',mac1)

 

  拓展知识:发送数据时,如果目标IP地址中最后一组数字是255,表示广播地址,也就是说局域网内的所有主机都会受到信息。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325100218&siteId=291194637