Finding My Socket's Public IP Address? - python

I'm trying to create the ability for a client to enter the IP address/port of a server and connect to it. In order to do this, I need the server's public IP address/port. Is there a good way to do this? What I've tried so far is...
ip_address = urllib.request.urlopen(<my web server>).read()
with the web server just containing the php script:
<?php echo $_SERVER["REMOTE_ADDR"]?>
And just storing the port from the
s.bind(('', port))
Connecting to this ip address and port times out. Is there a better way to do this?
EDIT:
OK so basically I'm trying to establish a connection over the internet, without knowing exactly what my router is going to be doing. I can use a webserver with any code if necessary, as I have access to permanent webspace. This is what I have right now.
Server:
import urllib.request
import threading
import socket
socket_list = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 0))
s.listen(10)
def listener(socket):
while(1):
data = socket.recv(1024)
print (data)
def accepter():
while(1):
socket, addr = s.accept()
socket_list.append(socket)
threading.Thread(target = listener, args = (socket,)).start()
ip_address = (urllib.request.urlopen("<MY WEB SERVER HERE>").read()).decode('utf-8')
print (ip_address)
print (s.getsockname()[1])
threading.Thread(target = accepter, args = ()).start()
Client:
import socket
print ("Enter IP Address")
ip_address = input()
print ("Enter Port")
port = int(input())
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2.connect((ip_address, port))s2.send("Connected!")
s2.close()
When I run the client I'm entering the IP address and port that are outputted by the server. Needless to say, this doesn't work.

I thought this was a good question you can do it like this if you didn't want to have your server set up like you have:
""" Easy IP Getter """
import json
import urllib2
info = json.loads(urllib2.urlopen("http://jsonip.com").read())
ip = info["ip"]
print ip
It depends on an outside service however which isn't the best, if they stop working you stop working.

Related

ConnectionRefusedError when trying to connect to different machine, but not the own machine

I've been making a reverse shell application and since now only tried it on the same machine instead of a different one. Everything works fine as expected when using the same machine but when I try two different machines, the machine on which client.py runs gives me a ConnectionsRefusedError.
The client.py code
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def send(s: socket.socket, obj):
s.send(dumps(obj))
def recv(s: socket.socket):
return loads(s.recv(1024 * 1000))
while True:
try:
server.connect(("server ip", 6969))
connected = True
except:
connected = False
try:
key = recv(server)
if key:
send(server, None)
else:
connected = False
except:
connected = False
loc = my_loc
while connected:
# reverse shell script
Here is the server.py code
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 6969))
server.listen()
def listen():
global server
while True:
conn, addr = server.accept()
clients[addr[0]] = {"conn": conn, "cmd": {"head": None}, "info": {}, "ping": 0, "allowed": True}
logs[addr[0]] = []
shells[addr[0]] = []
client_threads[addr[0]] = Thread(target=_client, args=(addr[0],))
client_threads[addr[0]].start()
listener = Thread(target=listen, name="Listener")
listener.start()
Thats not the whole code, but the part where I get the errors from.
I had this problem multiple times but always somehow fixed it by moving the server = socket.socket() part in server.py around.
Is there anything I'm not seeing here?
Ip for different computers are different.
you will have to check the Ip of the new computer.
I had the same problem:-
If you are connected via the same router the Ip will look like 192.168.**.*
you need this code to get the router IP
import socket
hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")
If you are doing socket on a different network then you need to change the router settings to do port forwarding.
it is different for different routers so look it up.
Then find your public Ip and change your Ip in the client script.(Do not change IP on server script)

How can i connect two computers with python socket?

im new here!
I have a problem with connection between two computers connected with different wi-fi's. After about 20 seconds i get information that connection can't be done.
There is my code:
SERVER:
from socket import *
lista = ['computer']
s = socket(AF_INET, SOCK_STREAM)
port = 21312
s.bind(('my ipv4', port))
s.listen(5)
while True:
for i in range (0, len(lista)):
a = str(lista[i]).encode()
c, addr = s.accept()
print("CONNECTION WITH",addr)
c.send(a)
print(a)
c.close()
CLIENT:
import socket
from socket import *
port = 21312
while True:
s = socket(AF_INET,SOCK_STREAM)
s.connect(('my ipv4', port))
odebrana = (s.recv(1024))
decoded = odebrana.decode()
print(decoded)
s.close()
Likely you are experiencing an issue because your server sits behind a Network Address Translator (NAT). This way your client cannot use the server's IP directly since it is not reachable. There are a few ways around it.
The easiest and not very practical one is: get both machines in the same network, then it should work.
Get a public IP address for the server. You can do that by hosting it on a cloud server that provides you with a public IP, e.g., aws, azure, google cloud etc.
In the old days we used hamachi to get a VPN that would connect both machines. Then they can identify each other over that VPN. Simply turn on hamachi (or any other VPN solution), run your server, then from your client (connected to the VPN), use the VPN's server IP (hamachi will provide you with one when you setup a network).
Disclaimer: I have not used hamachi in about 15 years, but just went through the process because of one of the comments below.
Seems like you can create an account, then once you turn it on you should see your v4 and v6 addresses as shown below:
Highlighted is my v4 address. I suspect you need to create a network, join both PCs in the same network and then use hamachi's IP to emulate behaviour as if they were connected via LAN.
So I faced the similar problem while sending image files between 2 computers using python sockets. I solved the issue by following this way:
First I completed writing the connection code of both server.py and client.py
Note: server.py should be in one computer and client.py should be in another computer.
server.py
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print(host)
server.bind((host, 12000))
server.listen()
client_socket, client_address = server.accept()
file = open('server_image.jpg','wb')
image_chunk = client_socket.recv(2048)
while image_chunk:
file.write(image_chunk)
image_chunk = client_socket.recv(2048)
file.close()
client_socket.close()
client.py
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # AF_INET = IP, SOCK_STREAM = TCP
server_host = 'LAPTOP-1231' # Replace this hostname with hostname printed in server.py
client.connect((server_host, 12000)) # 127.0.0.1
file = open('That_Sinking_Feeling_27.jpg', 'rb')
image_data = file.read(2048)
while image_data:
client.send(image_data)
image_data = file.read(2048)
file.close()
client.close()
Now you should add the image in the directory where client.py is located, so that you can send it to another computer (server). Rename it to img.jpg
Then, you need to run server.py in your another computer. It will print the hostname in terminal. Then copy that hostname and paste it in client.py (server_host = hostname_from_server)
Then run client.py
Finally the image will be transferred to new computer (server)

