Reputation: 17040
I was watching Computer Network on Coursea. getaddrinfo
makes sense for the client program (to resolve the server name to a network address), but why does a server program needs getaddrinfo
to bind to a socket?
Please see page 12 on https://d396qusza40orc.cloudfront.net/comnetworks/lect%2F1-4-sockets-ink.pdf
Thanks.
Here is tutorial from Python. http://docs.python.org/3/howto/sockets.html#creating-a-socket
As you see I can do assign a port at the bind. But there is getaddrinfo()
in the _socketobject
level. (try access serversocket.getaddrinfo()
).
EDIT
Okay. Based on nos's comment, I think this is what he meant.
Supposed you want to run your own SSH program on port 22. For sake of OS portability, since the port is defined in /etc/services
you can ask socket to translate the port from OS.
import socket
# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
ssh_addrinfo = socket.getaddrinfo(socket.gethostname(), 'ssh')[0][4]
serversocket.bind(ssh_addrinfo)
# become a server socket
serversocket.listen(5)
serversocket.close()
ssh_addrinfo
looks like this:
>>> socket.getaddrinfo(socket.gethostname(), 'ssh')
[(2, 2, 17, '', ('192.168.33.1', 22)), (2, 1, 6, '', ('192.168.33.1', 22)), (2, 2, 17, '', ('192.168.1.4', 22)), (2, 1, 6, '', ('192.168.1.4', 22)), (30, 2, 17, '', ('fe80::2acf:e9ff:fe1e:4985%en0', 22, 0, 4)), (30, 1, 6, '', ('fe80::2acf:e9ff:fe1e:4985%en0', 22, 0, 4))]
Upvotes: 0
Views: 121
Reputation: 229108
You can configure a textual name for the port(service) in e.g. /etc/services, and have the server look that up with getaddrinfo() to learn which port it should listen on.
That step is optional though, you can set the port number by other means.
Upvotes: 1