C TCP / IP服务器绑定错误 - 非套接字上的套接字操作

时间:2015-04-04 22:34:43

标签: c sockets server bind tcp-ip

当我运行以下程序时,我的程序启动到绑定功能,并且失败了我的错误“非套接字上的套接字操作”。我不确定发生了什么。我用“gcc a3server.c -g -o server”编译,没有编译错误。

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Error. Please enter the right amount of arguments (2)");
        exit(1);
    }

    int sock, port, clientlen, connection, readfd, writefd;
    char buffer[255];
    struct sockaddr_in server, clientaddr;

    if (sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) < 0)
    {
        printf("Socket was not made.");
        exit(1);
    }

    //bzero((char *) &server, sizeof(server));
    port = atoi(argv[1]);

    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(port);

    int bindfd = bind(sock, (struct sockaddr *) &server, sizeof(server));

    if (bindfd < 0)
    {
        perror("Could not bind socket to address: ");
        exit(1);
    }

    listen(sock, 5);

    clientlen = sizeof(clientaddr);

    if (connection = accept(sock, (struct sockaddr *) &clientaddr, &clientlen) < 0)
    {
        printf("Could not accept connection");
        exit(1);
    }       

    if (readfd = read(connection, buffer, 255) < 0)
    {
        printf("Could not read from socket");
        exit(1);
    }

    printf("!---THIS IS A TEST---! \n BUFFER: %s", buffer);

    if (writefd = write(connection, buffer, 255) < 0)
    {
        printf("Could not write to socket");
        exit(1);
    }

    return 0;
}   

1 个答案:

答案 0 :(得分:1)

if (sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) < 0)

应该是

if ( (sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))  < 0)