创建 C 服务器

Creating a C server

我正在创建一个 C 服务器。它除了显示一条消息,说明目前已正确建立连接外什么都不做:

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stddef.h>
#include <unistd.h>

#include "utils.h"

int main(int argc, char* argv[]){
    int fd, fd_conn, result;
    struct sockaddr_in sock;

    fd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(fd == -1, "socket");

    sock.sin_family = AF_INET;
    sock.sin_addr.s_addr = INADDR_ANY;
    sock.sin_port = htons(7000);
    bzero(&(sock.sin_zero),8); // 0 en el resto de la estructura

    result = bind(fd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in));
    exit_if(result == -1, "bind");

    result = listen(fd, 5);
    exit_if(result == -1, "listen");

    fd_conn = accept(fd, NULL, NULL);
    exit_if(fd_conn == -1, "accept");

    printf("Connection established\n");

    close(fd_conn);
    close(fd);
}

显然,在执行时,它会等待传入连接,但在使用 telnet 进行测试时:

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

我修正了你的(微不足道的)错误:


#include <stdio.h> // for fprintf
#include <string.h> // for memset
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stddef.h>
#include <unistd.h>

// #include "utils.h"
#define exit_if(a,b) if(a) {fprintf(stderr, b);}  else

int main(int argc, char* argv[]){
    int fd, fd_conn, result;
    struct sockaddr_in sock;

    fd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(fd == -1, "socket");

    memset(&sock,0, sizeof sock); // <-- zero the complete struct.

    sock.sin_family = AF_INET;
    sock.sin_addr.s_addr = INADDR_ANY;
    sock.sin_port = htons(7000);
    memset(&sock.sin_zero,0, sizeof sock.sin_zero); // <<-- not needed anymore

    result = bind(fd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in));
    exit_if(result == -1, "bind");

    result = listen(fd, 5);
    exit_if(result == -1, "listen");

    fd_conn = accept(fd, NULL, NULL);
    exit_if(fd_conn == -1, "accept");

    printf("Connection established\n");

    close(fd_conn);
    close(fd);

    return 0;
}