I'm trying to connect a Flask server with C++ client through a socket connection:
Server:
from flask import Flask
from os.path import dirname, abspath
from queue import Queue
import base64
import cv2
import numpy as np
from PIL import Image
import io
from object_detection import detect_object
d = dirname(dirname(abspath(__file__)))
app = Flask(__name__)
app.queue = Queue()
#app.route("/")
def home():
return "Hello"
#app.route("/")
def test_live(message):
app.queue.put(message['data'])
img_bytes = base64.b64decode(app.queue.get())
img_np = np.array(Image.open(io.BytesIO(img_bytes)))
img_np = detect_object(img_np)
frame = cv2.imencode('.jpg', cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB))[
1
].tobytes()
base64_bytes = base64.b64encode(frame)
base64_string = base64_bytes.decode('utf-8')
if __name__ == '__main__':
app.run(app, host = '127.0.0.1', port = 5000, debug = True)
C++ client
#include <iostream>
#include <string>
#include <WS2tcpip.h>
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
using namespace cv;
void main()
{
string ipAddress = "127.0.0.1"; // IP Address of the server
int port = 5000; // Listening port # on the server
// Initialize WinSock
WSAData data;
WORD ver = MAKEWORD(2, 2);
int wsResult = WSAStartup(ver, &data);
if (wsResult != 0)
{
cerr << "Can't start Winsock, Err #" << wsResult << endl;
return;
}
// Create socket
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET)
{
cerr << "Can't create socket, Err #" << WSAGetLastError() << endl;
WSACleanup();
return;
}
// Fill in a hint structure
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET, ipAddress.c_str(), &hint.sin_addr);
// Connect to server
int connResult = connect(sock, (sockaddr*)&hint, sizeof(hint));
if (connResult == SOCKET_ERROR)
{
cerr << "Can't connect to server, Err #" << WSAGetLastError() << endl;
closesocket(sock);
WSACleanup();
return;
}
// Do-while loop to send and receive data
char buf[4096];
string userInput;
do
{
// Prompt the user for some text
cout << "> ";
getline(cin, userInput);
if (userInput.size() > 0) // Make sure the user has typed in something
{
// Send the text
Mat frame;
frame = imread(userInput.c_str(), IMREAD_COLOR);
int imgSize = frame.total() * frame.elemSize();
int sendResult = send(sock, (const char*) frame.data, imgSize, 0);
if (sendResult != SOCKET_ERROR)
{
// Wait for response
ZeroMemory(buf, 4096);
int bytesReceived = recv(sock, buf, 4096, 0);
if (bytesReceived > 0)
{
// Echo response to console
cout << "SERVER> " << string(buf, 0, bytesReceived) << endl;
}
}
}
} while (userInput.size() > 0);
// Gracefully close down everything
closesocket(sock);
WSACleanup();
}
I'm getting this error on the server when I try to send a image from the client:
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [10/Feb/2020 11:45:40] code 400, message Bad request syntax ('54043/0.--+*/--1//2-.2-./+**(\'#! \x19\x1c\x1a\x12\x19\x16\x0f\x1a\x17\x13 \x1e\x14%"\x16*+\x17,-\x180.\x1830\x1b63\x1c96\x1b:7\x1c;8\x1e?;\x1eA= C?\x1fGB#JH&QN*WT-\\Y2_\\5b_9ga<jd>jc>jc>jc>jc7e_6f`9ic:mf;oh:ng9pg;riCxn<qg;sh=uj:ti=wlB{sC|t?ytB|wE}xBzu#yq#yq?xo:vl7rj;wo;wo;wo;vn7rj5nf0f_+^Z\'VS\'TQ\'OM%LJ\x1eCA\x1c<;\x1654\x17//\x15--\x13--\x1400\x13++')
127.0.0.1 - - [10/Feb/2020 11:45:40] "54043/0.--+*/--1//2-.2-./+**('#! %"*+,-0.306396:7;8?;A= C?GB#JH&QN*WT-\Y2_\5b_9ga<jd>jc>jc>jc>jc7e_6f`9ic:mf;oh:ng9pg;riCxn<qg;sh=uj:ti=wlB{sC|t?ytB|wE}xBzu#yq#yq?xo:vl7rj;wo;wo;wo;vn7rj5nf0f_+^Z'VS'TQ'OM%LJCA<;54//----00++" HTTPStatus.BAD_REQUEST -
127.0.0.1 - - [10/Feb/2020 11:46:00] code 400, message Bad request syntax ('54043/0.--+*/--1//2-.2-./+**(\'#! \x19\x1c\x1a\x12\x19\x16\x0f\x1a\x17\x13 \x1e\x14%"\x16*+\x17,-\x180.\x1830\x1b63\x1c96\x1b:7\x1c;8\x1e?;\x1eA= C?\x1fGB#JH&QN*WT-\\Y2_\\5b_9ga<jd>jc>jc>jc>jc7e_6f`9ic:mf;oh:ng9pg;riCxn<qg;sh=uj:ti=wlB{sC|t?ytB|wE}xBzu#yq#yq?xo:vl7rj;wo;wo;wo;vn7rj5nf0f_+^Z\'VS\'TQ\'OM%LJ\x1eCA\x1c<;\x1654\x17//\x15--\x13--\x1400\x13++')
127.0.0.1 - - [10/Feb/2020 11:46:00] "54043/0.--+*/--1//2-.2-./+**('#! %"*+,-0.306396:7;8?;A= C?GB#JH&QN*WT-\Y2_\5b_9ga<jd>jc>jc>jc>jc7e_6f`9ic:mf;oh:ng9pg;riCxn<qg;sh=uj:ti=wlB{sC|t?ytB|wE}xBzu#yq#yq?xo:vl7rj;wo;wo;wo;vn7rj5nf0f_+^Z'VS'TQ'OM%LJCA<;54//----00++" HTTPStatus.BAD_REQUEST -
I have read that's because my client is trying to connect via HTTPS but I don't find how to change it.
Thanks for your help
Related
I want that my ESP32 takes a picture, stores it in the SPIFFS and then send it via a WiFiClient from WiFi.h. The reciever is a python server socket. The server should store it as a jpg in the local windows filesystem.
So far i can connect the esp to the wifi, take a picture and store it in the SPIFFS. In another project i already send char from the WiFiClientto the python server without any problem. But if i want to send the picture a bytes with WiFiClient.print() it only sends two bytes and that cannot be correct i think.
What i need is help for sending the bytes of the jpg from the esp and decode the recieved bytes from the python socket server and store the bytes as a jpg. If there is a better way then using a the esp32 WiFiClient-class or python socket, feel free to say it.
Here is my ESP code (yes i know. The structure is not the best. Its only an example for me):
#include <WiFi.h>
const char* ssid = "xxx";
const char* password = "xxx";
const uint16_t port = xxx;
const char * host = "xxx";
/*********
Rui Santos
Complete instructions at https://RandomNerdTutorials.com/esp32-cam-projects-ebook/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*********/
#include "esp_camera.h"
//#include "SPI.h"
//#include "driver/rtc_io.h"
#include <FS.h>
#include <SPIFFS.h>
#define CAMERA_MODEL_WROVER_KIT
#if defined(CAMERA_MODEL_WROVER_KIT)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 21
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 19
#define Y4_GPIO_NUM 18
#define Y3_GPIO_NUM 5
#define Y2_GPIO_NUM 4
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
#else
#error "Camera model not selected"
#endif
// Photo File Name to save in SPIFFS
#define FILE_PHOTO "/photo.jpg"
File file;
camera_fb_t * fb;
WiFiClient client;
void setup() {
//WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
Serial.begin(115200);
Serial.println();
// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
if (!SPIFFS.begin(true)) {
Serial.println("An Error has occurred while mounting SPIFFS");
ESP.restart();
}
else {
delay(500);
Serial.println("SPIFFS mounted successfully");
}
// Print ESP32 Local IP Address
Serial.print("IP Address: http://");
Serial.println(WiFi.localIP());
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.pixel_format = PIXFORMAT_JPEG;
if(psramFound()){
config.frame_size = FRAMESIZE_UXGA;
config.jpeg_quality = 10;
config.fb_count = 2;
} else {
config.frame_size = FRAMESIZE_SVGA;
config.jpeg_quality = 12;
config.fb_count = 1;
}
// Initialize camera
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init failed with error 0x%x", err);
return;
}
}
void loop()
{
if (!client.connect(host, port)) {
Serial.println("Connection to host failed");
delay(1000);
return;
}
Serial.println("Connected to server successful!");
fb = NULL; // pointer
bool ok = 0; // Boolean indicating if the picture has been taken correctly
do {
// Take a photo with the camera
Serial.println("Taking a photo...");
fb = esp_camera_fb_get();
if (!fb) {
Serial.println("Camera capture failed");
return;
}
// Photo file name
Serial.printf("Picture file name: %s\n", FILE_PHOTO);
file = SPIFFS.open(FILE_PHOTO, FILE_WRITE);
// Insert the data in the photo file
if (!file) {
Serial.println("Failed to open file in writing mode");
}
else {
file.write(fb->buf, fb->len); // payload (image), payload length
Serial.print("The picture has been saved in ");
Serial.print(FILE_PHOTO);
Serial.print(" - Size: ");
Serial.print(file.size());
Serial.println(" bytes");
}
// check if file has been correctly saved in SPIFFS
ok = checkPhoto(SPIFFS);
} while ( !ok );
while(file.available()){
Serial.println(client.print(file.read()));
}
// Close the file
file.close();
esp_camera_fb_return(fb);
delay(1000);
}
// Check if photo capture was successful
bool checkPhoto( fs::FS &fs ) {
File f_pic = fs.open( FILE_PHOTO );
unsigned int pic_sz = f_pic.size();
return ( pic_sz > 100 );
}
and this is my python code:
import socket
s = socket.socket()
s.bind(('yyy', yyy ))
s.listen(0)
while True:
try:
print("-------------------------------------------------------------------")
client, addr = s.accept()
print("Accepted a connection request from %s:%s"%(addr[0], addr[1]));
while True:
content = client.recv(131072)
if len(content) ==0:
break
else:
msg_recieved = content
msg_recieved_decode = content.decode()
print(msg_recieved)
print("Message decoded recieved: " + msg_recieved_decode)
f = open("demofile.jpg", "wb")
f.write(msg_recieved)
f.close()
print("Client closed")
client.close()
except Exception as e:
print("===================================================================")
print("Something went wrong")
print(e)
print("===================================================================")
i try to create a client written in c++ and a server using python flask. The task is simple, client connect and get data from server, then display it on console. I have two piece of code:
Server:
from flask import Flask
app = Flask(__name__)
#app.route('/hello')
def hello():
return "hello".encode("utf-16")
if __name__ == "__main__":
app.run(debug=True,host="127.0.0.1")
Client:
BOOL bResults = FALSE;
bool ret = false;
DWORD dwDownloaded = 0;
WCHAR wDataRecv[1024] = {0};
HINTERNET hConnect = NULL;
HINTERNET hRequest = NULL;
DWORD dwSize = 0;
HINTERNET hSession = WinHttpOpen(L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0); # open session to connect
hConnect = WinHttpConnect(hSession, L"localhost", (port == 0) ? INTERNET_DEFAULT_HTTP_PORT : port, 0); # connect to localhost with port 80 or custom port (this time i use port 5000)
if (!hConnect)
goto Free_And_Exit;
hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/hello", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
if (hRequest) {
bResults = WinHttpSendRequest(hRequest, NULL, 0,WINHTTP_NO_REQUEST_DATA, 0,0, 0);# send GET request
}
if (bResults)
bResults = WinHttpReceiveResponse(hRequest, NULL);
if (bResults)
{
dwSize = 0;
if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) {
std::cout << "WinHttpQueryDataAvailable failed with code: " << GetLastError();
}
if (!WinHttpReadData(hRequest, wDataRecv, dwSize, &dwDownloaded)) {
std::cout << "WinHttpReadData failed with code: " << GetLastError();
}
std::wcout << wDataRecv; # wcout wont print anything to console
}
Free_And_Exit: #clean up
if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
return ret;
I noticed that the data return from server like:
b'\xfe\xff\hello'
Why 0xFEFF is there ?
Its is BOM (byte order mark). I just need to decode from the client or use:
return "hello".encode('UTF-16LE') # not UTF-16
I've been trying to listen to multicast UDP messages from my Yeelight smart bulb. At a regular interval, the bulb broadcasts its presence on IP 239.255.255.250 port 1982. Also, when sending a specific request (found on page 5 - section 3.1) on the same IP and port, the bulb will respond.
Using sockets, I am trying to establish the communication. On two machines (macOS and Linux), the Python program shown below run at the REPL works, but the Rust code and C++ code also shown below (essentially doing the same thing) doesn't. The Rust program seems to successfully receive 0 bytes twice and then hangs waiting. In the C++ program, the recv function just hangs right away, never returning.
What could be the problem? Why can only Python successfully communicate?
import socket as s
import struct
sock = s.socket(s.AF_INET, s.SOCK_DGRAM, s.IPPROTO_UDP)
sock.setsockopt(s.IPPROTO_IP, s.IP_ADD_MEMBERSHIP, struct.pack("4sL", s.inet_aton("239.255.255.250"), s.INADDR_ANY))
sock.sendto("M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1982\r\nMAN: \"ssdp:discover\"\r\nST: wifi_bulb\r\n".encode('UTF-8'), ("239.255.255.250", 1982))
sock.recv(4096) # Message received successfully right away from first call
#[macro_use] extern crate log;
use socket2::{Socket, Domain, Type, Protocol, SockAddr};
use std::net::{SocketAddrV4, Ipv4Addr};
fn main() {
env_logger::init();
let yeelight_ip = Ipv4Addr::new(239, 255,255, 250);
let yeelight_port: u16 = 1982;
let socket = Socket::new(
Domain::ipv4(),
Type::dgram(),
Some(Protocol::udp())
).expect("Failed to create socket!");
socket.join_multicast_v4(
&yeelight_ip,
&Ipv4Addr::UNSPECIFIED
).expect("Unable to join multicast broadcast!");
let msg = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1982\r\nMAN: \"ssdp:discover\"\r\nST: wifi_bulb\r\n";
match socket.send_to(
msg.as_bytes(),
&SockAddr::from(
SocketAddrV4::new(
yeelight_ip,
yeelight_port
)
)
) {
Ok(bytes_sent) => {
// Some lines of debug printing
},
Err(_) => eprintln!("Error broadcasting request for identification!")
loop {
let mut buffer = Vec::with_capacity(1024 * 1024);
let received_bytes = socket
.recv(&mut buffer)
.expect("Unable to receive message!");
debug!("Received {} bytes", received_bytes);
}
}
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <string>
#include <array>
const std::string msg = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1982\r\nMAN: \"ssdp:discover\"\r\nST: wifi_bulb\r\n";
int main() {
auto yeelight_ip = in_addr();
inet_aton("239.255.255.250", &yeelight_ip);
unsigned int yeelight_port = 1982;
auto sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
std::cerr << "Created socket!" << std::endl;
auto mreq = ip_mreq();
mreq.imr_interface.s_addr = INADDR_ANY;
mreq.imr_multiaddr.s_addr = yeelight_ip.s_addr;
if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) != 0) {
std::cerr << "Error joining multicast!" << std::endl;
exit(errno);
}
else {
std::cerr << "Joined multicast!" << std::endl;
}
auto addr = sockaddr_in();
addr.sin_port = yeelight_port;
for (int i = 0; i < 8; i++) addr.sin_zero[i] = 0;
addr.sin_family = AF_INET;
addr.sin_addr = yeelight_ip;
if (sendto(sock, msg.c_str(), msg.length(), 0, (sockaddr*)(&addr), sizeof(addr)) == -1) {
std::cerr << "Error broadcasting request for identification!" << std::endl;
std::cerr << errno << std::endl;
}
else {
std::cerr << "Sent broadcast request for idetification!" << std::endl;
}
while (true) {
std::array<char, 1024 * 1024> buffer;
auto bytes_read = recv(sock, buffer.data(), buffer.size(), 0);
if (bytes_read == -1) {
std::cerr << "Unable to receive message!" << std::endl;
std::cerr << errno << std::endl;
}
else {
std::cerr << "Read " << bytes_read << " bytes..." << std::endl;
std::cout << std::string(buffer.begin(), buffer.begin() + bytes_read) << std::endl;
}
}
return 0;
}
The Python program works as expected due to Python nicely implementing conversions behind the scenes.
The C(++) program didn't work because the endianness of the port was wrong. I forgot that I have to use addr.sin_port = htons(yeelight_port);.
As for the Rust program, I forgot that with_capacity only allocated the internal buffer, but the Vec is still empty. The solution, described here, is to call buffer.resize(buffer.capacity(), 0);.
I have a multicast packet from a capture using tcpdump. I can replay the packet using tcpreplay -i eth0 on.pcap and I can receive it on another machine using tcpdump.
I have tried c code and python code to try and capture this packet without success. I've tried both on MacOS and Raspian (Rpi 3b).
https://mega.nz/#!ELAgBSDL!XZ3EXCkDBsLLwFn8J1ofWuMm4Z7sssOZPuZVEpmRqvs
here is a c code example:
/*
multicast.c
The following program sends or receives multicast packets. If invoked
with one argument, it sends a packet containing the current time to an
arbitrarily chosen multicast group and UDP port. If invoked with no
arguments, it receives and prints these packets. Start it as a sender on
just one host and as a receiver on all the other hosts
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <stdio.h>
#define EXAMPLE_PORT 2068
#define EXAMPLE_GROUP "226.2.2.2"
main(int argc)
{
struct sockaddr_in addr;
int addrlen, sock, cnt;
struct ip_mreq mreq;
char message[50];
/* set up socket */
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0)
{
perror("socket");
exit(1);
}
bzero((char *)&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(EXAMPLE_PORT);
addrlen = sizeof(addr);
if (argc > 1)
{
/* send */
addr.sin_addr.s_addr = inet_addr(EXAMPLE_GROUP);
while (1)
{
time_t t = time(0);
sprintf(message, "time is %-24.24s", ctime(&t));
printf("sending: %s\n", message);
cnt = sendto(sock, message, sizeof(message), 0,
(struct sockaddr *) &addr, addrlen);
if (cnt < 0)
{
perror("sendto");
exit(1);
}
sleep(5);
}
}
else
{
/* receive */
if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0)
{
perror("bind");
exit(1);
}
mreq.imr_multiaddr.s_addr = inet_addr(EXAMPLE_GROUP);
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
&mreq, sizeof(mreq)) < 0)
{
perror("setsockopt mreq");
exit(1);
}
while (1)
{
cnt = recvfrom(sock, message, sizeof(message), 0,
(struct sockaddr *) &addr, &addrlen);
if (cnt < 0)
{
perror("recvfrom");
exit(1);
}
else if (cnt == 0)
{
break;
}
printf("%s: message = \"%s\"\n", inet_ntoa(addr.sin_addr), message);
}
}
}
Here is a python example:
#!/usr/bin/env python
import socket
import binascii
import sys
MCAST_GRP = '226.2.2.2'
MCAST_PORT = 2068
MCAST_IFACE = '192.168.168.200'
def joinMcast(mcast_addr,port,if_ip):
"""
Returns a live multicast socket
mcast_addr is a dotted string format of the multicast group
port is an integer of the UDP port you want to receive
if_ip is a dotted string format of the interface you will use
"""
#create a UDP socket
mcastsock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#allow other sockets to bind this port too
mcastsock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
#explicitly join the multicast group on the interface specified
mcastsock.setsockopt(socket.SOL_IP,socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(mcast_addr)+socket.inet_aton(if_ip))
#finally bind the socket to start getting data into your socket
mcastsock.bind((mcast_addr,port))
return mcastsock
def main():
sock = joinMcast(MCAST_GRP, MCAST_PORT, MCAST_IFACE)
while True:
print >>sys.stderr, '\nwaiting to receive message'
print sock.recv(1024)
if __name__ == '__main__':
main()
I made a simple webserver using c. I can connect to it via a web browser and it works fine.
The goal of this webserver was to exploit it. So I wrote a simple python script that sends malicious data to the server. However, I only get an error message on the server saying: "Bad file descriptor".
C-Server Main:
int main(void) {
int sockfd, new_sockfd, yes=1;
struct sockaddr_in host_addr, client_addr;
socklen_t sin_size;
printf("Accepting web requests on port %d\n", PORT);
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
error_and_exit("in socket");
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
error_and_exit("setting socket option SO_REUSEADDR");
host_addr.sin_family = AF_INET;
host_addr.sin_port = htons(PORT);
host_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(host_addr.sin_zero), '\0', 8);
if (bind(sockfd, (struct sockaddr *)&host_addr, sizeof(struct sockaddr)) == -1)
error_and_exit("binding to socket");
if (listen(sockfd, 20) == -1)
error_and_exit("listening on socket");
while(1) { // Accept loop
sin_size = sizeof(struct sockaddr_in);
new_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &sin_size);
if(new_sockfd == -1)
error_and_exit("accepting connection");
handle_connection(new_sockfd, &client_addr);
}
return 0;
}
python code:
import socket
import struct
import sys
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('127.0.0.1', 8000)
sock.connect(server_address)
shellcode =(....)
values = ....
try:
sock.sendall(values)
finally:
sock.close()
Notes:
1.
the accept function (from <sys/socket.h>) in the while(1) loop returns -1, calling error_and_exit("accepting connection"). So the Server never executes handle_connection for my python client.
2.
Code for error_and_exit function:
void error_and_exit(char *message) {
char error_message[100];
strcpy(error_message, " Error ");
strncat(error_message, message, 83);
perror(error_message);
exit(-1);
}