A
A
ALEXOR13022018-03-08 23:50:23
Python
ALEXOR1302, 2018-03-08 23:50:23

Why are sockets not bound to an address when receiving data?

I wrote a simple messaging, in fact everything works, but I can’t understand one thing, why the one who first poisons the message does not bind the address with the method udp_socket.bind(addr)? Well, in principle, this is understandable: because otherwise he would think that he needed to listen on this port not on his interface and would give an error. But then how does it then receive messages with the method if the socket is not bound to its address? First sender:data = udp_socket.recvfrom(1024)

import socket
import sys

host = '192.168.1.37'
port = 7770
addr = (host,port)

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

while True:
    data = input("Отправьте сообщение: ")
    data = str.encode(data)
    udp_socket.sendto(data, addr)

    data = udp_socket.recvfrom(1024)
    print("Вам письмо: ", data[0].decode())


udp_socket.close()


First recipient:
#Модуль socket для сетевого программирования
import socket
import struct
#данные сервера
host = '192.168.1.37'
port = 7770
addr = (host,port)
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#bind - связывает адрес и порт с сокетом
udp_socket.bind(addr)

#Бесконечный цикл работы программы
while True:
    
    
    #recvfrom - получает UDP сообщения
    conn, addr = udp_socket.recvfrom(1024)
    res = conn.decode()
    print("Вам сообщение: " ,conn)
    reply = input("Что ответите? ")
    reply = str.encode(reply)
    #sendto - передача сообщения UDP
    udp_socket.sendto(reply, addr)
    
  
udp_socket.close()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-03-09
@ALEXOR1302

But then how does it then receive messages using the data = udp_socket.recvfrom(1024) method if the socket is not bound to its address?

Before data is sent over an unbound socket, it is implicitly bound because the UDP packet must contain the source port, and the IP packet containing it must contain the source address. You can see where the socket is bound using getsockname .
The receiver remembers from which address the message came:
and sends its response back to this address:
udp_socket.sendto(reply, addr)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question