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'
Related
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
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 want to create a small TCP server that takes incoming TCP connections from a device that is hooked up via Ethernet to my computer.
The physical port for that has the IP 192.168.1.100 statically assigned to it.
The scripts I use as a client and server are listed at the bottom.
The setup works if I want to send messages between the python scripts. However, I am unable to receive anything from the external device (screenshot from Wireshark capture below). From what I have read I can define an interface to listen to by defining its IP. So I defined the IP of the interface as the host variable. However, I do not receive anything in my script but the messages sent by the other script. I had a similar situation already here on stackoverflow. I thought that defining the correct IP as the host would resolve this issue but it did not.
I am also having a hard time capturing the traffic between the two scripts with Wireshark at all. They did not show up anywhere.
I need to pick up these connections on the eth0 interface with the static IP 192.168.1.100:
tcp_server.py
import socket
# create a socket object
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
# host = socket.gethostname()
host = "192.168.1.100"
port = 9002
# bind to the port
serverSocket.bind((host, port))
# queue up to 5 requests
serverSocket.listen(5)
while True:
# establish a connection
clientSocket, addr = serverSocket.accept()
print("Got a connection from %s" % str(addr))
msg = 'Thank you for connecting' + "\r\n"
clientSocket.send(msg.encode('ascii'))
clientSocket.close()
and this as a client:
tcp_client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
# host = socket.gethostname()
host = "192.168.1.100"
port = 9002
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
msg = s.recv(1024)
s.close()
print(msg.decode('ascii'))
I'm trying to code a port scanner in python with banner grabbing.
Without the s.send('getBanner\n') line (which grabs the banner) my script works, and it prints the open ports.
But when I add the 'getBanner' line, a socket error says '[Errn 32] Broken Pipe'.
I know that this error probably happens because the clients don't wait till the connection get established and close the socket. How can I solve this?
The code:
import socket
host = '192.168.1.1'
for port in range(1,1024):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
s.send(('getBanner\n'))
banner = s.recv(1024)
if result == 0:
print "[+] Port %s tcp/open" % port
print "[+] Banner: %s" % banner
s.close()
Not all ports have a service listening on them and when they do, you need to follow whatever protocol is normal for that service. I assume you have some sort of service that responds to "getBanner", but most will not. You are connecting to things like FTP, SSH, DNS, NFS and mail servers and these things don't have "getBanner" commands. But you are also trying to connect to ports that don't have anything listening on them and this generates an error.
Looking at the docs:
connect_ex(...)
connect_ex(address) -> errno
This is like connect(address), but returns an error code (the errno value)
instead of raising an exception when an error occurs.
Your connection call is returning an error code and you need to check that before trying to send the request. So, as a minimum:
import socket
host = '192.168.1.1'
for port in range(1,1024):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
if result == 0:
s.send(('getBanner\n'))
banner = s.recv(1024)
if result == 0:
print "[+] Port %s tcp/open" % port
print "[+] Banner: %s" % banner
s.close()
But since most servers listening on ports don't respond to a "getBanner" command, its either going to hang or more likely raise connection reset errors.
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)