一个完整的Socket例子 [Socket]
[root@lvdbing python]# cat connect3.py
#!/usr/bin/env python
import socket
print "Creating Socket ...",
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "done."
print "Looking up port number ...",
port = socket.getservbyname('http','tcp')
print "done."
print "Connecting to remote host on port %d..." % port,
s.connect(("www.google.com",port))
print "done."
print "Connected from ", s.getsockname()
print "Connected to ", s.getpeername()
运行结果:
[root@lvdbing python]# ./connect3.py
Creating Socket ... done.
Looking up port number ... done.
Connecting to remote host on port 80... done.
Connected from ('192.168.33.38', 32775)
Connected to ('64.233.189.147', 80)
[root@lvdbing python]# ./connect3.py
Creating Socket ... done.
Looking up port number ... done.
Connecting to remote host on port 80... done.
Connected from ('192.168.33.38', 32776)
Connected to ('64.233.189.99', 80)
[root@lvdbing python]# ./connect3.py
Creating Socket ... done.
Looking up port number ... done.
Connecting to remote host on port 80... done.
Connected from ('192.168.33.38', 32777)
Connected to ('64.233.189.147', 80)
[root@lvdbing python]# ./connect3.py
Creating Socket ... done.
Looking up port number ... done.
Connecting to remote host on port 80... done.
Connected from ('192.168.33.38', 32778)
Connected to ('64.233.189.104', 80)
[root@lvdbing python]# netstat -na
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 192.168.33.38:32778 64.233.189.104:80 TIME_WAIT
tcp 0 0 192.168.33.38:32777 64.233.189.147:80 TIME_WAIT
tcp 0 0 192.168.33.38:32775 64.233.189.147:80 TIME_WAIT
tcp 0 0 192.168.33.38:32776 64.233.189.99:80 TIME_WAIT
tcp 0 0 :::22 :::* LISTEN
tcp 0 0 ::ffff:192.168.33.38:22 ::ffff:192.168.32.161:3473 ESTABLISHED
udp 0 0 0.0.0.0:68 0.0.0.0:*
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags Type State I-Node Path
unix 2 [ ACC ] STREAM LISTENING 6153 /dev/gpmctl
unix 2 [ ACC ] STREAM LISTENING 29282 /tmp/ssh-Fpuhq14755/agent.14755
unix 6 [ ] DGRAM 6060 /dev/log
unix 2 [ ] DGRAM 2632 @udevd
unix 2 [ ] DGRAM 29592
unix 2 [ ] DGRAM 29514
unix 2 [ ] DGRAM 6170
unix 2 [ ] DGRAM 6152
unix 2 [ ] DGRAM 6068