Socket uses random ports and I need a certain one

Here is the problem, I want to create a connection between two computer in two networks in a certain port but when I am running the run I got this message that shows me every single time different ports:
Accepted a connection request from 192.168.1.2:**12345**
DATA
This is the listening code:
import socket
import logging
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind(("**server's Local ip**",6464))
serverSocket.listen(1)
while(True):
(clientConnected, clientAddress) = serverSocket.accept()
print("Accepted a connection request from %s:%s"%(clientAddress[0], clientAddress[1])) #[0], ...[1]
dataFromClient = clientConnected.recv(1024)
print(dataFromClient.decode())
clientConnected.send("Hello User".encode())
user = dataFromClient
cip = clientAddress
LOG_FILENAME = '/home/user/listenlog.txt'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
logging.debug(cip)
logging.debug(user)
logging.debug("--------------------------------------------------------")
and this is the client code:
import socket
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect(("**Server's IP**",6464))
data = 'Hello'
clientSocket.send(data.encode())
dataFromServer = clientSocket.recv(1024)
print(dataFromServer.decode())
How should I make the using port static?
if the connection that you got is public and behind nat
it is usual to be a random port because it is from isp or nat device so else i dont think that would be local
If you want your client’s socket to be bound to a specific port, you can call bind() on the socket before you call connect() on it.
Note that there is typically no benefit to doing that, however. The downside is that if that port is already in use, the bind() call will fail.

port forwarding not working with python sockets

I am learning how to use python sockets right now, and now I am trying to use the simple chat program that I created to talk with one of my friends. of course, the porgram didnt work because I didnt port forward it.
I have forwarded port 21342 using the ip (the ip is static) I found at whatismyip.com as my external ip and the ip shown as the ipv4 in the oputput of the ipconfig command in the cmd as the internal ip.
now, even after forwarding it still isnt working. am I still missing something obvious or is this a real issue?
code:
server:
import socket
import threading as thread
sock = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
host = ''
sock.bind((host , 21342))
sock.listen(5)
connections = []
def chat(client , address):
global connections
while True:
info = client.recv(1024)
for connection in connections:
if connection != client:
connection.send(info)
if not info:
connections.remove(client)
client.close()
break
try:
while True:
client , address = sock.accept()
print 'new connection!'
client_thread = thread.Thread(target = chat , args = (client , address))
client_thread.daemon = True
client_thread.start()
connections.append(client)
sock.close()
except:
for connection in connections:
connection.close()
sock.close()
client:
import socket
import threading as thread
sock = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
host = 'ip found at whatsmyip.com'
sock.connect((host , 21342))
def get_info(sock):
while True:
print sock.recv(1024)
get_info_thread = thread.Thread(target = get_info , args = [sock])
get_info_thread.daemon = True
get_info_thread.start()
while True:
sock.send(raw_input())
sock.close()

Python server TCP server accessable from anywhere (via external IP, port forwarding is done)

I am new here, so please, don't be angry if I am stupid - but I don't know about it.
I would like to make a python TCP server, which can be accessed from anywhere via external (public) IP. I have done simple server (it works) in local network from this tutorial:
https://www.youtube.com/watch?v=XiVVYfgDolU
The client sends string and the server sends back that string but with uppercase.
Now I want to do the same but accessable from anywhere. I read a lot about it. I have Raspberry Pi, where I set up static IP address and I did the port forward (on port 42424). I am just looking for some tutorial, you can direct me anywhere - thats all I need. Or you can tell me how to do it step by step, but I know that it takes a lot of time to write answer. I tried googling, but I didn't find anything. And if I did, it was a person who didn't know what the external IP and the port forwarding is so the end of the conversation was: Learn what is port forwarding.
So please, give me some tips how to do it, or direct me somewhere. Thanks!
The code
Server:
import socket
def Main():
host = '10.0.0.140'
port = 42424
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
while True:
data = c.recv(1024)
if not data:
break
data = str(data).upper()
c.send(data)
c.close()
if __name__ == '__main__':
Main()
Client:
import socket
def Main():
host = '10.0.0.140'
port = 42424
s = socket.socket()
s.connect((host,port))
message = raw_input("->")
while message != 'q':
s.send(message)
data = s.recv(1024)
message = raw_input("->")
s.close()
if __name__ == '__main__':
Main()
When connecting to a server behind a NAT firewall/router, in addition to port forwarding, the client should be directed to the IP address of the router. As far as the client is concerned, the IP address of the router is the server. The router simply forwards the traffic according to the port forwarding rules.

Categories