Name or service not known - python

I have been trying to get the ipaddress of the person who logged into the machine using the below code but I get a error.
>>> import socket
>>> socket.gethostbyname_ex(socket.gethostname())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
socket.gaierror: [Errno -2] Name or service not known
The same code works in other linux box.
Not sure I fix it.

Error has occurred just because of not setting up hostname properly. Set the hostname at three different places, which are in -
/etc/hostname
/etc/hosts
run command $ hostname
then logout and login again. You are done.

Check what is being returned by socket.gethostname() and see if you can ping it. Basically this is a lookup failure. Check your /etc/hosts to see if it is listed. I know it seems strange, but I think if the hostname being returned does not have an entry, you'll get a name service failure which is what that is.

If you are working with IPv6 or with servers with multiple network interfaces, this command will not work correctly.
Instead, you can use this command that tries to connect to the Google DNS server at 8.8.8.8 at port 53, and return your ip:
import socket
print([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])

Related

Python & Mcpi (minecraft) - connection refused error

I use mcpi: https://github.com/AdventuresInMinecraft/AdventuresInMinecraft-Linux
Starting the local server.
After, run program:
import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()
mc.postToChat("Hello Minecraft World")
I am facing the below error:
Traceback (most recent call last):
File "/home/home/AdventuresInMinecraft/MyAdventures/HelloMinecraftWorld.py", line 2, in mc = minecraft.Minecraft.create()
File "/home/home/.local/lib/python3.6/site-packages/mcpi/minecraft.py", line 376, in create return Minecraft(Connection(address, port))
File "/home/home/.local/lib/python3.6/site-packages/mcpi/connection.py", line 17, in init self.socket.connect((address, port))
ConnectionRefusedError: [Errno 111] Connection refused
A ConnectionRefusedError means that the address + port combination was unable to be secured for this particular Minecraft server and thus raised an exception. This could be because some other application is already using the port of interest, the port is unavailable because of the OS, or a handful of other networking configuration mishaps.
But perhaps a better series of questions to ask yourself is:
What is the default address and port that minecraft.Minecraft.create() will attempt to launch / listen at?
Do I have access to that server (address + port)?
If I do have access, are there any security issues (AKA Firewall)?
This post has already addressed the root issue of your question, and I hope it gives you a good start at understanding the foundation of your problem.
Notice how their question mentions s.connect((host,port)) and your stack trace has self.socket.connect((address, port)) Looks like the same thing to me!
Some more reading:
- localhost
- check if port is in use
I encountered the same issue. I looked into the code of mcpi and found that the default port is 4711. However, a Minecraft Server's default port is 25565. All you need to do is add 2 parameters on the create() function. Code(Python):
mc = minecraft.Minecraft.create(address="127.0.0.1", port=25565)
btw change "address" in the code to the host of the server (only if you modified the "server.properties" file).
Also, ConnectionRefusedError doesn't mean that it's not secured, I believe it means that either the server is not online, it doesn't exist, or the server refused it for some reason.
EDIT:
Oops sorry I just found out that mcpi actually connects to the RaspberryJam plugin which is hosted on another IP and port. The plugin runs on port 4711. So mcpi has the right port.
So check if you have the RaspberryJam plugin installed. If not, download it from
https://www.spigotmc.org/resources/raspberryjuice.22724/
And put the .jar file inside the plugins folder in your server directory.

Python 2.7 [Errno 113] No route to host

I have 2 computers on the same LAN. The first PC has an ip address 192.168.178.30, the other PC has an ip address 192.168.178.26.
Ping, traceroute, telnet, ssh, everything works between the two PCs. Both PCs run the same OS - CentOS 7 and both PCs have the same python version 2.7.5 (checked with the python -V command).
I copied simple python code from a computer networking book.
client.py
from socket import *
serverName = '192.168.178.30'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input('Input lowercase sentence: ')
clientSocket.send(sentence)
modifiedSentence = clientSocket.recv(1024)
print 'From Server:', modifiedSentence
clientSocket.close()
server.py
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('192.168.178.30',serverPort))
serverSocket.listen(5)
print 'The server is ready to receive'
while 1:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024)
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence)
connectionSocket.close()
The code works when it is ran on the same PC (where the server is listening on localhost).
When I run the client code on one PC and the server code on the other PC I get this error on the client side.
Traceback (most recent call last):
File "client.py", line 5, in <module>
clientSocket.connect((serverName,serverPort))
File "/usr/lib64/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 113] No route to host
Can someone help?
Check the firewall (on the server).
I stopped the firewall like Messa suggested and now it works.
service firewalld stop
I still don't understand what the problem was. I even tried using different distributions. Do all distributions have strict firewalls or something. For example Ubuntu to Ubuntu, Ubuntu to CentOS, CentOS to Ubuntu I still had the same problem (error).
~]#supervisord
Error: No config file found at default paths (/usr/etc/supervisord.conf, /usr/supervisord.conf, supervisord.conf, etc/supervisord.conf, /etc/supervisord.conf); use the -c option to specify a config file at a different path
For help, use /usr/bin/supervisord -h
You should use
ln -s /etc/supervisor/supervisord.conf /usr/etc/supervisord.conf
None of this stuff worked for me. I just connected both the devices to the same WiFi network and my program worked!
You can also get this same error ([Errno 113] No route to host) if you are trying to connect 2 devices on the same network. the error can be fixed by double checking to make sure both devices are connected to the mqtt_client or whatever you are using. as soon as I connected the device I was trying to talk to everything worked as to be expected.I would also check to make sure the right IP_Address is being passed
We had this problem. I am putting our findings here in case anyone else stumbles across this question like I did.
Our configuration:
Host A: IP address 192.168.0.1, netmask 255.255.255.0
Host B: IP address 192.168.1.1, netmask 255.255.254.0
Neither host has a default gateway.
We are connecting from Host B to Host A. (That is not a typo.) The connect call succeeds, but when we try to send data, we get errno 113 aka. EHOSTUNREACH aka. "No route to host".
The fix, of course, was to change the subnet on Host A to match Host B.
We were surprised to see this error on a connection within the same subnet / same LAN. And we were surprised that connect succeeded followed by send failing. And we were surprised to see this error on Host B even though the network configuration on Host B itself was fine.
Somehow, the incorrect subnet on Host A caused this error on Host B...
...and just like that, today I learned about ICMP "destination unreachable" messages.

