delphi – Socket Error – Indy

Bom dia pessoal,
Atualmente utilizo o componente Indy para fazer a seguinte requisição, da seguinte forma

Var
getTicker: TIdHTTP;
begin
try
try
IdSSLIOHandlerSocketOpenSSL1 :=
TIdSSLIOHandlerSocketOpenSSL.Create(nil);
getTicker := TIdHTTP.Create(nil);
getTicker.IOHandler := IdSSLIOHandlerSocketOpenSSL1;
getTicker.Request.UserAgent := ‘Mozilla/5.0 (compatible; test)’;
getTicker.ConnectTimeout := 30000;
getTicker.Get(‘www.result/ticker24hs’);
except
finally
FreeAndNil(getTicker);
end;

Este processo executa de hora em hora.
Porém de vez em quando, cai a conexão com a internet, é exibido a mensagem em abaixo :

Socket Error # 11001
Host not found

Dai então a aplicação para de executar.
Preciso que após este problema de conexão, a aplicação continue a executar o processo de hora em hora.
Porém fiz alguns testes aqui, mas sem sucesso, alguém saberia como poderia fazer isso ?

Fallo socket ESP32 (Arduino) – App (Android Studio)

Estoy intentando establecer un socket entre una aplicación Android (desarrollada en Android Studio) y un módulo ESP32 (programado con Arduino), siendo este último el servidor. Este socket deberá establecerse vía WiFi, utilizando el protocolo TCP/IP, y tanto el smartphone en el que pruebo la app como el módulo ESP32 están conectados a la misma red de área local. Tras consultar distintos ejemplos, conseguí escribir ambos códigos.

El problema es que no se establece el socket por alguna razón. He probado a escribir en un TextView de la app, dentro de la AsyncTask encargada de establecer la conexión (Comm), un mensaje indicador de que efectivamente se ha alcanzado el punto en el que se establece dicho enlace. Sin embargo, este mensaje solo me aparece cuando ordeno que se escriba antes del establecimiento del socket; si lo pongo después, no llega a aparecer. Esto me hace pensar que el socket no termina de establecerse pero tampoco da error, sino que se mantiene en un intento de conexión permanente (aunque en realidad soy novato, no tengo mucha idea de qué estará pasando).

Este es el código Java en Android Studio (cliente), y en el que creo que está el fallo:

package com.example.controlluz;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Arrays;

import static java.lang.System.out;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button button;
    private boolean on;

    String estado = "0";

    private Toast toast;
    public TextView textview;
    Comm comm;

    //Inicializo variables y establezco socket
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);

        textview = findViewById(R.id.textView);
        textview.setText("");

        //mTCPCliente = null;

        comm = new Comm();
        comm.execute(estado);
 
    }
 

    //Cuando pulso el botón se enciende o se apaga, en función de su estado anterior
    @Override
    public void onClick(View v){

        //I change button's background
        if (!on) {
            button.setBackground(this.getResources().getDrawable(R.mipmap.encendido));
            on = true;
            estado = "1";
        } else {
            button.setBackground(this.getResources().getDrawable(R.mipmap.apagado));
            on = false;
            estado = "0";
        }
    }

 

    public class Comm extends AsyncTask <String, Void, Void> {

        String ip;
        int puerto;

        Comm() {
            ip = "192.168.1.88";
            puerto = 8888;
        }

        @Override
        protected Void doInBackground(String... estado) {

            Socket sk = null;
            PrintWriter salida = null;
            BufferedReader entrada = null;
 

            try {
                sk = new Socket(ip, puerto);
                textview.setText("Hola?????");
                salida = new PrintWriter(sk.getOutputStream(), true);
                entrada = new BufferedReader(new InputStreamReader(sk.getInputStream()));
                salida.println(estado(0));
                //lectura = in.readLine();
                salida.close();
                entrada.close();
                sk.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
 
            return null;
        }
 
    }
 
}

