#!/usr/bin/env python
# Python Network Programming Cookbook -- Chapter - 1
# This program requires Python 2.7 or any later version
import socket
from binascii import hexlify
def convert_ip4_address():
for ip_addr in ['127.0.0.1', '192.168.0.1',"192.168.4.1"]:
packed_ip_addr = socket.inet_aton(ip_addr)
unpacked_ip_addr = socket.inet_ntoa(packed_ip_addr);
print ("IP Address: %s => Packed: %s, Unpacked: %s" % (ip_addr, hexlify(packed_ip_addr), unpacked_ip_addr))
if __name__ == '__main__':
convert_ip4_address()
获取默认端口号对应的服务
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import socket
#获取默认端口对应的服务!
def find_service_name():
protocolname = 'tcp'
#for port in [80, 25,21,443,8080]:
for port in range(1,11320+1):#端口号范围0-65535
try:
print "Port: %s => service name: %s" % (port, socket.getservbyport(port, protocolname))
except socket.error:
err="";
print "Port udp: %s => service name: %s" %(53, socket.getservbyport(53, 'udp'))
if __name__ == '__main__':
find_service_name()
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import ntplib
import time
import datetime
#window C:\Python27\Scripts\pip.exe install ntplib
#pip install ntplib
def print_time():
ntp_client = ntplib.NTPClient()
response = ntp_client.request('pool.ntp.org')
str=time.ctime(response.tx_time)
print str;
#时间戳转换为字符串
newtime=time.localtime(response.tx_time);
line=time.strftime("%Y-%m-%d %H:%M:%S",newtime)
print line
if __name__ == '__main__':
print_time()