I am writing a simple client and server and want to introduce some simple bounds checking to insure the IP address entered by a user is in the correct format i.e.(int.int.int.int), does anybody have any suggestions as to hwo this can be done at the moment my code just accepts the value and will throw an OS error if its invalid. But I want to stop a user being able to enter anything in here.
def ipEntered():
global ipEntered
ipEntered = input("Please enter the ip address of the server you wish to connect with:")
Thanks
Use the ipaddress module (introduced in Python 3.3):
import ipaddress
def ipEntered():
while True:
try:
val = input("Please enter the ip address of the server you wish to connect with:")
return ipaddress.ip_address(val)
except ValueError:
print("Not a valid IP address")
which will accept IPv4 addresses of the form "100.200.30.40", e.g. a dotted quad, and IPv6 addresses in both longhand form (8 groups of 4 hexadecimal characters separated by :) and shorthand forms.
If you only want to accept IPv4 addresses, use return ipaddress.IPv4Address(val) instead.
Related
I have achieved sniffing IP packets. I use the following code.
def print_summary(pkt):
print("SRC:", pkt[scapy.IP].src, "\t\tDEST:", pkt[scapy.IP].dst)
scapy.sniff( iface=interface, filter="ip", prn=print_summary)
If I try to ping a domain name say 'youtube.com' or open it using a web browser, how can I show the domain name using the above print_summary function. I have tried searching for what filters to use for dns but found nothing.
Okay, I get it now. What I did was to remove the filter argument altogether from the sniff() method.
scapy.sniff( iface=interface, prn=print_summary)
Then in the print_summary() function, I filtered according to the layer each packet had (IP or DNS).
def print_summary(pkt):
if scapy.IP in pkt:
print("SRC:", pkt[scapy.IP].src, "\t\tDEST:", pkt[scapy.IP].dst)
if scapy.DNS in pkt:
print("Domain:", pkt.[scapy.DNS].qd.qname.decode("utf-8"))
decode("utf-8") because the qname is a utf encoded byte string.
I've the following problem : I'm actually making a script for an ovirt server to automatically delete virtual machine which include unregister them from the DNS. But for some very specific virtual machine there is multiple FQDN for an IP address example:
myfirstfqdn.com IN A 10.10.10.10
mysecondfqdn.com IN A 10.10.10.10
I've tried to do it with socket in Python but it return only one answer, I've also tried python with dnspython but I failed.
the goal is to count the number of type A record on the dns server
Anyone have an idea to do stuff like this?
That's outright impossible. If I am in the right mood, I could add an entry to my DNS server pointing to your IP address. Generally, you cannot find it out (except for some hints in some protocols like http(s)).
Given a zone file in the above format, you could do something like...
from collections import defaultdict
zone_file = """myfirstfqdn.com IN A 10.10.10.10
mysecondfqdn.com IN A 10.10.10.10"""
# Build mapping for lookups
ip_fqdn_mapping = defaultdict(list)
for record in zone_file.split("\n"):
fqdn, record_class, record_type, ip_address = record.split()
ip_fqdn_mapping[ip_address].append(fqdn)
# Lookup
ip_address_to_lookup = "10.10.10.10"
fqdns = ip_fqdn_mapping[ip_address_to_lookup]
print(fqdns)
Note: Using socket can be done like so - Python lookup hostname from IP with 1 second timeout
However this does require that DNS server that you are querying has correctly configured PTR reverse records.
https://www.cloudns.net/wiki/article/40/
I'm working on python, how can I receive a website address? I have tried but it doesn't work.
I have this:
import socket
socket.gethostbyname(name)
but nothing happens.
The gethostbyname(hostname) method translates a host name to an IPv4 address format. The IPv4 address is returned as a string.
So the argument for this method has to be a host name like "www.python.org". Assign a hostname for the 'name' variable in string format in your code.
Ex. name = "www.python.org"
Hope this helps!
I want to write a short script using python that read my ip address conversely , so when I write 127.0.0.1 I should find as a result 1.0.0.127.
any help please
Try this
ip = '127.0.0.1'
ip = ip.split('.')
ip.reverse()
print('.'.join(ip))
If you want to preserve the original ip. it's very easy since strings are immutable in python assign it to a new variable and just call reversed on it instead of calling the list's reverse() so you don't alter the list also (if you want that)
ip = '127.0.0.1'
new = ip.split('.')
new = reversed(new)
print('.'.join(new))
print(ip)
You can use this :
def reverseIP(ip):
ip = ip.split(".")
ip.reverse()
return '.'.join(ip)
Example :
print(reverseIP("127.0.0.1")) # Prints 1.0.0.127
Is there a function in Python that determines if a hostname is a domain name or an IP(v4) address?
Note, the domain name may look like: alex.foo.bar.com or even (I think this is valid): 1.2.3.com.
One of the visual differences between IP and domain address is when you delete dots in the IP address the result would be a number. So based on this difference we can check if the input string is an IP or a domain address. We remove dots in the input string and after that check if we can convert the result to an integer or we get an exception.
def is_ip(address):
return address.replace('.', '').isnumeric()
Although in some IP-Representations like dotted hexadecimal (e.g. 0xC0.0x00.0x02.0xEB) there can be both letters and numbers in the IP-Address. However the top-level-domain (.org, .com, ...) never includes numbers. Using the function below will work in even more cases than the function above.
def is_ip(address):
return not address.split('.')[-1].isalpha()
I'd use IPy to test if the string is an IP address, and if it isn't - assume it's a domain name. E.g.:
from IPy import IP
def isIP(str):
try:
IP(str)
except ValueError:
return False
return True