非套接字上的套接字操作:设置套接字选项和绑定套接字时出错

时间:2017-04-18 06:54:31

标签: c sockets

运行时,程序发出

非套接字上的套接字操作:绑定套接字时出错。

之后我使用setsockopt() 它再次给我错误:

socket operation on non socket, error while setting options to socket.

我目前正在使用Ubuntu 16.04。是否存在问题 操作系统还是我的代码? (因为我看到了我正在使用的端口 这里没有任何其他程序使用,我尝试过更改 端口号为10000,范围为56000)

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

#define PORT 7890

int main()
{
    int sock_fd, new_sockfd;
    struct sockaddr_in host_addr, client_addr;              
    socklen_t sin_size;
    int recv_length, yes = 1;
    char buffer[1024];                                      


    if(sock_fd = socket(AF_INET, SOCK_STREAM, 0) == -1)     
    {
        perror("in creating socket \n");
        exit(-1);
    }   
    else
        printf("Socket: SUCCESS \n");

    if(setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(int)) == -1)
        perror("while setting socket option SO_REUSEADDR \n");
    else
        printf("Socket Option: SUCCESS \n");



    host_addr.sin_family = AF_INET;             
    host_addr.sin_port = htons(PORT);           
    host_addr.sin_addr.s_addr = 0;               
    memset(&(host_addr.sin_zero), '\0', 8);     




    if(bind(sock_fd, (struct sockaddr *)&host_addr, sizeof(struct sockaddr)) == -1)
        perror("while binding \n");
    else
        printf("Binding: SUCCESS \n");  


    if(listen(sock_fd, 5) == -1)
        perror("while listening \n");
    else
        printf("Listen: SUCCESS \n");   


    while(1)
    {

        sin_size = sizeof(struct sockaddr_in);

        new_sockfd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size);

            if(new_sockfd == -1)
            {
                perror("failed to accept \n");
                exit(-1);   
            }   
            else
                printf("accept: SUCCESS \n");
            printf("Server got connction from IP ADDRESS: %s, PORT NUMBER:%d \n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
    send(new_sockfd, "HELLO BASTARDS !\n", 16, 0);

        recv_length = recv(new_sockfd, &buffer, 1024, 0);

            while(recv_length > 0)
            {
                printf("Recieved %d Bytes \n", recv_length );



                recv_length = recv(new_sockfd, &buffer, 1024, 0);                       
            }

        close(new_sockfd);  
    }




return 0;
}

1 个答案:

答案 0 :(得分:0)

通常的运算符优先级问题:

if(sock_fd = socket(AF_INET, SOCK_STREAM, 0) == -1)     

应该是

if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)