How to send a message in a specific port with python sockets ? No random ports -
i have test broadcast acknowledgement on localhost. have text files represent nodes , inside there list of neighbors.
use localhost ip , port number of node.
the problem when receive message (that sent) node 7000, python replaces random number example 65724. father 65724 instead of 7000, cannot remove 7000 list of neighbors.
cannot complete algorithm , frustrating.
i can send message port number want, it's not elegant.
could tell me how not allow python randomize port?
rmunn saved me, answer looking far bind before connect method. befor sending message bind own port , connect other one.
this not python problem, per se. confused how ports work.
each tcp communication (sending or receiving) has 2 ip addresses , 2 ports: host ip , host port, , destination ip , destination port.
if you're communicating computer "out there" on network, host , destination ips different. in test case, host , destination ips both 127.0.0.1 (localhost). i'm going go "different ips" case example, because makes easier see.
so ip address is, 10.1.2.3, , you're talking computer @ 10.1.2.99. tell system want talk 10.1.2.99 @ port 7000, , opens connection. when happens, randomly pick source port that's not in use. there's two-way communication channel open:
10.1.2.3:65274 <-> 10.1.2.99:7000
note did not pick host port. edit: said "in fact, system will not allow pick host port; assigned you" here, wrong. if s
socket object, can call s.bind()
set source port, call s.connect()
connect destination port.
now, when you're listening message, pick port you're listening on, , computer that's connecting have random port. if listening message on port 8912, incoming connection (once established) like:
10.1.2.3:8912 <-> 10.1.2.99:38290
note 38290 chosen @ random operating system of computer @ 10.1.2.99 ip address.
now bit of python. mention sockets in question title, i'll assume you're using socket
module python's standard library. once you've created socket object s
, use s.getpeername()
find out address (host , port) you've connected to, , s.getsockname()
find out address (host , port) you've connected from.
since talk expecting number 7000 , getting random number, think you're using host socket when should using destination socket.
Comments
Post a Comment