Unable to get Hostname and IP and output to file Python3 - python

I am currently trying to write my first Python3 program. In my program I am calling upon socket to get the IP and Hostname and write it to a file using a function (See code below). However, whenever I call the function it never outputs the IP or Hostname to the file IP.txt, it only writes the except message.
def get_Host_name_IP():
try:
f = open("IP.txt","w+")
host_name = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
f.write("Hostname : ", host_name)
f.write("IP : ", host_ip)
except:
f.write("Unable to get Hostname and IP")

write() takes one argument (string), so you need to format your strings properly:
def get_Host_name_IP():
try:
f = open("IP.txt","w+")
host_name = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
f.write(f"Hostname : {host_name}\n")
f.write(f"IP : {host_ip}")
except:
f.write("Unable to get Hostname and IP")

Related

Connecting a ' local network ' python chatroom to the ' internet '

so i tried to make a simple chat room with python 3.8 , with a simple twist that instead of having one server and tow client connecting to that server , the conversation goes on between a client and the server it self , the code worked completely as intended on a single machine and also on tow different devices on a local network ( both connected to the same router and modem ) , but when i tried to access it on a different device out of the local network , client could not connect to the server , here is my code for the server side :
import socket
import threading
FORMAT = "utf-8"
PORT = 9999
HOST_IP = '192.168.1.56'
print("[SERVER STARTING]")
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST_IP, PORT))
server.listen()
def accepting():
global connection
print('[WAITING FOR CONNECTION ... ]')
while True:
connection, address = server.accept()
print(f'[NEW CONNECTION] {address} Connected to the server ')
connection.send(f"[SERVER] Welcome to {HOST_IP}".encode(FORMAT))
def receiving():
global connection
while True:
try:
msg = connection.recv(2048).decode(FORMAT)
if len(msg) == 0:
pass
else:
print('[CLIENT] ' + msg)
except:
pass
def sending():
global connection
while True:
try:
server_msg = input("> ")
connection.send(server_msg.encode(FORMAT))
except:
pass
receiving_th = threading.Thread(target=receiving)
accepting_th = threading.Thread(target=accepting)
sending_th = threading.Thread(target=sending)
accepting_th.start()
receiving_th.start()
sending_th.start()
i tried changing the HOST_IP on line 6 to all of the following :
HOST_IP = ''
HOST_IP = '0.0.0.0'
HOST_IP = '127.0.0.1'
neither of them worked . i also tried putting my Public IP address but the following error poped up :
Traceback (most recent call last):
File "C:\Users\pc\PycharmProjects\PrivateMssg1.0\Server.py", line 9, in <module>
server.bind((HOST_IP, PORT))
OSError: [WinError 10049] The requested address is not valid in its context
on the client side , here is my code :
import socket
import threading
FORMAT = "utf-8"
PORT = 9999
HOST_IP = "192.168.1.56"
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST_IP, PORT))
msg = client.recv(2048).decode(FORMAT)
print(msg)
def receiving():
while True:
try:
msg = client.recv(2048).decode(FORMAT)
print('[SERVER] ' + msg)
except:
pass
def sending():
while True:
try:
client_msg = input("> ")
client.send(client_msg.encode(FORMAT))
except:
pass
receiving_th = threading.Thread(target=receiving)
sending_th = threading.Thread(target=sending)
receiving_th.start()
sending_th.start()
i tried my Public IP address here on line 6 HOST_IP = "my public IP" as well but it didnt work .
i researched about 2 days and tried disabling my PC s firewall and my router firewall but that didnt work either .
i also tried opening port 9999 on my pc and also Port Forwarding port 9999 on my router to my local ip 196.168.1.56 . i tried restarting my router and my pc . but none of them worked . i dont think my code is causing it to not connect because it worked fine on a local network . can anyone help me out ?
and can someone try ,y code on their setup ? because the problem might be with my router not port forwarding correctly .
the problem was with my public IP , you need a static public IP to be able to accept inbound request, it worked fine on a linux based server .

Using GET/ filename.html HTTP ......... python serve client

Hopefully I can make this somewhat clear. I have to create a server and client in python that sends HTTP GET request to each other. Now I created a basic server/client program and now my goal is to send the server a HTTP GET request(from an html file I have saved) and the server to display the content.
Example Server would display something like
Date:
Content Length:
content Type:
As of now when I run the client and type GET / filename.html HTTP/1.1\n\r the server does not display. When I type that exact command in just a Linux shell it displays perfectly. How can I do this in a client and server. Hopefully this makes sense. Here is my client and server.
#CLIENT
import socket
import sys
host = socket.gethostname()
port = 12345 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print(s.recv(1024))
inpt = input("type")
b = bytes(inpt, 'utf-8') #THIS SENDS BUT SERVER DOESDNT RECIEVE
s.sendall(b)
print("Message Sent")
#SERVERimport socket
import sys
host = '' # Symbolic name meaning all available interfaces
port = 12345 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print("Connection accepted from " + repr(addr[1]))
c.send(b"Server Approved")
print(repr(addr[1]) + ":" + c.recv(1024).decode("UTF-8"))
c.close()
I want to type something like this to my server and display its content
GET / google.com HTTP/1.1\r\n
The error message is so straightforward, just read it to fix the code that doesn't work.
Traceback (most recent call last):
...
print(repr(addr[1]) + ":" + c.recv(1024))
TypeError: must be str, not bytes
Add .decode("utf-8"):
print(repr(addr[1]) + ":" + c.recv(1024).decode("utf-8"))
And more clear is to use str() instead of repr(). You can read about the differences between these two here: Difference between __str__ and __repr__ in Python.
print(str(addr[1]) + ":" + c.recv(1024).decode("utf-8"))