En el IDE de Arduino veo que se conecta el módulo a la red y que la dirección IP es la deseada, pero en ningún momento aparece el mensaje que indica que hay un cliente conectado (lógicamente).

Este es el código en Arduino (servidor):

#include <WiFi.h>

const char* ssid = "PASCAL";                                  //NOMBRE ROUTER
const char* password = "1473DE3054C57C4867EB";                //CONTRASEÑA

IPAddress ip(192,168,1,88);                                   //DIRECCIÓN IP ESP8266
IPAddress gateway(192,168,1,1);                               //PUERTA DE ENLACE
IPAddress subnet(255,255,255,0);                              //MÁSCARA DE RED
WiFiServer wifiServer(8888);                                  //PUERTO DE ESCUCHA DEL SERVIDOR
WiFiClient client;
int relayPin = 23;                                            //PIN DEL RELÉ EN EL MÓDULO
char c;

                        
 

void setup(){
  Serial.begin(115200);
 
  delay(500);
 
  WiFi.begin(ssid,password);                                  //CONEXIÓN WIFI A ROUTER
  WiFi.config(ip, gateway, subnet);                           //CONFIGURACIÓN DE IP ESTÁTICA
  
  int n;
  for (n = 0; n < 30 && WiFi.status() != WL_CONNECTED; n++ ) {
    delay(500);
    Serial.println("Connecting...");
  }
  if(n==30){
    Serial.println();
    Serial.print("La conexión no ha podido establecerse");
  }else{
    Serial.print("Connected to WiFi. IP:");
    Serial.println(WiFi.localIP());
  }


 
  
  wifiServer.begin();                                         //ESTABLECER ESP8266 COMO SERVIDOR
  pinMode(relayPin, OUTPUT);                                  //CONFIGURACIÓN DEL PIN DEL RELÉ COMO PIN DE SALIDA
  digitalWrite(relayPin, LOW);                                //Se inicializa a 0 lógico, la luz permanece apagada cuando se arranca el módulo

}

void loop() {
  client = wifiServer.available();

  if(client){
    Serial.println("Client connected");
    Serial.print("Client connected with IP:");
    Serial.println(client.remoteIP());
 
    while( client.connected()){

        while (client.available()>0) {
          c = client.read();
          Serial.println(c);

          switch (c){
            case '1':
              digitalWrite(relayPin, HIGH);
              break;
            case '0':
              digitalWrite(relayPin, LOW);
              break;
          }
        }
        delay(10);
    }
    client.stop();
    Serial.println("Client disconnected");
  }
   
}

Cualquier tipo de información me vendrá bien seguro.

Muchas gracias de antemano.

pg hba.conf – postgresql only allows connections via unix socket even though my pg_hba.conf lists 127.0.0.1/32?

I have the following pg_hba.conf:

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
# IPv6 local connections:
host    all             all             ::1/128                 trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     trust
host    replication     all             127.0.0.1/32            trust
host    replication     all             ::1/128                 trust

With the above I assume host all all 127.0.0.1/32 trust would allow TCP connections from localhost. However this does not seem to be the case

(root@XenonKiloCranberry:~)# psql -U postgres
psql (11.7)
Type "help" for help.

postgres=# q

(root@XenonKiloCranberry:~)# psql -U postgres -h 127.0.0.1
psql: FATAL:  no pg_hba.conf entry for host "127.0.0.1", user "postgres", database "postgres", SSL off

Where am I going wrong?

Javascript does support socket programming

I am a javascript begginner.
For few days I am searching on how to do socket programming in JavaScript.
I noticed there is a library called SOCKET.IO which runs on NODE.JS. but is there any way to do socket programming like java,c# or python where we can create server and client by our own code. Which can run also on mobile by WiFi

webserver – How to create socket dynamically on lighttpd server?

We are hosting more than 200 websites/users on the lighttpd web server. When we keep all the socket connection open/active, the memory consumption is very high.
We want to create the socket, on demand when there is a request. How can we do it ?

