In: Computer Science
What's wrong with my Python code. We have to find the regularexpression in Python My output should look like this
My IP address 128. 0. 0. 1
My IP address 53. 20. 62. 201
My code
ipAddresses = []
ipRegEx = re.compile(r"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}")
result = myRegEx.find all(Search Text)
def Regular_expression(ipAddresses)
for i in ipAddresses:
print(i)
ipSearchResult = ipRegEx.search(line)
if ipSearchResult != None and ipSearchResult.group() not in ipAddresses:
ipAddresses.append(ipSearchResult.group())
we have to use loop too.
This modified code will fetch the IP
addresses.
The module “re” should be
imported to handle the regular expression.
The module “socket” should be
imported to find the IP Addresses
The statement “ipAddresses =
socket.gethostbyname_ex(socket.gethostname())” fetches all
the active IP addresses and assign it to the variable.
The loop iterates through all the ip addresses fetched.
There may be some blank entries fetched depending on whether you
are connected to the Internet, having multiple NIC cards etc. If
blank, do not proceed and continue with the next iteration of the
loop. The statement “if(len(ipAddress)
> 0)” handles that.
The regular expression then checks if it is a matching pattern of
IP address and if so, will proceed in printing that.
Code
import re #This should be imported to use the regular
expression
import socket #This should be imported to find the IP Addresses
def getIPAddresses():
ipAddresses = socket.gethostbyname_ex(socket.gethostname()) #This
statement will fetch all the ip addresses and assign it to the
variable
for ipAddress in ipAddresses: #This loop will loop through the
fetched ip addresses.
if(len(ipAddress) > 0): #There may be some blank entries fetched
depending on whether you are connected to the Internet, having
multiple NIC cards etc. If blank, do not proceed and continue with
the next iteration of the loop.
ipAddressString = ipAddress[0] #The variable "ipAddress" is a list
and take the 1st entry from that.
if(re.search("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}", ipAddressString)):
#Apply a regular expression and check if it is an ip address. If
so, proceed in printing that.
print ("My IP address " + ipAddressString)
getIPAddresses()