In: Computer Science
I am new to socket programming and I wish to know what these
lines of code do. I know they are creating UDP sockets, but it
would help if someone explained what the code means. Thank
you.
Python Code:
import socket
testingSocket = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM)
testingSocket.setsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR,
testingSocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST,
1)
testingSocket.bind(('0.0.0.0', 50000))
send_socket = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM)
send_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST,
1)
receiving_thread = Thread(target=self.receivingFunction)
send_thread = Thread(target=self.sendMessage)
broadcast_online_status_thread = Thread(target=onlineStatus)
Explanation is given with # before every code line.
CODE:
# this module can give access to low-level socket functionalities.
# in this module some of the functions are platform dependant
import socket
# The AF_INET is in reference to th family or domain, it means ipv4, as opposed to ipv6 with AF_INET6. The SOCK_DGRAM means it will be a UDP socket. UDP means it will be connectionless.
testingSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# configuring the socket with the available options here, setsockopt function used to set the socket options. When retrieving a socket option, or setting it, you specify the option name as well as the level. When level = SOL_SOCKET, the item will be searched for in the socket itself. SO_REUSEADDR is set to 1 means that the validated addresses supplied to bind() should allow reuse of local addresses.
testingSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
# SO_BROADCAST this option is used check the reports whether transmission of broadcast messages is set to 1 here means allowed.
testingSocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# bind the socket with the provided < ip address and the port number >
testingSocket.bind(('0.0.0.0', 50000))
#creating another socket by name send socket
send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#configures the send socket and checking the whether broadcast is set to True
send_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# This constructor should always be called with keyword arguments. Arguments target is the callable object to be invoked by the run() method. Defaults is None means nothing is called.
#receiving function is called
receiving_thread = Thread(target=self.receivingFunction)
# send Message is called
send_thread = Thread(target=self.sendMessage)
#onlineStatus is called
broadcast_online_status_thread = Thread(target=onlineStatus)