I am trying to change my IP while I use bind in socket but it gives me an error:
socket.error: [Errno 10049] The requested address is not valid in its
context
You didn't include any code so I assume you did it like so:
import socket
sock = socket.socket()
#The port and IP are for the sake of example
sock.bind(('1.2.3.4', 1200))
You can't do that. When you bind a socket to an IP and port you "say" to that socket to listen and wait until somebody send something to that port. Of course you can't listen to a port on some other computer so it gives you an error.
If you still wish to change your IP you can use Scapy: http://www.secdev.org/projects/scapy/
This tool very complex but here is the most basic way to change your IP:
from scapy.all import *
#again the IP is only for the sake of example
MyPack = IP(src='1.2.3.4', dst='www.google.com')
send(MyPack)
Congratulations! you have sent a packet with a different IP (pretty sure it's illegal though)
Related
I'm using the socket module from Python 3.7 (shouldn't matter, as I tried activating a different Python version from different venv's).
The problem is that I've created a TCP connection listening at port 65432, an arbitrary number that I selected for this simple demo.
server.py looks like the following:
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 65432 # Non-privileged ports are > 1024
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
client.py is relatively straightforward as it makes a connection with 127.0.0.1:65432.
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # Port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
# Send its message and then read the server's reply and prints it
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
Executing server.py to open the port 65432 for listening (in first console) and then executing client.py to send a simple 'hello world' message (in a second console). This is what got printed to the first console:
Connected by ('127.0.0.1', 56051)
So far so good. Port 56051 connecting to port 65432, right? No.
I execute netstat -am (command tool utility to see state of sockets on the host machine) and found this:
Active Internet connections (including servers)
Proto Recv-Q Send-Q Local Address Foreign Address (state)
tcp4 0 0 127.0.0.1.51495 *.* LISTEN
Instead of 127.0.0.1.65432 as local address, it is using port 51495 instead.
Doing another verification check, this time firing off lsof -i -n:
COMMAND PID FD TYPE DEVICE SIZE/OFF NODE NAME
Code\x20H 51214 37u IPv4 0x1af15eb424ba89f3 0t0 TCP 127.0.0.1:51495 (LISTEN)
Both verifications confirmed that port 51495 is being used instead of 65432 as specified in my server.py and client.py scripts. Any leads or tips? Many thanks in advance!
65432 is the port number of your server socket, not your client socket. As the client end is not attached with any specific port number, it will be dynamically allocated with port number, every time you run the client code.
As far as I understood, you mentioned -
Connected by ('127.0.0.1', 56051)
is shown on the first console which is your server console. so this port number is port number of client socket. not the server socket.
In the server code, you are using, s.accept(), this function returns the connection temporary id and the address of the client which made the request. same thing you are trying to print in the code.
As #ottomeister pointed out, the process name was the first giveaway. The process name should have been Python but it showed VS Code instead, which is indicative that the port 51495 is opened by the VS Code process and has nothing to do with our socket module code.
The way the context manager was setup means that the connection will be closed the moment the last line (in this case, socket.sendall()) is executed. So the server socket is not active anymore.
I run netstat after the client socket has connected, by this point the server port is closed.
When I monitor the ports status while the server port is open (before the client socket connects with it) then sure enough 65432 is what appeared. This is confirmed in netstat, lsof and also nmap. A simple print statement after the socket connection is successful will also confirmed that the server port is in fact using the specified port number, which is 65432.
Sorry for the inconvenience, and again much appreciation to Ottomeister for first pointing this out.
my question is about sending data via Ethernet using Python and Socket.
I've just created a socket on Python side, I think the code is just simple and understandable. In this way I'd like just send data outside the computer.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 'tcp')
host = socket.gethostname()
port = 12345 # Example of a port
s.connect((host, port)) # set server connection((ip_server, port_server))
s.send("Data to send")
print s.recv(1024) # receive data form the socket; argument is a bufsize
s.close
And if I create the socket right above, then the send data go via the port outside? Is it enough to for data to go out via the port? Using some sniffer programs I should see the data in some way?
Unfortunately it doesn't work.
I have such a problem:
return getattr(self._sock,name)(*args)
socket.error: [Errno 10061] and the comment is : can't set the connection because the destination computer refuses it
I can't understand why if I create a socket in this way
from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.bind(("192.168.1.10",26000))
print s.recvfrom(4096)[0]
and I try to send to it a broadcast packet like this
from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
s.sendto("hey!", ("<broadcast>", 26000))
it doesn't work (it hangs on the recvfrom()) but if I try to bind it to "0.0.0.0" it receives the packet correctly.
I know that 0.0.0.0 means that every address on every interface will be listening on that port, but why binding directly to an address makes it don't receive the packet?
Operating system: OSX 10.9.2, Python version: 2.7.6
Even if I'm not running Linux, I tried binding the socket to the subnet broadcast address anyway, same results.
If the operating system is Linux then try to bind socket to the subnet broadcast address.
For example, if your ifconfig settings are inet addr:192.168.0.62 Bcast:192.168.0.255 Mask:255.255.255.0then bind your receiver socket to 192.168.0.255. On Linux you won't be able to use your regular IP address
There is a previous discussion on the topic here
In order to Listen to Broadcast packets you need to use the following.
sock.bind(("<broadcast>", port_num))
or
sock.bind(("", port_num))
I just started with networking and am writing a very simple code for multicasting. I am still not sure about the different interfaces. Some examples used "0.0.0.0" while others have used "127.0.0.1".
Code for Server
import socket
import sys
import time
ANY = socket.gethostbyname('localhost')
S_PORT = 1501
M_ADDR = "224.168.2.9"
M_PORT = 1600
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEPORT,1)
sock.bind((ANY,S_PORT))
sock.setsockopt(socket.IPPROTO_IP,socket.IP_MULTICAST_TTL,255)
while 1:
message = raw_input("Enter message: ")
sock.sendto(message,(M_ADDR,M_PORT))
if message == "exit":
break
sock.close()
Code for Client
import socket
import time
import sys
ANY = socket.gethostbyname('localhost')
M_ADDR = "224.168.2.9"
M_PORT = 1600
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEPORT,1)
sock.bind((ANY,M_PORT))
sock.setsockopt(socket.IPPROTO_IP,socket.IP_MULTICAST_TTL,255)
status = sock.setsockopt(socket.IPPROTO_IP,socket.IP_ADD_MEMBERSHIP,socket.inet_aton(M_ADDR) + socket.inet_aton(ANY))
while 1:
data,addr = sock.recvfrom(1024)
print "Received message from " + str(addr) + " : " + data
if data == "exit":
break
sock.close()
The Client code runs properly and is waiting to receive message on the socket. But the Code Server crashes as soon as I enter any message.
Traceback (most recent call last):
File "multicast_server.py", line 17, in <module>
sock.sendto(message,(M_ADDR,M_PORT))
socket.error: [Errno 49] Can't assign requested address
What is causing this issue ?
The above code works if I use ANY = "0.0.0.0". Why is that ? What changes ?
In IPv4, 0.0.0.0 is a special address, aka INADDR_ANY, that means "bind every possible address on every interface".
So, the multicast network at 224.168.2.9, if it's reachable at all, will certainly be reachable from a socket bound to 0.0.0.0.
Meanwhile, 127.0.0.1 is a special address, aka INADDR_LOOPBACK, that means "bind localhost only on the loopback device". There's no way to reach anything but the local host itself on that socket. In particular, you can't reach your multicast network. Whether you get an ENETUNREACH, ENETDOWN, or EADDRNOTAVAIL is platform-specific, but whether it works is not—it can't possibly work.
If you want to test multicasting without testing across multiple computers, you will need to set up a loopback network with more than one address, so you can bind the client, the server, and the multicast group all to different addresses within that network.
When you use "0.0.0.0" or "" for networking in python, it opens up to any IP inbound. For your case, I would use "0.0.0.0" or "127.0.0.1" (if you are not comfortable opening up to the world.)
get your device ip address
ubuntu: ifcongfig
choose the ip address from any ethernet ,loop, wlan
replace M_ADDR with that ip address
I'm new to Sockets, please excuse my complete lack of understanding.
I have a server script(server.py):
#!/usr/bin/python
import socket #import the socket module
s = socket.socket() #Create a socket object
host = socket.gethostname() #Get the local machine name
port = 12397 # Reserve a port for your service
s.bind((host,port)) #Bind to the port
s.listen(5) #Wait for the client connection
while True:
c,addr = s.accept() #Establish a connection with the client
print "Got connection from", addr
c.send("Thank you for connecting!")
c.close()
and client script (client.py):
#!/usr/bin/python
import socket #import socket module
s = socket.socket() #create a socket object
host = '192.168.1.94' #Host i.p
port = 12397 #Reserve a port for your service
s.connect((host,port))
print s.recv(1024)
s.close
I go to my desktop terminal and start the script by typing:
python server.py
after which, I go to my laptop terminal and start the client script:
python client.py
but I get the following error:
File "client.py", line 9, in
s.connect((host,port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
I've tried using different port numbers to no avail. However, I was able to get the host name using the same ip and the gethostname() method in the client script and I can ping the desktop (server).
Instead of
host = socket.gethostname() #Get the local machine name
port = 12397 # Reserve a port for your service
s.bind((host,port)) #Bind to the port
you should try
port = 12397 # Reserve a port for your service
s.bind(('', port)) #Bind to the port
so that the listening socket isn't too restricted. Maybe otherwise the listening only occurs on one interface which, in turn, isn't related with the local network.
One example could be that it only listens to 127.0.0.1, which makes connecting from a different host impossible.
This error means that for whatever reason the client cannot connect to the port on the computer running server script. This can be caused by few things, like lack of routing to the destination, but since you can ping the server, it should not be the case. The other reason might be that you have a firewall somewhere between your client and the server - it could be on server itself or on the client. Given your network addressing, I assume both server and client are on the same LAN, so there shouldn't be any router/firewall involved that could block the traffic. In this case, I'd try the following:
check if you really have that port listening on the server (this should tell you if your code does what you think it should): based on your OS, but on linux you could do something like netstat -ntulp
check from the server, if you're accepting the connections to the server: again based on your OS, but telnet LISTENING_IP LISTENING_PORT should do the job
check if you can access the port of the server from the client, but not using the code: just us the telnet (or appropriate command for your OS) from the client
and then let us know the findings.
Assume s = socket.socket()
The server can be bound by following methods:
Method 1:
host = socket.gethostname()
s.bind((host, port))
Method 2:
host = socket.gethostbyname("localhost") #Note the extra letters "by"
s.bind((host, port))
Method 3:
host = socket.gethostbyname("192.168.1.48")
s.bind((host, port))
If you do not exactly use same method on the client side, you will get the error: socket.error errno 111 connection refused.
So, you have to use on the client side exactly same method to get the host, as you do on the server. For example, in case of client, you will correspondingly use following methods:
Method 1:
host = socket.gethostname()
s.connect((host, port))
Method 2:
host = socket.gethostbyname("localhost") # Get local machine name
s.connect((host, port))
Method 3:
host = socket.gethostbyname("192.168.1.48") # Get local machine name
s.connect((host, port))
Hope that resolves the problem.
host = socket.gethostname() # Get the local machine name
port = 12397 # Reserve a port for your service
s.bind((host,port)) # Bind to the port
I think this error may related to the DNS resolution.
This sentence host = socket.gethostname() get the host name, but if the operating system can not resolve the host name to local address, you would get the error.
Linux operating system can modify the /etc/hosts file, add one line in it. It looks like below( 'hostname' is which socket.gethostname() got).
127.0.0.1 hostname
in your server.py file make : host ='192.168.1.94' instead of host = socket.gethostname()
Pay attention to change the port number. Sometimes, you need just to change the port number. I experienced that when i made changes over changes over syntax and functions.
I was being able to ping my connection but was STILL getting the 'connection refused' error. Turns out I was pinging myself! That's what the problem was.
I was getting the same problem in my code, and after thow days of search i finally found the solution, and the problem is the function socket.gethostbyname(socket.gethostname) doesnt work in linux so instead of that you have to use socket.gethostbyname('put the hostname manually') not socket.gethostbyname('localhost'), use socket.gethostbyname('host') looking with ifconfig.
try this command in terminal:
sudo ufw enable
ufw allow 12397