Socket.py has no attribute AF_INET - python

I am trying to create a simple HTTP Client and I'm having trouble creating a simple socket. I use PyCharm and it highlights the AF_INET attribute of socket.py as non-existent and my script also crashes at runtime when it tries to get the AF_INET property. I checked my imports and I'm sure I have them right. Thanks!
import re
import socket
def getAddress():
address = input('Please enter a http address and a port (example: http://httpbin.org):\n')
parseAddress(address)
def parseAddress(address):
urlMatch = re.compile(r'^(.*:)//([A-Za-z0-9\-\.]+)(:[0-9]+)?(.*)$')
searchResult = urlMatch.match(address)
host = searchResult.group(2)
port = '80'
portTest = searchResult.group(3)
if portTest is not None:
port = portTest.replace(':', '')
connectToServer(host, port)
def connectToServer(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.bind((host, port))
#s.send('HTTP REQUEST')
#response = s.recv()
#print(response)
I also checked for any files named socket.py and there aren't any in my project structure. Also when I ctrl+click the socket import it points me to the right file in the Python install folder :(

Related

What are the capabilities of socket module in python, and how are they achieved

I've been recently introduced to the standard socket module in python, and have begun experimenting with it myself. However, upon sending my projects to friends, I've soon bumped into the problem that the programs have only local network reach.
Here's an example of what I've been working on- it's a simple program that connects a server to one client, then engages them in a simple chat loop indefinetly.
This program has been copied from this video tutorial, with some modifications:
https://www.youtube.com/watch?v=YwWfKitB8aA&t=1614s
(IP has been slightly modified for privacy purposes.)
SERVER:
import socket
HOST = '192.168.0.1'
PORT = 43218
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
commsocket, address = server.accept()
print(f"Connected to {address}")
while(True):
message = commsocket.recv(1024).decode("utf-8")
print(f"Message from client: {message}")
returnmessage = input("Type in message to send: ")
commsocket.send(returnmessage.encode('utf-8'))
CLIENT:
import socket
from time import sleep
HOST = '192.168.0.1'
PORT = 43218
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect((HOST, PORT))
while(True):
message = input("Type in message to send, then press enter: ")
server.send(message.encode('utf-8'))
print(f"Message from server {server.recv(1024).decode('utf-8')}")
Is it in any way possible to modify this so that anyone from outside my LAN (if possible, even to a global reach) can use this program as a client? If possible, with only the use of the vanilla socket module.
Thank you

Receiving files python socket server

I was trying to create a python socket server that could send and receive data, so I created a socket on the server using the code here:
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('', 1208))
serversocket.listen(5)
(client,(ip,port)) = serversocket.accept()
Then I tried to create a sample connection from my machine by going to command prompt and typing
telnet www.filesendr.com 1208
However, the console simply replies with "Could not open connection to the host, on port 1208...Connection failed." I went back over my code but couldn't identify the problem. Any help would be greatly appreciated.
I think part of the problem is that after you accept the connection you don't do anything else. Once the accept happens, you get to the end of the script, python exits and closes all open file handles (including the socket you just opened). If you want to be able to talk to yourself through telnet, try something like this:
import socket
import select
import sys
port = 1208
listener = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
listener.bind(('',port))
listener.listen(128)
newSock, addr = listener.accept()
while True:
r,w,e = select.select([newSock,sys.stdin],[],[])
if newSock in r:
data = newSock.recv(4096)
sys.stdout.write(data)
if sys.stdin in r:
newSock.send(sys.stdin.readline())

Web Server & Socket Programming