socket.gethostbyaddr returns unknown host

I want to get the fqdn from the hostname.
I am am executiong this command on a linux server:
python -c "import sys, socket; sys.stdout.write(socket.gethostbyaddr('')[0])"
THis command works well and returns the fqdn from the hostname. But for some other servers, it returns this error:
Traceback (most recent call last):
File "", line 1, in
socket.herror: [Errno 1] Unknown host
When i do "host " linux command, I get the fqdn of the failed host names with python command.
Anyone have a solution for that plz?
Difficulty using Python's socket.gethostbyaddr() covers this nicely.
The gist is that you must verify there's a PTR record. If not, you'll have to handle it via a try, except clause.
Specifically look at the part comparing the a valid and non-valid PTR records.

TCP port scanner written in Python using Scapy yields no response

I’m trying to make a TCP port scanner, but I’m sticking to a very simple example that I lined together from a more advanced example I found online.
I don’t get any errors.
I’m expecting the code to show me that port 80 is open since I started my Apache server on my Linux box.
Here is the code:
#!/usr/bin/python
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
ip = "127.0.0.1"
port = 80
response = sr1(IP(dst=ip)/TCP(dport=port, flags="S"),verbose=False, timeout=0.2)
if response :
if response[TCP].flags == 18 :
print "Port open"
Warning I had (but that does not show up any more):
WARNING: No route found for IPv6 destination :: (no default route?)
I read that including these two lines below would help on the error:
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
Nmap scan:
STATE SERVICE
80/tcp open http
The output is… Nothing at all.
I tried several things like changing the port to different other ports, some which I had open and some which I did not.
Any ideas as to what I did wrong?
The scapy docs mention that the loopback address is a special case
The loopback interface is a very special interface. Packets going
through it are not really assembled and dissassembled. The kernel
routes the packet to its destination while it is still stored an
internal structure. What you see with tcpdump -i lo is only a fake to
make you think everything is normal. The kernel is not aware of what
Scapy is doing behind his back, so what you see on the loopback
interface is also a fake. Except this one did not come from a local
structure. Thus the kernel will never receive it.
In order to speak to local applications, you need to build your
packets one layer upper, using a PF_INET/SOCK_RAW socket instead of a
PF_PACKET/SOCK_RAW (or its equivalent on other systems that Linux):
>>> conf.L3socket
<class __main__.L3PacketSocket at 0xb7bdf5fc>
>>> conf.L3socket=L3RawSocket
>>> sr1(IP(dst="127.0.0.1")/ICMP())
<IP version=4L ihl=5L tos=0x0 len=28 id=40953 flags= frag=0L ttl=64 proto=ICMP chksum=0xdce5 src=127.0.0.1 dst=127.0.0.1 options=''
|\>
However testing this on my OS-X machine results in the following error:
>>> conf.L3socket=L3RawSocket
>>> sr1(IP(dst="127.0.0.1")/ICMP())
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scapy/sendrecv.py", line 334, in sr1
s=conf.L3socket(filter=filter, nofilter=nofilter, iface=iface)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scapy/supersocket.py", line 64, in __init__
self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
AttributeError: 'module' object has no attribute 'AF_PACKET'
So your mileage may vary
EDIT
Apparently this is a known bug in scapy on BSD like systems (including OS-X): http://bb.secdev.org/scapy/issue/174/sniffing-loopback-in-mac-os-x-darwin

Python Socket Error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

i was writing a small IRC bot when much to my dismay, i got an error that i cannot seem to understand or fix. the code i used worked before but now windows seems to not be happy with it.
Error:
socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions
This is the quick code i knocked up:
import socket
s = socket.socket().connect(("irc.cryto.net", 6667))
s.send("NICK kNij\r\n")
s.send("USER kNij 0 0 kNij :derp :3\r\n")
inputfile = s.makefile()
while 1:
line = inputfile.readline()
print line
Edit: it seems to be an all over problem with some sockets
That can never work. connect returns None (at least on Windows 7 with Python 2.7.2).
Try:
import socket
s = socket.socket()
s.connect(("Lidingo.SE.EU.Undernet.org", 6667))
s.send("NICK kNij\r\n")
s.send("USER kNij 0 0 kNij :derp :3\r\n")
inputfile = s.makefile()
while 1:
line = inputfile.readline()
print line,
(I changed the server to make sure the code really works)
Now, why you get that error, and not, like me:
Traceback (most recent call last):
File "D:\workspaces\generic\SO_Python\9337618.py", line 4, in <module>
s.send("NICK kNij\r\n")
AttributeError: 'NoneType' object has no attribute 'send'
is a mistery...
maybe the port 8000 is not accessible.
try change the port number to 8888 by using python manage.py runserver 8888 command.
it worked for me

Categories