Python find IP address which is also shown to online websites - python

I want to find out my computer’s IP address which other online services access. I have tried following pieces of code from Finding local IP addresses using Python's stdlib
import socket
print("\nYour IP Address is: ",end="")
print(socket.gethostbyname(socket.gethostname()))
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
s.close()
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
s.close()
print(IP)
However, the first two return: 10.105.220.74 and the third returns 127.0.1.1.
However, 192.31.105.231 is returned when using https://get-myip.com/ and https://www.iplocation.net/find-ip-address.
https://whatismyipaddress.com/ returns: IPv6:
2607:f140:6000:17:f0b8:ba78:a9df:213 IPv4: Not detected
Note that I slightly adjusted the IP addresses for privacy reasons.
Thank you for your help!

Related

get details from ipconfig python

I am looking for a short command to get an network interface ip address by its name, in python.
it did not work with socket.getaddr()
for example, this is my details:
I want a func so:
x=func('vEthernet (VIC Ethernet)')
so that x will be 10.10.255.254
i dont want to run ipconfig and parse it
thanks
It returns the IP address and port as a tuple.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
you can use this function to get the primary IP:
import socket
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(0)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
to get all ips you can use netifaces :
from netifaces import interfaces, ifaddresses, AF_INET
for ifaceName in interfaces():
addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
print(' '.join(addresses))
output:
No IP addr
No IP addr
No IP addr
No IP addr
192.168.0.104
127.0.0.1
scapy module has a func the does it - get_if_addr(iface_name)
thanks for everyone

Getting all IP addresses connected to WiFi using python and scapy

How would I get the IP addresses of all ips connected to wifi (that I am on). I tried doing it by using sniff() and getting all src IP of those packets using the following lines:
ips = []
captured = sniff(count=200)
for i in range(len(captured)):
try:
rpp = captured[i].getlayer(IP).src
if "192." in rpp and rpp != router_ip:
ips.append(rpp)
ips = list(set(ips))
But this rarely gets me all IP's, so how would I pull that off using python and (if needed) scapy?
Forgive me if I'm misunderstanding your question.. what you're trying to do is map all live hosts on your LAN?
A simpler approach is to use the builtin ipaddress and socket libraries. For each IP in your LAN subnet, try connecting a socket to various ports (TCP/UDP). If a connection is established, a host exists at that IP.
Here's some code I can think of that might solve your problem (I have not tested this myself)
import socket
import ipaddress
live_hosts = []
# google popular tcp/udp ports and add more port numbers to your liking
common_tcp_ports = [23, 80, 443, 445]
common_udp_ports = [67, 68, 69]
def scan_subnet_for_hosts(subn = '192.168.1.0/24'):
network = ipaddress.IPv4Network(subn)
for ipaddr in list(network.hosts()):
for port in common_tcp_ports:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
s.connect((str(ipaddr), port))
live_hosts.append(ipaddr)
except socket.error:
continue
for port in common_udp_ports:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
# UDP is connectionless, so you might have to try using s.send() as well
s.connect((str(ipaddr), port))
live_hosts.append(ipaddr)
except socket.error:
continue
scan_subnet_for_hosts()
for host in live_hosts:
print(f"Found live host: {str(host)}")

Invalid argument when trying to bind python socket to IPv6 address

