Search code examples
csocketstelnet

C | socket not accepting connection via telnet


First of all, this is my code:

#include "database.h"
#include "pop3.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <fcntl.h>

#define PORT 1234

DBRecord fbPopHost = { "host", "pop3", "localhost" };
DBRecord fbPopPort = { "port", "pop3", "8110" };


int main(void) {
    int pop3socket;
    int clientSocket;
    int len;
    int binden;
    int zuhoeren;

    struct sockaddr_in mailserver;

    /* Socket erstellen */
    pop3socket = socket(AF_INET, SOCK_STREAM, 0);
    if(pop3socket < 0) {
        perror("Fehler beim Erstellen des Sockets!");
    }

    /* IP und Port festlegen mithilfe von Bind */
    memset(&mailserver, 0, sizeof(mailserver)); 
    mailserver.sin_family = AF_INET;
    mailserver.sin_addr.s_addr = htonl(INADDR_ANY);
    mailserver.sin_port = htons(1234);
    binden = (pop3socket, (struct sockaddr*)&mailserver, sizeof(mailserver));
    if(binden < 0) {
        perror("Fehler beim Binden des Sockets");
    }

    /* Warteschlange einrichten */
    zuhoeren = listen(pop3socket, 5);
    if(zuhoeren == -1) {
        perror("Fehler beim Listen");
    }

    /* Verbindung(en) akzeptieren */
    struct sockaddr_in pop3client; /* Client Infos */

    for(;;) {
        len = sizeof(struct sockaddr);
        clientSocket = accept(pop3socket, (struct sockaddr*)&pop3client, &len);
        if(clientSocket < 0) {
            perror("Fehler beim Accepten der Verbindung");
        }
        process_pop3(clientSocket);
    }


}

When I try to open up a connection via telnet:

telnet localhost 1234

it sadly says:

Trying 127.0.0.1... telnet: Unable to connect to remote host: Connection refused

When I am starting the program it listens to connections, so I don't know what is wrong. Can somebody help me please, it is getting frustrating?

Thanks for the help!


Solution

  • You should actually call bind() in this line:

    binden = (pop3socket, (struct sockaddr*)&mailserver, sizeof(mailserver));
    

    :-)