Twisted: IP address of the source of outgoing connections

I am implementing a Python service using the Twisted framework running on Debian GNU / Linux that checks for SIP servers. I use the OPTIONS method (SIP protocol function) for this, as this is apparently common practice. To create the correct and RFC compliant headers, I need to know the source IP address and source port for the connection to be established. [How] can this be done using Twisted?

This is what I tried: I subclassed protocol.DatagramProtocol and in and startProtocol(self)used . The latter is indeed the port to be used, while the former only gives 0.0.0.0.self.transport.getHost().hostself.transport.getHost().port

I assume that at this point Twisted does not know [yet?] Which interface and as such will use the source IP address. Does Twisted have a tool that could help me with this, or would I need to interact with the OS (routing) differently? Or am I just using it wrong self.transport.getHost().host?

+3
source share
3 answers

For completeness, I answer my question:

Before attempting to determine the IP address of the host source, make sure you use connect (). The following excerpt shows the relevant part of the protocol implementation:

class FooBarProtocol(protocol.DatagramProtocol):
    def startProtocol(self):
        self.transport.getHost().host   # => 0.0.0.0
        self.transport.connect(self.dstHost, self.dstPort)
        self.transport.getHost().host   # => 192.168.1.102
+8
source

If you use UDP, then the endpoint is defined either:

  • bind()

, .

, . , , , , , , , t.i.d.SelectReactor. , t.n.d.DNSDatagramProtocol .

twisted , , :

>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
<socket._socketobject object at 0x10025d670>
>>> s.getsockname()           # this is an unbound or unnamed socket
('0.0.0.0', 0)
>>> s.bind( ('0.0.0.0', 0) )  # 0.0.0.0 is INADDR_ANY, 0 means pick a port
>>> s.getsockname()           # IP is still zero, but it has picked a port
('0.0.0.0', 56814)

, IPv4 IPv6. , , socket.bind() .

, . , . , .

.

0

, , SIP, Twisted?

, UDP Twisted, , Twisted. Twisted, reactor.listenUDP(port, protocol, interface) UDP . self.transport.write(msg, addr) addr, , .

, , , , interface reactor.listenUDP(...).

0
source

Source: https://habr.com/ru/post/1721035/


All Articles