I'm trying from my virtual machine to bind my socket in python to the address of my other virtual machine so that I could sniff the frames that are exchanged by the two. So here's my code
import socket
UDP_IP = "fe80:849b:21f4:624c:d70b"
UDP_PORT = 61627
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024)
print(data)
When I try to execute my python, I get an error message :
sock.bind((UDP_IP, UDP_PORT))
socket.error: [Error 22] Invalid argument
What am I doing wrong, thanks in advance !
I bet, you had found the answer already, but nevertheless on the first glance I see two issues with your code:
In IPv6 fe80::/10 address block is reserved for Link-local addresses. These addresses are valid for local subnet only, therefore they are used with scope suffixes like %eth0 to specify proper scope. Where eth0 is a name of the network interface for which the IPv6 address is valid.
So for my MacOS laptop UDP_IP address could look like:
UDP_IP = "fe80:849b:21f4:624c:d70b%en0"
Next, specifying (UDP_IP, UDP_PORT) tuple is absolutely valid for IPv4 but for IPv6 this tuple should also contain flow_info and scope_id fields. Sometimes, flow_info and scope_id could be omitted or missed: (UDP_IP, UDP_PORT, 0, 0). It may work sometimes, but it's not the right way to use in the code.
So, these fields can be fetched via socket.getaddrinfo(IP, PORT) which returns a list of tuples for each address family and socket_kind. Filter them with something like that:
for ainfo in socket.getaddrinfo(UDP_IP, UDP_PORT):
if ainfo[0].name == 'AF_INET6' and ainfo[1].name == 'SOCK_DGRAM':
target_address = ainfo[4]
break
sock.bind(target_address)
I'm not sure, if I wrote the sample code right, as I didn't test it, check it before usage.

Python socket gethostbyname() returns only one IP address

I'm doing some simple experiments using Python socket, where I've a HOSTNAME which resolves with two IP addresses but when I use, socket.gethostbyname('demo.sample.com') I'm getting only one IP address. Why is it showing that way? Is there any other way I can get multiple IP addresses?
EDIT - 1
I got it guys, instead of gethostbyname('demo.sample.com') I tried gethostbyname_ex('demo.sample.com') It gives the result as I expected.
From the documentation it is visible that:
gethostbyname returns only a single IPv4 address. And to cite: See gethostbyname_ex() for a more complete interface.
gethostbyname_ex will return multiple IPv4 address, but check out the usage. And to cite: gethostbyname_ex() does not support IPv6 name resolution, and getaddrinfo() should be used instead for IPv4/v6 dual stack support.
getaddrinfo will return all IPv4 and IPv6 addresses, but check out the usage.
I found a solution here, which returns the internal network IP:
import socket
def ip_addr(hostIP=None):
if hostIP is None or hostIP == 'auto':
hostIP = 'ip'
if hostIP == 'dns':
hostIP = socket.getfqdn()
elif hostIP == 'ip':
from socket import gaierror
try:
hostIP = socket.gethostbyname(socket.getfqdn())
except gaierror:
logger.warn('gethostbyname(socket.getfqdn()) failed... trying on hostname()')
hostIP = socket.gethostbyname(socket.gethostname())
if hostIP.startswith("127."):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# doesn't have to be reachable
s.connect(('10.255.255.255', 1))
hostIP = s.getsockname()[0]
return hostIP
if __name__ == '__main__':
print('%s' % ip_addr())

How to connect two computers on the same network using python

This is the server side program
import socket
s = socket.socket()
host = socket.gethostname()
port = 9077
s.bind((host,port))
s.listen(5)
while True:
c, addr = s.accept()
print("Connection accepted from " + repr(addr[1]))
c.send("Thank you for connecting")
c.close()
This is the client program
import socket
s = socket.socket()
host = socket.gethostname()
port = 9077
s.connect((host, port))
print s.recv(1024)
When i run these two programs on the same computer, it works perfectly.
But when i run the client and server programs in two different computers on the same network, the program doesn't work.
Can anyone please tell me how to send message from one computer to another on the same network.
This is the first time i'm doing any network programming. Any help would be appreciated
Thanks in advance
You are connecting from the client to the client's computer, or well attempting to, because you are using the client's hostname rather than the servers hostname/ip address.
So, to fix this change the line s.connect((host, port)) so that the host points to the servers ip address instead of the client's hostname.
You can find this by looking at your network settings on the server and doing the following:
host = "the ip found from the server's network settings"
host must be edited to the server's ip if the server is not the same computer.

Categories

Resources