Domanda Problema socket

  • Autore discussione Utente cancellato 274325
  • Data d'inizio
U

Utente cancellato 274325

Linguaggio C:
Ciao a tutti ho un problema coi socket quando provo a passarmi una stringa tra un server e client, mediante i socket, usando send e recv, la stringa che arriva è codice binario o hex, sapete come risolvere?
 
Server:
C:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#define SIZE 1024
#define PORT 4444

int main(int argc, char *argv[]) {
    char buffer[SIZE];
    char buf[SIZE];
    int s=socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server;
    server.sin_addr.s_addr=htonl(INADDR_ANY);
    server.sin_port=htons(PORT);
    server.sin_family=AF_INET;
    int sbind=bind(s, (struct sockaddr*)&server, sizeof(server));
    int slist=listen(s, 3);
    while (1) {
        int sa=accept(s, (struct sockaddr*)NULL, NULL);
        printf("client> ");
        fgets(buffer, SIZE, stdin);
        buffer[strlen(buffer)-1]='\0';
        send(s, buffer, sizeof(buffer), 0);

    }


    return 0;
}
Client:
C:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#define SIZE 1024
#define PORT 4444

int main(int argc, char *argv[]) {
    char buffer[SIZE];
    int s=socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in client;
    client.sin_family=AF_INET;
    client.sin_port=htons(PORT);
    client.sin_addr.s_addr=inet_addr("127.0.0.1");
    while (1) {
        int ccsock=connect(s, (struct sockaddr*)&client, sizeof(client));
        recv(s, buffer, sizeof(buffer), 0);
        printf("%s\n",buffer);
    }

    return 0;
}
 
Server:
C:
send(sa, buffer, strlen(buffer), 0); // strlen o al massimo SIZE, non sizeof e soprattutto sa (il file descriptor del client) e non s (il file descriptor del server).

Client:
C:
memset(buffer, '\0', sizeof(buffer)); // '\0' oppure 0, ma non '0'
//...
recv(s, buffer, SIZE, 0); // SIZE, non sizeof

Il codice non è il massimo, ma penso che il tuo obiettivo fosse quello di sbloccarti e iniziare a vedere qualcosa.
Fatto questo dovrebbe iniziare a funzionarti. Se dovessi avere altri problemi, fa sapere.
 
  • Mi piace
Reazioni: DanyDollaro