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
Related
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!
I've recently been tinkering around with the python socket module and I have come across an issue.
Here is my python server side script (im using python3.8.2)
import socket
#defin socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 0))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"connection from client has been established")
clientsocket.send(bytes("welcome to the server!", "utf-8"))
My server side script runs fine, however when i run the client script
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(127.0.0.1), 0))
msg = s.recv(1024)
print(msg.decode("utf-8"))
i get the following:
File "client.py", line 3
s.connect((socket.gethostname(127.0.0.1), 0))
^
SyntaxError: invalid syntax
I've tried changing the IP to my computer host name and gives the following:
raceback (most recent call last):
File "client.py", line 3, in <module>
s.connect(socket.gethostname((LAPTOP-XXXXXXX), 0))
NameError: name 'LAPTOP' is not defined
There are multiple issues:
when specifying IP addresses and hostnames, they must be formatted as strings (e.g. "127.0.0.1" and "LAPTOP-XXXXXXX"). Specifying them without quotes causes Python to attempt to interpret them as other tokens, such as variable names, reserved keyword, numbers, etc., which fails causing erros such as SyntaxError and NameError.
socket.gethostname() does not take an argument
specifying port 0 in the socket.bind() call results in a random high numbered port being assigned, so you either need to hardcode the port you use or dynamically specify the correct port in your client (e.g. by specifying it as an argument when executing the program)
in the server code, socket.gethostname() may not end up using the loopback address. One option here is using an empty string, which results in accepting connections on any IPv4 address.
Here's a working implementation:
server.py
import socket
HOST = ''
PORT = 45555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
host_addr = s.getsockname()
print("listening on {}:{}".format(host_addr[0], host_addr[1]))
s.listen(5)
while True:
client_socket, client_addr = s.accept()
print("connection from {}:{} established".format(client_addr[0], client_addr[1]))
client_socket.send(bytes("welcome to the server!", "utf-8"))
client.py
import socket
HOST = '127.0.0.1'
PORT = 45555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
msg = s.recv(1024)
print(msg.decode("utf-8"))
Output from the server:
$ python3 server.py
listening on 0.0.0.0:45555
connection from 127.0.0.1:51188 established
connection from 127.0.0.1:51244 established
Output from client:
$ python3 client.py
welcome to the server!
$ python3 client.py
welcome to the server!
Put the 127.0.0.1 as string in gethostname
In the /etc/hosts file content, You will have an IP address mapping with '127.0.1.1' to your hostname. This will cause the name resolution to get 127.0.1.1. Just comment this line. So Every one in your LAN can receive the data when they connect with your ip (192.168.1.*). Used threading to manage multiple Clients.
Here's the Server and Client Code:
Server Code:
import socket
import os
from threading import Thread
import threading
import time
import datetime
def listener(client, address):
print ("Accepted connection from: ", address)
with clients_lock:
clients.add(client)
try:
while True:
client.send(a)
time.sleep(2)
finally:
with clients_lock:
clients.remove(client)
client.close()
clients = set()
clients_lock = threading.Lock()
host = socket.getfqdn() # it gets ip of lan
port = 10016
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
client, address = s.accept()
timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
a = ("Hi Steven!!!" + timestamp).encode()
th.append(Thread(target=listener, args = (client,address)).start())
s.close()
Client Code:
import socket
import os
import time
s = socket.socket()
host = '192.168.1.43' #my server ip
port = 10016
print(host)
print(port)
s.connect((host, port))
while True:
print((s.recv(1024)).decode())
s.close()
Output:
(base) paulsteven#smackcoders:~$ python server.py
Server is listening for connections...
Accepted connection from: ('192.168.1.43', 38716)
(base) paulsteven#smackcoders:~$ python client.py
192.168.1.43
10016
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
From the python library 'socket' is there a method that returns the IP of the socket that got binded to it?
Suppose a socket was declared and initialized like:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(ip, port)
And I wanted to find the IP of a received datagram from a socket:
while True:
for s in socks:
recv = s.recv(1024)
#get ip of s or socket
#print received data from s.gethostname()
How would I go on about this?
you can try with recvfrom this method returns data and the address of the sender
data, address = sock.recvfrom(4)
Try with socket.getpeername().
Simple way would be like
data, (ip, port) = sock.recvfrom(4096)
print (ip)
Here is broadcast server
from time import sleep
from socket import *
PORT = 50000
s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', 0))
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
data = "I am server"
while 1:
s.sendto(data, ('<broadcast>', PORT))
print "sent data"
sleep(5)
Please note that you need to change '<broadcast>' with actual broadcast address of your network. Please see Python can't send a broadcast package with address
Here is broadcast receiver
from socket import socket, AF_INET, SOCK_DGRAM
PORT = 50000
client = socket(AF_INET, SOCK_DGRAM)
client.bind(('0.0.0.0', PORT))
data, addr = s.recvfrom(1024) #sticks here forever!
if data:
print "Found Broadcast server at : " + addr
But problem is that my receiver just sticks at s.recvfrom(1024)
While through tcpdump I am able to see the packet, then why this python client is not able to catch it ?
command is sudo tcpdump -i wlan0 ip -X dst host 255.255.255.255
I changed your code to Python 3 and corrected 2 errors:
Change s to client
Print the statement only when there is data from recvfrom()
Hope it helps.
from socket import socket, AF_INET, SOCK_DGRAM
PORT = 50000
client = socket(AF_INET, SOCK_DGRAM)
client.bind(('0.0.0.0', PORT))
while True:
data, addr = client.recvfrom(1024) #sticks here forever!
if data:
print("Found Broadcast server at : ", addr)
You need to set socket options before you bind it, and you need to bind it to INADDR_BROADCAST.
in do.py
servport = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
servport.bind( (socket.gethostname(), 0) )
wrapper = 'doing.py'
pid = os.fork()
if not pid:
argv = [sys.executable, wrapper, '%s:%d' % servport.getsockname()]
os.execv(argv[0], argv)
try:
print "do.py: someone connect to me"
servport.listen(1)
(send_sock, got_addr) = servport.accept()
print "do.py: connected from %s" % str(got_addr)
in doing.py
print "doing.py: got %s" % str(sys.argv)
(host, port) = sys.argv[1].split(':')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect( (host,port) )
I see that '%s:%d' % socket.getsockname() gives out 127.0.1.1:36802
but my public ip address is something that starts with 98...*
if i do ifconfig on my box (ubuntu), i have wlan0 of 192.168..
I read and and understood that there are different classes of ip address and 127...* is basically saying that the packet is destined for another app running on the same machine.
How do I code so that '%s:%d' % socket.getsockname() gives out my 98...*?
from suggestions,
if i change to servport.bind( ('0.0.0.0', 0) ) in do.py
i get
do.py: someone connect to me
doing.py: got ['doing.py', 0.0.0.0:41107']
do.py: connected from ('127.0.0.1', 43871)
is this mean my packets were actually sent outside of my network and came back? <-----
Referencing this question: Finding local IP addresses using Python's stdlib
Use socket.getfqdn to resolve your qualified host name.
Then use socket.gethostbyname to turn it in to resolvable ip address
Just like this
>>> from socket import gethostbyname, getfqdn
>>> gethostbyname(getfqdn())
'0.0.0.0'