日期:2014-05-16  浏览次数:20902 次

发送UDP,Socket operation on non-socket,初学,请指教
今天刚开始看TCP/IP详解:实现,第一个程序示例就出现了错误,望大家帮助!谢谢!
C/C++ code

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

#define BUFFSIZE 150

int main(void){
    struct sockaddr_in serv;
    char buff[BUFFSIZE];
    int sockfd, n;

    if((sockfd = socket(PF_INET, SOCK_DGRAM, 0) < 0))
        perror("socket error");

    bzero((char*)&serv, sizeof(serv));
    memset(buff, 0, BUFFSIZE);

    serv.sin_family = AF_INET;
    serv.sin_addr.s_addr = inet_addr("140.252.1.32");
    serv.sin_port = htons(13);

    if(n = sendto(sockfd, buff, BUFFSIZE, 0,
                (struct sockaddr *)&serv, sizeof(serv)) != BUFFSIZE)
        perror("sendto error");

    if((n = recvfrom(sockfd, buff, BUFFSIZE, 0,
                        (struct sockaddr *)NULL, (int*)NULL)) != BUFFSIZE)
        perror("recvfrom error");

    printf("%s\n", buff);

    exit(0);
}


运行后出现:
sendto error: Socket operation on non-socket
recvfrom error: Socket operation on non-socket

------解决方案--------------------
楼主这样修改试试:

if((sockfd = socket(PF_INET, SOCK_DGRAM, 0) < 0))
perror("socket error");

改为:
if(((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0))
perror("socket error");

=优先级小于<
因此sockfd实际上=0,因此出现 Socket operation on non-socket错误
消息根本就没发送
------解决方案--------------------
if((sockfd = socket(PF_INET, SOCK_DGRAM, 0) < 0))

'<'号的优先级比'='号的高,因此你的sockfd的值不是0,就是1
改成
if((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0)