What to do after split String? - python

I have an IP address that I need to split in order to know the location of the device.
s = "11.19.27.55"
ip = [item[::-1] for item in s[::-1].split('.', 1)][::-1]
print(ip)
Result:
['11.19.27', '55']
How can I now compare to certain parts of this result?
The first part I need for location second part for knowing which device it is.

I found the solution myself:
print(ip[0]) for the first part
print(ip[1]) for the second part

Related

How to remove/exclude unwanted objects from a list in python

Hi I am trying to get the IP of every interface on my machine using netifaces in python. I am still new to python and working my way through some concepts but it seems like I can query every NIC at once and then put the results into a list the problem is my end goal is to ask the user which network to work on and I want to exclude everything that returns 'No IP addr'.
I have already tried a few different methods including removing strings from the list and that didnt work or only adding IP addresses objects but im pretty sure im not doing it properly since it still errors out. Any help is appreciated.
import os
import socket
from netifaces import interfaces, ifaddresses, AF_INET
def get_self_IP():
for ifaceName in interfaces():
addresses = []
possibilities = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
print(' '.join(possibilities))
for i in possibilities:
if isinstance(i, ifaddress.ipaddress): # if i is an IP address
addresses.append(i)
print(addresses)
Also I have two lists now because ive changed it a few times to troubleshoot but if I can keep it as one list and only .append the IPs to it while its gathering IPs rather than have to do an entire separate list with a separate for or if loop it would be ideal but I do not know another way unfortunately.
Not sure if this is what you want, but:
I changed the function to:
def get_self_IP():
addresses = []
for ifaceName in interfaces():
ifaddresses_list = ifaddresses(ifaceName)
possibilities = [i['addr'] for i in ifaddresses_list.setdefault(AF_INET, [{'addr': 'No IP addr'}])]
for i in possibilities:
if ifaddresses_list[2][0]['addr'] != "No IP addr":
addresses.append(i)
print(addresses)
The ifaddresses(ifaceName) returns a dictionary which apparently the key 2 contains the IP address in the index 0 with the key 'addr', which in case the IP doesn't exist the value is No IP addr. In that the if checks if that is not the case and then adds the IP address to the addresses list.
If I didn't understand what you want clearly, please answer with more details :)

Trying to replace last 2 octets of ip address

I have the following ip address "192.168.2.65"
Is there a way to convert the last 2 octets to 0.
I found the following, but it only lets me replace the last one, i need to replace the last 2.
ip = 192.168.2.65
output='.'.join(ip.split('.')[:-1]+["0"])
print(output)
which gives me 192.168.2.0 and i would like to be 192.168.0.0
Index -1 means the last index. If you want to change two, change your index to -2.
output='.'.join(ip.split('.')[:-2]+["0", "0"])
You could also use a regex based approach here:
ip = "192.168.2.65"
output = re.sub(r'\.\d+\.\d+$', '.0.0', ip)
print(output) # prints 192.168.0.0
Dependant on the logic you are trying to apply.. if you are simply wanting to modify a string, the other answers are correct.
However, if you are looking to get the network address for the subnet an address resides in, you should handle the addresses correctly and use the ipaddress module.
This will assist in calculating the correct network & broadcast addresses, and allow you to check inclusions in networks etc.
import ipaddress
interface = IPv4Interface('192.168.2.35/255.255.0.0')
print(interface.network)
#192.168.0.0/16
print(interface.network.network_address)
#192.168.0.0
print(interface.network.broadcast_address)
#192.168.255.255

How to check an IP address is within a predefined list in python

Providing that I have this list which contains a number IP addresses:
IpAddresses = ["192.168.0.1","192.168.0.2","192.168.0.3","192.168.0.4"]
Then after receiving a packet I want to check if its source address is included in the predefined list IpAddresses
data, address = rxsocket.recvfrom(4096)
I have tried two alternatives, but both didn't work:
First:
if (address in IpAddresses):
do something
Then, I tried to convert address into string before making the comparison:
str_address = str(address)
if (str_address in IpAddresses):
do something
I am not familiar with python syntax, so please could you show me how to do this.
if address[0] in IpAddresses:
since the address object appears as a tuple only the 0th index appears in your list so you should check for its existence (also you can usually skip the parenthesis on an if statement unless it makes the if statement less readable)

Referencing range of IP addresses

I am trying to specify a range of addresses that will be set every time an API is called. For the example below, when api is referenced, I would like it to hosts in the range to a list, and not just one as it currently does.
api = xmlrpclib.ServerProxy("http://user:pass#192.168.0.1:8442/")
Generating the addresses seems straightforward enough, but I am unsure how to store it so that when api is reference, it's sends to every host, e.g. 192.168.0.1 - 192.168.0.100 and not just one.
for i in range(100):
ip = "192.168.0.%d" % (i)
print ip
I would also like to be able to specify the range, e.g. 192.168.0.5 - 192.168.0.50 rather then incrementing from zero.
Update: The API does not handle a list very well so the solution need to be able to parse the list. Might this simply require a second for statement?
If you want a different range:
for i in range(5,51):
ip = "192.168.0.%d" % (i)
print ip
Not sure what you mean by setting multiple. That for loop is doing that for you. If you're talking about saving references of your api, you can also throw those into a list.
api = []
for i in xrange(5,51):
ip = "192.168.0.%d" % (i)
api.append(xmlrpclib.ServerProxy("http://user:pass#" + ip))

How to split the return of socket,gethostbyaddr and write to file?

I have a script that reads addresses from a file and looks up its hostname with socket.gethostbyaddr, however the return of this function is messy and doesn't look right.
The line where it writes to the destination file reads:
destfile.write(str(socket.gethostbyaddr(ip)))
The results come out like this when it reads 8.8.8.8:
('google-public-dns-a.google.com', [], ['8.8.8.8])
However, I only need that first output, google-public-dns-a.google.com. I hope to have it write to the file and look like this:
8.8.8.8 resolves to google-public-dns-a.google.com
Anyone know how to split this? Can provide more code if needed.
Well, the first step is to split the one-liner up into multiple lines:
host = socket.gethostbyaddr(ip)
Now, you can do whatever you want to that. If you don't know what you want to do, try printing out host and type(host). You'll find that it's a tuple of 3 elements (although in this case, you could have guessed that from the string written to the file), and you want the first. So:
hostname = host[0]
Or:
hostname, _, addrlist = host
Now, you can write that to the output:
destfile.write('{} resolves to {}'.format(ip, hostname))
Another way to discover the same information would be to look at the documentation, which says:
Return a triple (hostname, aliaslist, ipaddrlist) where hostname is the primary host name responding to the given ip_address, aliaslist is a (possibly empty) list of alternative host names for the same address, and ipaddrlist is a list of IPv4/v6 addresses for the same interface on the same host (most likely containing only a single address).
Or to use the built-in help in the interpreter:
>>> help(socket.gethostbyaddr)
gethostbyaddr(host) -> (name, aliaslist, addresslist)
Return the true host name, a list of aliases, and a list of IP addresses,
for a host. The host argument is a string giving a host name or IP number.
What you want to do is unpack the tuple holding the information you want. There are multiple ways to do this, but this is what I would do:
(name, _, ip_address_list) = socket.gethostbyaddr(ip)
ip_address = ip_address_list[0]
destfile.write(ip_address + " resolves to " + name)

Categories