port scanning an IP range in python

So I'm working on a simple port scanner in python for a class (not allowed to use the python-nmap library), and while I can get it to work when passing a single IP address, I can't get it to work using a range of IPs.
This is what I have:
#!/usr/bin/env python
from socket import *
from netaddr import *
# port scanner
def port_scan(port, host)
s = socket(AF_INET, SOCK_STREAM)
try:
s = s.connect((host, port))
print "Port ", port, " is open"
except Exception, e:
pass
# get user input for range in form xxx.xxx.xxx.xxx-xxx.xxx.xxx.xxx and xx-xx
ipStart, ipEnd = raw_input ("Enter IP-IP: ").split("-")
portStart, portEnd = raw_input ("Enter port-port: ").split("-")
# cast port string to int
portStart, portEnd = [int(portStart), int(portEnd)]
# define IP range
iprange = IPRange(ipStart, ipEnd)
# this is where my problem is
for ip in iprange:
host = ip
for port in range(startPort, endPort + 1)
port_scan(port, host)
So when I run the code, after adding print statements below
host = ip
print host # added
and then again after
port_scan(port, host)
print port # added
I end up with the following output:
root#kali:~/Desktop/python# python what.py
Enter IP-IP: 172.16.250.100-172.16.250.104
Enter port-port: 20-22
172.16.250.100
20
21
22
172.16.250.101
20
21
22
...and so on
Thanks in advance everyone!
I appreciate any help that I can get!
code picture for reference, slightly different
output picture for reference
The problem turned out to be an issue with using the netaddr.IPRange, as suggested by #bravosierra99.
Thanks again everyone!

getting a socket.gaierror Error 2 when using an actual hostname defined in /etc/hosts, but do not get error with localhost

I have copied simple server/client python programs to test some socket communications.
If host is defined as 'localhost' or '', they work.
If I substitute the actual hostname in /etc/hosts, they fail with the socket.gaierror 2.
socket.gethostname() returns the correct value
as does 'hostname' on the command line.
Here is the server code that fails
#!/usr/bin/env python
"""
A simple echo server
"""
import socket
import sys
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print( " using host [%s] " % (host) )
s.bind((host,port))
s.listen(backlog)
while 1:
client, address = s.accept()
data = client.recv(size)
print( data )
if data:
client.send(data)
client.close()
and here is the client program
#!/usr/bin/env python
"""
A simple echo client
"""
import socket
host = 'localhost'
port = 50000
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
s.connect((host,port))
s.send('Hello, world')
data = s.recv(size)
s.close()
print( 'Received:', data )
This is the actual output from the server.py while using the gethostname() call.
using host [HP-linux]
Traceback (most recent call last):
File "server.py", line 18, in <module>
s.bind((host,port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno -2] Name or service not known
Like I said, if I comment out the 'gethostname() calls, they work.
I have not been able to find any posts about gaierrors that have answers that work to solve this issue.
This running on SuSE Linux 13.1, and python2.7.
Thanks
This issue was resolved by adding an alias to the /etc/hosts file.
No rational answer as to why this would work.
Binding the server on hostname you're actualy binding it on local address, this is because normally there's a line in /etc/hosts like this 127.0.1.1 somehostname, this is to use lo iface instead of eth on the same machine for optimization reasons. If you want to accept connections from all interfaces use '0.0.0.0' instead.
I simply did these steps.
Ran command:
hostname
Say it returned me a value 'yourHostName'
Make an entry in your /etc/hosts file as follows.
127.0.0.1 yourHostName localhost
Reference for this information is : format of /etc/hosts file. Which you can see here.

IP address by Domain Name

I am trying to get IP address of a domain..
i am using following code
>> import socket
>> socket.gethostbyname('www.google.com')
its giving me following error..
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
socket.gethostbyname('www.google.com')
gaierror: [Errno 11001] getaddrinfo failed
what is wrong with my code...is there any other way to get ip address by domain name in python..???
please help...
Your code is correct.
Perhaps you have a firewall in between you and these servers that is blocking the request?
import socket
domainName = input('Enter the domain name: ')
print(socket.gethostbyname(domainName))
I think you forgot to print it because it works for me.
# Python3 code to display hostname and
# IP address
# Importing socket library
import socket
# Function to display hostname and
# IP address
def get_Host_name_IP():
try:
host_name = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
print("Hostname : ",host_name)
print("IP : ",host_ip)
except:
print("Unable to get Hostname and IP")
# Driver code
get_Host_name_IP() #Function call
#This code is conributed by "Sharad_Bhardwaj".
That error also appears when the domain is not hosted anywhere (is not connected to any IP, any nameserver) or simply does not exist.
Here is full example, how you can get IP address by Domain Name.
import urllib.parse
import socket
import dns.resolver
def get_ip(target):
try:
print(socket.gethostbyname(target))
except socket.gaierror:
res = head(target, allow_redirects=True)
try:
print(r.headers['Host'])
except KeyError:
parsed_url = urllib.parse.urlparse(target)
hostname = parsed_url.hostname
try:
answers = dns.resolver.query(hostname, 'A')
for rdata in answers:
print(rdata.address)
except dns.resolver.NXDOMAIN:
print('ip not found')
get_ip('example.com')

Categories