Currently doing an assignment in which we are programming sockets in python and thus creating a web server when the webserver.py code is executed.The code should then display HTTP headers and other information when you access a file(test.html)from the web server. Now my code works (or I'd like to believe so) and I have created a test.html file and the question goes on to say that I should place the test.html file in the same directory as the web server, where exactly is that on my local machine? I placed the test.html in the same folder as webserver.py in the python's root directory and proceeded to 127.0.0.1:1336/test.html to test my code but it doesn't work, where exactly on my machine is the webserver directory in which I should place test.html? Is it that I have to use wamp/xamp and place the test.html in there?
N.B 1336 is the port I specified in the code to connect to.
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverPort = 1336
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serverSocket.bind(('', serverPort)) #set up socket connection
serverSocket.listen(1) #tells the server to try a maximum of one connect request before ending connection
while True:
#Establish the connection
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()
print 'connected to port',serverPort
try:
message = connectionSocket.recv(1024) #Makes it so that you can recieve message from client
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.open(filename[1:])
#Send one HTTP header line into socket2
#Fill in start
connectionSocket.send('HTTP/1.0 200 OK\r\n')
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
#Send response message for file not found
print '404 Error : File Not Found.'
#Close client socket
connectionSocket.close()
serverSocket.close()
First of all, you shouldn't use the socket module to make a HTTP server. I recommend using the http.ser ver module, and change the working directory to where the html files are. Lets say i had test.html in C:\User\Desktop.
An example:
from http.server import HTTPServer, CGIHTTPRequestHandler
import os
os.chdir("C:/User/Desktop")
address = ("", 1336)
httpserver = HTTPServer(address,, CGIHTTPRequestHandler)
httpserver.serve_forever()
Then you can access it by 127.0.0.1:1336/test.html
If this isn't the answer you are looking for, please add the webserver.py to the question.

Socket Server in Python

I am trying to set up a local server so that other PCs on the same local network can connect to it. When trying to do so, on the client side, I get the following error:
[Errno 10061] No connection could be made because the target machine actively refused it
I have been searching around for hours and still couldn't resolve this issue. I tried turning off my Firewall too, but nothing.
These are my server and client codes:
Server Code:
import socket
import threading
import SocketServer
import datetime
ver_codes = []
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
print threading.current_thread().isDaemon()
data = self.request.recv(1024)
command = data.split()[0]
if(command=="login"):
if(logged_in(data.split()[1])==False):
self.request.sendall(login(data.split()[1], data.split()[2]))
else:
self.request.sendall("already in")
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def client(ip, port, message):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
try:
sock.sendall(message)
response = sock.recv(1024)
print "Received: {}".format(response)
finally:
sock.close()
def logged_in(id_num):
for i in ver_codes:
if(i[0]==id_num):
return True
return False
def login(username, password):
login_file = open("Login.txt", "r")
match = login_file.readline()
while(match!="*"):
if(match.split()[0]==username):
if(match.split()[1]==password):
ver_codes.append([match.split()[0], encryption_code(match.split()[2])])
login_file.close()
return "{} {}".format(match.split()[2], encryption_code(match.split()[2]))
print "And Here"
match = login_file.readline()
return "Denied"
login_file.close()
def encryption_code(to_encrypt):
now = datetime.datetime.now()
return int(str(now.microsecond)) * int(to_encrypt)
if __name__ == "__main__":
HOST, PORT = "localhost", 7274
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
ip, port = server.server_address
print server.server_address
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = False
server_thread.start()
print "Server loop running in thread:", server_thread.name
Client Code:
import socket
import sys
HOST, PORT = "localhost", 7274
data = " ".join(sys.argv[1:])
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
sock.sendall("login mahdiNolan m1373")
received = sock.recv(1024)
finally:
sock.close()
I really appreciate any help you could give me!
Thanks A LOT beforehand!
Your issue is because you're listening on localhost - this will only accept connections from the local machine.
If you want to accept connections from anywhere, instead of "localhost" just pass the empty string "". This is equivalent to specifying INADDR_ANY to the C sockets API - see the ip man page for more information, or this page also looks like it has some useful explanation. In short, this means "accept connections on any local interface".
Instead of the empty string you can instead specify an IP address of a local interface to only accept connections on that interface - it's unlikely you need to do this unless you machine has multiple network cards inside it (e.g. acting as a gateway) and you only want to serve requests on one of the networks.
Also, on the client side you should use the actual address of the machine - replace "localhost" with the IP address or hostname of the server machine. For example, something like "192.168.0.99". If you want to find the IP address of the server under Windows, open a DOS window and run the ipconfig command, look for the line with IPv4 Address (assuming you've got an IPv4 network which is very likely).
The Windows firewall will also block the server from accepting connections as you've already found, but you shouldn't need to disable it - as soon as you run your server you should see a popup window where you can instruct it to accept connections (that was on Windows 7, it might be different on other versions). In any case, turning the software firewall off should allow everything to work, although whether that's a security risk is a matter outside of the scope of this question.

Python 2.7 - Help using an API (HL7)

I am new to programming and Python.
I have a very basic python script that connects to server and send a text message:
#!/usr/bin/python
import socket
s = socket.socket()
host = '127.0.0.1'
port = 4106
s.connect((host, port))
message = 'test1'
s.send(message)
print s.recv(1024)
s.close
Everything is fine, except that this message is an HL7 message and needs to wrapped in MLLP
I found this API that I think can do this for me (http://python-hl7.readthedocs.org/en/latest/api.html#mllp-network-client)
So I modified my program to the following, but I keep getting the error message: NameError: name 'MLLPClient' is not defined
#!/usr/bin/python
import socket
import hl7
host = '127.0.0.1'
port = 4106
with MLLPClient(host, port) as client:
client.send_message('test1')
print s.recv(1024)
s.close
You can do this in different ways;
If you import the top-level package
import hl7
You should create the object with its complete name:
with hl7.client.MLLPClient(host, port) as client:
client.send_message('test1')
or you can import only the specific class:
from hl7.client import MLLPClient
and use it like you did in your example.
See the modules documentation for more information.
maybe from hl7 import MLLPClient ?
or maybe do
with hl7.MLLPClient(...) as ...

Categories

Resources