Skip to content

Instantly share code, notes, and snippets.

@n0nuser
Last active March 19, 2021 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n0nuser/12a2869d228eeba042d7cbe9232f1f20 to your computer and use it in GitHub Desktop.
Save n0nuser/12a2869d228eeba042d7cbe9232f1f20 to your computer and use it in GitHub Desktop.
Networking related Python Functions
import re
import socket
import struct
import platform
import subprocess
# https://stackoverflow.com/a/166589
def getWANIP():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
IP = s.getsockname()[0]
s.close()
return IP
# https://www.kite.com/python/answers/how-to-get-the-local-ip-address-in-python
def getIP():
return socket.gethostbyname(socket.gethostname())
def validateIP(ip):
if (not(re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip))):
try:
return socket.gethostbyname(ip)
except:
print(" Invalid Host!")
return -1
else:
return ip
def validatePort(port):
if (not (1 <= port <= 65535)):
print(" That port can't be used!")
return -1
# https://github.com/AnthraX1/InsightScan/blob/f0f258120b7fb230fb2749c212fa2cb19a347e3a/scanner.py#L276
def ip2bin(ip):
"""
Convert an IP address from its dotted-quad format to
its 32 binary digit representation
"""
b = ""
inQuads = ip.split(".")
outQuads = 4
for q in inQuads:
if q != "":
b += dec2bin(int(q),8)
outQuads -= 1
while outQuads > 0:
b += "00000000"
outQuads -= 1
return b
# All of the 4 Functions from: https://stackoverflow.com/a/819420
def makeMask(n):
"Return a mask of n bits as a long integer"
return (2L<<n-1) - 1
def dottedQuadToNum(ip):
"Convert decimal dotted quad string to long integer"
return struct.unpack('L',socket.inet_aton(ip))[0]
def networkMask(ip,bits):
"Convert a network address to a long integer"
return dottedQuadToNum(ip) & makeMask(bits)
def addressInNetwork(ip,net):
"Is an address in a network"
return ip & net == net
# https://stackoverflow.com/a/32684938
def ping(host):
"""
Returns True if host (str) responds to a ping request.
Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
"""
# Option for the number of packets as a function of
param = '-n' if platform.system().lower()=='windows' else '-c'
# Building the command. Ex: "ping -c 1 google.com"
command = ['ping', param, '1', host]
return subprocess.call(command) == 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment