Created
January 30, 2015 08:18
-
-
Save kozmonaut/6a5fac4303b118b2cc23 to your computer and use it in GitHub Desktop.
Networking workbook in py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Import socket library | |
import socket | |
# Import hexlify for ip address conversion | |
from binascii import hexlify | |
# Use NTP protocol | |
import ntplib | |
from time import ctime | |
# Print hostname | |
hostname = socket.gethostname() | |
print "Hostname %s" % hostname | |
# Print IP address | |
ip_address = socket.gethostbyname(hostname) | |
print "Your IP address: %s" % ip_address | |
# Wrap this into function | |
def print_hostname(): | |
hostname = socket.gethostname() | |
ip_address = socket.gethostbyname(hostname) | |
print "Hostname: %s" % hostname | |
print "Your IP address: %s" % ip_address | |
# Find IP address of remote machine | |
def find_ip_address(): | |
remote_host = 'www.dropsql.com' | |
print "IP address of %s: %s" %(remote_host, socket.gethostbyname(remote_host)) | |
# Convert IP address | |
def ip_address_convert(): | |
remote_host = 'www.dropsql.com' | |
ip_address = socket.gethostbyname(remote_host) | |
# Convert address to 32 bit binary format | |
packed = socket.inet_aton(ip_address) | |
# Convert a 32-bit packed IPv4 address to dotted notation | |
unpacked = socket.inet_ntoa(packed) | |
print "Converted IP address: Packed - %s | Unpacked - %s" %(hexlify(packed), unpacked) | |
# Find services on ports | |
def service_on_ports(): | |
protocol = 'tcp' | |
for port in [25, 80, 21]: | |
print "On port %s is service %s" %(port, socket.getservbyport(port, protocol)) | |
# Contact NTP servers to fetch current time | |
def ntp(): | |
# Create NTP client | |
client = ntplib.NTPClient() | |
response = client.request('0.hr.pool.ntp.org') | |
print ctime(response.tx_time) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment