Well, it's nothing much to present but, I wanted to make my cellphone and PC somehow connected, and at very first steps of research, I made these VERY SIMPLE tests:
#this is for the udp client file
import socket as soc
import os
server = "192.167.1.4"
serverPort = 12000
value = 0
sockobj = soc.socket(soc.AF_INET, soc.SOCK_DGRAM)
while True:
message = 'This is my secret message: '
message += input("Enter your message: ")
data = message.encode(encoding="UTF-8")
sockobj.sendto(data, (server, serverPort))
if not value:
# os.system("traceroute 192.168.1.4")
value += 1
import time
time.sleep(5)
print("sleep ended")
message, address = sockobj.recvfrom(2048)
print("I got", message.decode())
sockobj.close()
__
and this is for the udp server file
import socket as soc
import time
server = ''
serverPort = 12000
sockobj = soc.socket(soc.AF_INET, soc.SOCK_DGRAM)
sockobj.bind((server, serverPort))
while True:
message, clientaddress = sockobj.recvfrom(2048)
print("I got the client's address as: ", clientaddress)
print("I got the message")
print("...modifying, this might take time")
message = message.decode().upper()
data = ("Server: {} data with {} length".format(message, len(message.split()))).encode(encoding="UTF-8")
time.sleep(1.5)
sockobj.sendto(data,clientaddress)
print("SENT!")
sockobj.close()
I currently have QPython installed on my android device and am running the server file from there. And the devices do connect and communicate!!
So, at this point, I wanted to see how the packets travelled from my PC to cell phone, running traceroute from terminal was no use, connection was refused to my cell phone's local IP: 192.167.1.4, I thought so I'd do a system call from the udp client script, but no luck from there either. I guess is that the packets would bounce from my PC to router to my cell phone, but, that's just a guess. So, How can I trace my packets for this script?
Probably better served as a comment. But seeing as their has been almost no activity on this post, I figured to just post it as an answer.
Have you tried using: https://github.com/CiscoDevNet/dnac-python-path-trace
It does pretty much what you seem to be looking for. You can look at the code to get an idea of how it works.
Related
I could like to do a bi-directional communication between server and client. I end up with a problem.
I am getting the host ip from server and then connecting to it. but i am not sure how to get it from one def to another.
If i specify host ip directly it works. But i dont want it like that.
Please post your idea.
client program:
import socket
import os
import re
class cont():
def get_bd(self):
def receive_bd(self):
# receive broadcast
def get_ip_data(ether_adapter):
ip_data = os.popen("ifconfig " + ether_adapter)
for line in ip_data:
match2 = re.search(r'broadcast\s+(\d+.\d+.\d+.\d+)', line)
if match2:
bd = match2.group(1)
return bd
if __name__ == "__main__":
ethernet_card = "wlp1s0"
inet_list = get_ip_data(ethernet_card)
# print(inet_list)
self.sock.bind((inet_list, 12345))
msg, client = self.sock.recvfrom(1024)
a = (msg.decode())
#here i receive the ip of my server to the client
host = a
def send_ls(self):
#i want the host i received in that receive_bd as a host here
host= "here?if i give direct ip of server it works which i dont want to do but directly get it from receive_bd "
port=4343
address=host,port
client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while (True):
msg=input("Controller 1 :")
client.sendto(bytearray(msg,"utf-8"),address)
reply=client.recvfrom(1000)
recved=str(reply)
print("Main Controller: %s " %(recved))
if __name__=='__main__':
c=cont()
c.send_ls()
It looks to me like you only need to enable sending to a broadcast address. That's done with client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1).
I changed your send_ls as shown below and I'm able to communicate with a UDP echo program listening on port 4343. Here 192.168.40.255 is the subnet broadcast address.
def send_ls(self):
host = '192.168.40.255'
port=4343
address=host,port
client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
while (True):
msg=input("Controller 1 :")
client.sendto(bytearray(msg,"utf-8"),address)
reply=client.recvfrom(1000)
recved=str(reply)
print("Main Controller: %s " %(recved))
Sample output shown below. Note that the server side didn't specify an address in the bind. So the server is able to receive messages sent to the broadcast address, but when it sends back, the response comes from the unicast address of the server's network adapter.
Controller 1 :Hello there
Main Controller: (b'Hello there', ('192.168.40.128', 4343))
Controller 1 :You still there?
Main Controller: (b'You still there?', ('192.168.40.128', 4343))
Controller 1 :
One more note: If your client code here remembers the address it gets back from the reply, then subsequent messages it sends don't need to go to the broadcast address. That is, simply assign reply[1] to address after the recvfrom, and then you won't be sending broadcasts after the first message (which is better for the performance of your network).
I am trying to do wireless communications between a PC (macbook) and a Raspberry Pi 2 using python's socket module (python 2.7). The server is the PC and the client is the Pi.
When I run the code (server first then client) both scripts get stuck on the socket.accept() and socket.connect() methods respectfully.
What is funny is that when I do the reverse (Pi being the server and PC being the client) the code works fine, with data been sent correctly.
The scripts below are meant to loop forever whilst incrementing a counter sent over (I increment the port's after each succesful transfer to avoid '[Errno 48] Address already in use' (probably terrible practice I know))
My client script:
import socket
import sys
def read(port):
s = socket.socket()
host = '10.19.92.44' #(IP address of PC (server))
s.connect((host,port))
try:
msg = s.recv(1024)
s.close()
except socket.error, msg:
sys.stderr.write('error %s'%msg[1])
s.close()
print 'close'
sys.exit(2)
return msg
if __name__ == '__main__':
port = 1025
while True:
print 'hey, checking TCP socket'
data = read(port)
print 'i just read %s' % data
print 'port num is: %d' % port
port = port + 1
My server script:
import socket
import time
def send(data, port):
s = socket.socket()
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print 'Got connection from',addr
c.send(data)
c.close()
if __name__ == '__main__':
port = 1025
num = 1
while True:
print 'hey, sending data'
words = 'helloWorld'
data = words + str(num)
print 'send data: %s' % data
send(data,port)
port = port + 1
num = num + 1
As I mentioned when I swap roles (and replace the server IP address in the client script to the Pis 172.17.33.125) the code works fine...
Any ideas/suggestions?
Thank you very much
I don't have an immediate answer, but I have a couple of ideas.
Your PC and Pi seem to be in different networks. The PC's address is 10.19.92.44, while Pi's is 172.17.33.125. There's a probability that 10.19.92.44 isn't the address you need. In order to find out what is the correct PC IP address to use in the application:
Issue networksetup -listallhardwareports to figure out the name of your wifi interface (should be like en0, en1).
Issue ifconfig, find the wifi interface. The IP address attached to this interface is the one you need.
Another option is to install wireshark on the PC, set up a working system (server-Pi, client-PC) and use wireshark to capture the traffic between the PC and Pi. Wireshark makes it easy to figure out IP addresses of both parties. I would advise to have this program installed whenever you want to debug a complicated networking issue.
First off, thanks to all users because I learnt a lot reading questions and answers on this website.
I'm starting to learn Python and I'm trying to send information of a PC over internet through sockets to another PC. It all worked great when I connected two computers of my localhost. However, I'm trying to connect with a friend's computer and I can't do it. I know (thanks to previous topics on this page) that the server needs to forward a port to his own computer. My friend already did that and, me as a client and he as a server, we haven't been able to connect.
I'd like to show you my really simple code because I'm sure I mistaken something I can't figure out what.
This is the client script:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("Public IP of server",9990))
if True:
print "Conexion establecida"
while True:
mensaje = raw_input("Mensaje a enviar: ")
if mensaje == "close":
break
else:
s.send(mensaje)
print "Mensaje enviado."
s.close()
And this is the server script:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("",9990))
s.listen(1)
sc, addr = s.accept()
print "Conexion establecida con ", str(addr[0])
while True:
recibido = sc.recv(1024)
if recibido == "close":
break
print str(addr[0]) + " dice: ", recibido
sc.close()
s.close()
The client script connect with the public ip the server and, if true, let the user send a message. The server scripts just receives the message and prints it. I hope it is enough to no not make you lose a lot of time. Lot of thanks for reading me!
I have been self-learning python since few months now , and finally learning Socket programming. As an text book exercise, I am supposed to design a half-duplex chat system . Below is the code. The first request and response are just fine , but everytime I try sending a second message from client, the server seems to be hanging. The program is TCP based.
I am suspecting that since ss.accept() is being called everytime a new message has to be sent, a new thread is being created but since I have made only 1 call to sc.connect() from client , may be my new connection at the server end is hanging there for infinite time.
As a trail : I called ss.accept() outside the while loop, ie making only 1 connection and listening to data over and over on while loop, the conversations works just fine
Can someone please have a look a the code and help me understand where exactly is the issue.
Since, I am learning, I have not moved to twisted yet. I want to learn all the basics first before I move to frameworks.
!bin/usr/env python
import socket, sys
HOST =''
PORT = 1060
ADDR =(HOST,PORT)
def userinput(sock):
usermessage = input('>')
sock.sendall(str(len(usermessage)))
return usermessage
def server():
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind(ADDR)
s.listen(1)
print 'the server is listening at',s.getsockname()
while True:
ss,sockname = s.accept()
#listen to determine the bytes sent by client
msglen = ss.recv(4096)
#accept the complete message
msg = ss.recv(int(msglen))
print 'client:', repr(msg)
servermsg = userinput(ss)
ss.sendall(servermsg)
print " ---------------"
ss.close()
def client():
sc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sc.connect(ADDR)
while True:
message = userinput(sc)
sc.sendall(message)
replylen = sc.recv(4096)
reply = sc.recv(int(replylen))
print "reply:",reply
print "----------------"
sc.close()
if sys.argv[1:] == ['server']:
server()
elif sys.argv[1:] == ['client']:
client()
else:
print >> sys.stderr,'usage:tcp_2_7.py server|client[host]'
Your trial - accepting once and then receiving multiple messages - is how you should do this. Calling accept is waiting for a new connection - you don't need to do this every time you want to send or receive a message, just as you don't want to call connect every time you want to send or receive.
Think of it this way:
When you connect to a chat server, do you connect, send a message, then disconnect immediately? No - you have a constant open connection which messages are sent through, and the connection is only closed at the end of a chat session.
From the docs on accept:
socket.accept()
Accept a connection. The socket must be bound to an
address and listening for connections. The return value is a pair
(conn, address) where conn is a new socket object usable to send and
receive data on the connection, and address is the address bound to
the socket on the other end of the connection.
i got this code from http://www.evolt.org/node/60276 and modified it to listen for a single "1" coming from the other side
but whenever i run this program it stops and python IDLE goes to non-responding on "data1,addr = UDPSock.recvfrom(1024)"
def get1():
# Server program, receives 1 if ball found
# ff1 is file w/ received data
import socket
import time
# Set the socket parameters
host = "mysystem"
port = 21567
#buf = 1024
addr = (host,port)
# Create socket (UDP) and bind to address
UDPSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
UDPSock.bind(addr)
# Receive messages
while 1:
print "waiting..............."
data1,addr = UDPSock.recvfrom(1024)
print "got 1"
if not data1:
print "Client has exited!"
break
else:
print "\nReceived message '", data1,"'"
UDPSock.close() # Close socket
print "socket closed\n"
#call some other function that uses 1
and client side
def send1():
# Client program, sends 1 if ball found
# mf1 is file with data to be sent
import socket
# Set the socket parameters
host = "mysystem"
port = 21567
buf = 1024
addr = (host,port)
# Create socket (UDP)
UDPSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
mf1=1
print mf1
# Send messages
if(UDPSock.sendto(str(mf1),addr)):
print "Sending message '",str(mf1),"'....."
# Close socket
UDPSock.close()
does anyone know what might be the cause of this? (sorry for long post)
As a second guess (I replaced my first guess with this) I suspect that you are running the receiver in IDLE and then IDLE is hanging so you can't run the client. I don't know exactly how IDLE works as I never use it, but the line containing recvfrom will stop the Python thread its running in until data is sent. So you need to start the client in a separate instance of IDLE or from the command line or something.
At any rate, I have tested the program in question on my Python with 127.0.0.1 as the host, and it worked fine, for some values of fine. The recvfrom does hang, but only until some data is sent, then it comes back with the data and prints it out and everything. You do have a bug that happens after that though. :-)