[Modified] AttributeError: ‘socket‘ object has no attribute ‘ioctl‘ python linux

For beginners of python, refer to the common codes on the Internet to set the heartbeat of TCP:

def __ init__ (self, IP=”127.0.0.1″, Port=5555):

“” “initialize object” “”

self.code_mode = “utf-8”    # Transceiving data encoding/decoding format

self.IP = IP

self.Port = Port

self.my_socket =socket(AF_INET, SOCK_STREAM)   # Create socket

self.my_socket.setsockopt(SOL_SOCKET,SO_KEEPALIVE,True)

self.my_socket.ioctl(SIO_KEEPALIVE_VALS,(1,10000,1000))

Run error:

AttributeError: ‘socket’ object has no attribute ‘ioctl’

It is found that there are no exceptions marked in VSC, and the rewritten code can be automatically supplemented, indicating that socket has this function. I checked that there is no relevant wrong information on the Internet, which may be due to my lack of TCP related common sense. This is confirmed by opening the socket.ioctl definition of Python. The definition is as follows:

if sys.platform == “win32”:

def ioctl(self, __control: int, __option: int | tuple[int, int, int] | bool) -> None: …

To sum up: I write code with vs in win7 and upload it to Linux for operation, while IOCTL is only valid in window.

Under Linux, it should be changed to

self.my_socket.setsockopt(SOL_SOCKET,SO_KEEPALIVE,True)

# self.my_socket.ioctl(SIO_KEEPALIVE_VALS,(1,10000,1000))

self.my_ socket.setsockopt(IPPROTO_TCP, TCP_KEEPIDLE, 10)

self.my_socket.setsockopt(IPPROTO_TCP, TCP_KEEPINTVL, 3)

self.my_socket.setsockopt(IPPROTO_TCP, TCP_KEEPCNT, 5)

Read More: