2017-10-24 3 views
-2

Ich erhalte diesen Fehler, wenn ich versuche, eine Anwendung zum Verbinden und Abhören eines Ports für Daten zu machen.Socket-Betrieb an nicht-Socket C

#include <sys/socket.h> 
#include <sys/types.h> 
#include <arpa/inet.h> 
#include <netdb.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <errno.h> 
#include <unistd.h> 
#include <fcntl.h> 

int main(int argc, char * arg[]){ 
int conn_s = socket(AF_INET, SOCK_STREAM, 0);  //Create the socket 

struct sockaddr_in servaddr; 

memset(&servaddr, 0, sizeof(servaddr)); 
servaddr.sin_family = AF_INET; 
servaddr.sin_port = htons(1234); 
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); 
int res = bind(conn_s, (struct sockaddr *) &servaddr, sizeof(servaddr)); 

if(res < 0){ 
    printf("Error has occured\n"); 
} 

FILE * stream = fdopen(conn_s, "w+");    //Create a stream for the socket 
FILE * file = fopen("response2.txt", "w+");   //Create a file to store the output of the stream 

char * line = NULL; //Where each line of the stream will be stored in 
size_t len = 0;  // The length of the line 
ssize_t bytes;   //The size of the line in bytes 

int lis = listen(conn_s, SOMAXCONN); 
fcntl(lis, F_SETFL, O_NONBLOCK); 

while(1) { 
    conn_s = accept(lis, NULL, NULL); 
    if(conn_s < 0){ 
     if((errno == EAGAIN) || (errno == EWOULDBLOCK)) 
      continue; 
     perror("Failed to accept connection"); 
     exit(EXIT_FAILURE); 
    } 

    long conn_s_flags = fcntl(conn_s, F_GETFL); 
    fcntl(conn_s, F_SETFL, conn_s_flags & ~O_NONBLOCK); 

    while((bytes = getline(&line, &len, stream)) != -1) { 
     printf("%s\n", line); 
     fwrite(line, sizeof(char), bytes, file);    
    } 

    close(conn_s); 
} 
free(line); 

return 0; 
} 

Ich versuche, Port 1234, hören sie zu verbinden und zu akzeptieren, es Daten zu empfangen, aber der Fehler hält auftritt.

Auch ich versuche, mit netcat zu testen, aber einen anderen Fehler erhalten, wenn nc auf dem Port ausgeführt wird, den ich angegeben habe.

Dank

+0

_aber der Fehler bleibt dabei_: Sie müssen mich spezifisch bohren. –

+0

Außer für die fcntl, machen Sie nichts mit dem 'conn_s' (bevor Sie es schließen) – joop

+0

Welchen Fehler sprechen Sie? – Devolus

Antwort

1
int lis = listen(conn_s, SOMAXCONN); 
fcntl(lis, F_SETFL, O_NONBLOCK); 
while(1) { 
    conn_s = accept(lis, NULL, NULL); 

listen() keine Buchse FD zurück. Es gibt null oder -1 zurück. Die zweite Zeile ist daher fehlerhaft, ebenso wie der folgende accept() Aufruf. Es sollte sein:

if (listen(conn_s, SOMAXCONN) == -1) 
{ 
    perror("listen"); 
    return; // or whatever 
} 
fcntl(conn_s, F_SETFL, O_NONBLOCK); 
while(1) { 
    int conn_c = accept(conn_s, NULL, NULL); 

NB nicht conn_s verlieren Sie durch das Ergebnis der accept() hinein zu speichern.