I am trying to connect test user through this socket ( /etc/my-project/fastcgi/test.socket ), If this socket is killed or not existing, then we get 503 error.

Lighttpd user config file,

$HTTP("host") =~ "8484" {
$HTTP("cookie") =~ "test" {
fastcgi.server = (
".php" => (
"localhost" => (
"socket" => "/etc/my-project/fastcgi/test.socket",
"max-procs" => 2,
"bin-copy-environment" => (
"PATH", "SHELL", "USER"

This is example config file.

python: connect using socket to https

I am reading one book about networking(I just started) with python and there was such code:

import sys, socket
try:
    rfc_number = int(sys.argv(1))
except (IndexError, ValueError):
    print('Must supply an RFC number as first argument')
    sys.exit(2)
host = "www.ietf.org"
port = 80
socket = socket.create_connection((host, port))
req = (f"GET /rfc/rfc{rfc_number}.txt HTTP/1.1rn"
       f"Host: {host} : {port}rn"
       f"User-Agent: Python {sys.version_info(0)}rn"
       "Connection: closern"
       "rn"
       )
socket.sendall(req.encode("ascii"))
rfc_raw = bytearray()
while True:
    buf = socket.recv(4096)
    print(buf)
    if not len(buf):
        break
    rfc_raw += buf
rfc = rfc_raw.decode('utf-8')

print(rfc)

I understood everything here and tried to run but it did not work because as I found out that web-page is https not http. And now i am interested how can I connect to this web-page using this code(this code works for http perfectly I tried for http web page).As I know there is security in https and I guess because of this I can not connect.(I did not dive to much yet in networking).so there should be something added in this code for security check or something like that(I do not know)

There was code using urllib and that worked perfectly but I am interested in using socket code.is it possible with socket to do this and how?please explain little bit as well.Thanks beforehand.

java – Buffered reader end of stream and empty messages while reading from socket

I read message from socket and append to my queue for processing. I need to know the difference between when empty message is received or what does end of stream means in my case. Sometimes, I receive empty messages that makes socket dirty and as a result the connection is terminated after specific number of tries. Is below piece of code correct or is there anything I need to consider.

public class SocketEOF {

private int invalidMsgCount = 0;

private BufferedReader reader = null;


public void receiveMessages(Socket client) throws IOException {
    while (true) {
        try {

            String response = (String) readMessage(client);
            if (invalidMsgCount > 0) {
                invalidMsgCount = 0;
                System.out.println("Problem resolved in attempts: " + invalidMsgCount);
            }

            appendMsgAndNotifyToQueue(response);
        }
        catch (InvalidMessageException ex) {
            invalidMsgCount++;
            System.out.println("Invalid Message received at socket: " + client);
            if (invalidMsgCount >= 20) {
                System.err.println("Socket broken. Connection lost.");
                closeSocketGracefully();
            }
        }
    }
}


public Object readMessage(Socket client) throws IOException, InvalidMessageException {
    String msgStr = null;
    if (null == reader) {
        reader = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.ISO_8859_1));
    }

    char() charBuf = new char(5);
    int noOfchar = reader.read(charBuf);

    if (noOfchar > 0) {
        msgStr = new String(charBuf);
        msgStr = msgStr.substring(0, noOfchar);

        System.out.println("Message Received at " + client.toString() + ": " + msgStr);
    }
    else {
        throw new InvalidMessageException("Invalid message of -1 length received at " + client.toString());
    }

    return msgStr;
}

How to send a string format exploit through the socket

I am doing a CTF exercise here:

https://c-wars.acnr.se/download/level2.tgz

There is a coupler with the vulnerable service, which I need to find the value of a variable. I could do it through the following entry:

== Login Service 1.0 ==
Username: %7$s
Password: a
Welcome: ACNR{_SERVICE_FLAG_}

My problem now is that sending must call a function that will send this string over a socket, so I guess I need to escape it. I have tried %7$s, But it does not work.

The submission format can be found at https://c-wars.acnr.se/download/MANUAL.pdf

#include 
#include 
#include 
#include 
#include 
#include "gamelib.h"
uint32_t main(uint32_t argc, uint8_t ** argv)
{
svc_init();
svc_set(10000);
svc_writeln("gimme flag");
svc_readuntil('}');
return 0;
}

python: use a Unix domain socket created by sshtunnelforwarder in paramiko

I have a remote server that can be connected through a hop server. I am trying to connect to the server through ssh_tunnel forwarder and paramiko. Here is my code

tunnel=SSHTunnelForwarder((jump_host, jump_port),ssh_username=jump_user,remote_bind_address=(remote_server, remote_port),set_keepalive=10)
tunnel.start()
client = paramiko.SSHClient()
client.connect(HOST, username=USER, password='password')
stdin,stdout,stderr=client.exec_command('uptime',timeout=20)

This works smoothly. Now you want to change the local link address from SSHTunnelForwarder to a local unix socket. The code is

tunnel=SSHTunnelForwarder((jump_host, jump_port),local_bind_address='/tmp/foo.sock',ssh_username=jump_user,remote_bind_address=(remote_server, remote_port),set_keepalive=10)
tunnel.start()
client = paramiko.SSHClient()
client.connect(HOST, username=USER, password='password',sock='/tmp/foo.sock')
stdin,stdout,stderr=client.exec_command('uptime',timeout=20)

This does not work and throws the following error.

Traceback (most recent call last):
File "paramiko_socket.py", line 14, in 
client.connect('172.16.3.101', 
File "/home/mafiree/.pyenv/versions/3.8.0/lib/python3.8/site-packages/paramiko/client.py", 
line 370, in connect
t = self._transport = Transport(
File "/home/mafiree/.pyenv/versions/3.8.0/lib/python3.8/site- packages/paramiko/transport.py", line 400, in __init__
addrinfos = socket.getaddrinfo(
File "/home/mafiree/.pyenv/versions/3.8.0/lib/python3.8/socket.py", line 914, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: (Errno -2) Name or service not known

c ++ – Winsock socket library base

I have decided to make a socket library in C ++.
To be honest, I found it a bit strenuous with winsock2; I'd say it's a bit complex, compared to, say, Python socket lib.
My code, header file:

#pragma once
#pragma comment(lib,"WS2_32.lib")
#include 
#include 
#include 
#include 
#include 

enum flags{
    TCPType = 0,
    UDPType = 1
};

inline flags operator|(const flags& x, const flags& y){
    return static_cast(static_cast(x)|static_cast(y));
}

class Socket
{
private:
    std::string ip;
    std::string port;

    SOCKET* currentSocket = nullptr;

    bool isTcp;

public:
    Socket(flags f = TCPType);
    ~Socket();

    bool Connect(const std::string& address, const std::string& port);
    bool BindToPort(int p);
    bool Listen();
    bool isTcpType();

    int ReceiveAll(void* buffer, int size);
    int Receive(void* buffer, int size);
    int Sendall(void* buffer, int size);
    int Send(void* buffer, int size);

    std::string  getAddress() const;
    std::string  getPort() const;

    Socket* AcceptConnection();
    void close();

    static bool InitWinsock();
};

And the source file:
#include "pch.h"
#include "Socket.h"

Socket::Socket(flags f)
{
    isTcp = !f;

    auto connectionType = SOCK_DGRAM;
    auto b = 0;

    if (isTcp) {
        connectionType = SOCK_STREAM;
        b = IPPROTO_TCP;
    }

    SOCKET mainSocket = socket(AF_INET, connectionType, b);
    if (mainSocket == INVALID_SOCKET)
    {
        std::cerr << "Error creating socket: " << WSAGetLastError() << 'n';
        WSACleanup();
    }

    currentSocket = new SOCKET(mainSocket);
}

Socket::~Socket()
{
    if(currentSocket != nullptr)
        delete currentSocket;
}

bool Socket::Connect(const std::string& address, const std::string& port){
    addrinfo hints, *result = nullptr;

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    int iResult = getaddrinfo(address.c_str(), port.c_str(), &hints, &result);
    if (iResult != 0) {
        std::cerr << "getaddrinfo failed with error: " << iResult << 'n';
        WSACleanup();
        return false;
    }

    addrinfo *ptr = result;

    iResult = connect(*currentSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        closesocket(*currentSocket);
        *currentSocket = INVALID_SOCKET;
    }

    return 0;
}

bool Socket::BindToPort(int p){
    if (currentSocket == nullptr)
        return false;

    sockaddr_in service;
    memset(&service, 0, sizeof(service));
    service.sin_family = AF_INET;
    InetPton(AF_INET, (PCWSTR)("127.0.0.1"), &service.sin_addr.s_addr);
    service.sin_port = htons(p);

    if(bind(*currentSocket, (SOCKADDR *)& service, sizeof(sockaddr)) == SOCKET_ERROR)
    {
        std::cerr << "Error during binding socket: " << WSAGetLastError() << 'n';
        closesocket(*currentSocket);
        return false;
    }

    this->port = p;

    return true;
}

bool Socket::Listen() {
    if (currentSocket == nullptr)
        return false;

    if(listen(*currentSocket, 1) == SOCKET_ERROR)
        std::cerr << "Error during trying to listen on socket: " << WSAGetLastError() << 'n';

    ip = "127.0.0.1";

    return true;
}

bool Socket::isTcpType(){
    return isTcp;
}

int Socket::ReceiveAll(void* buffer, int size) {
    int bytesLeft = size, current = 0;

    while (bytesLeft > 0) {
        int bytesRecv = recv(*currentSocket, static_cast(buffer), size, 0);

        if (bytesRecv < 0)
            return -1;

        bytesLeft -= bytesRecv;
    }

    return size;
}


int Socket::Receive(void* buffer, int size){
    if (currentSocket == nullptr)
        return -1;

    int bytesRecv = SOCKET_ERROR;

    while(bytesRecv == SOCKET_ERROR)
    {
        bytesRecv = recv(*currentSocket, static_cast(buffer), size, 0);

        if(bytesRecv == WSAECONNRESET)
            break;

        if (bytesRecv < 0)
            return -1;
    }

    return bytesRecv;
}

int Socket::Sendall(void* buffer, int size) {
    if (currentSocket == nullptr)
        return -1;

    int bytesSent = 0, counter = 0;

    while (counter < size) {
        bytesSent = send(*currentSocket, static_cast(buffer), size, 0);
        counter += bytesSent;
    }

    return size;
}

int Socket::Send(void* buffer, int size){
    if (currentSocket == nullptr)
        return -1;

    int bytesSent, bytesRecv = SOCKET_ERROR;
    bytesSent = send(*currentSocket, static_cast(buffer), size, 0);

    return bytesSent;
}

std::string  Socket::getAddress() const{
    return ip;
}

std::string  Socket::getPort() const{
    return port;
}

Socket* Socket::AcceptConnection(){
    if (currentSocket == nullptr)
        return false;

    SOCKET acceptSocket = SOCKET_ERROR;

    while (acceptSocket == SOCKET_ERROR)
    {
        acceptSocket = accept(*currentSocket, NULL, NULL);
    }

    Socket* result = new Socket(*this);
    result->currentSocket = new SOCKET(acceptSocket);

    return result;
}

void Socket::close() {
    closesocket(*currentSocket);
    delete currentSocket;
    WSACleanup();
}

bool Socket::InitWinsock() {
    WSADATA wsaData;

    int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (result != NO_ERROR) {
        std::cerr << "Error during initializing WinSock: " << WSAGetLastError() << 'n';
        return false;
    }

    return true;
}