socket bind error:Socket operation on non-socket
问题:编译Socket时候出现socket bind error:Socket operation on non-socket
时间:2014-7-14
解决:注意“==”和“=”的优先级,前者是大于后者的,故而在处理一些表达式的时候,注意加括号
注意:注意下面标注闪光字体的地方
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define portnumber 3332
int main(int argc,char *argv[])
{
int sockfd,new_fd;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int sin_size;
int nbytes;
char buffer[1024];
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
fprintf(stderr,"socket error:%s\n\a",strerror(errno));
exit(1);
}
bzero(&server_addr,sizeof(struct sockaddr_in));
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
server_addr.sin_port=htons(portnumber);
if(bind(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))!= 0 )
{
fprintf(stderr,"socket bind error:%s\n\a",strerror(errno));
exit(1);
}
if((listen(sockfd,5))!= 0 )
{
fprintf(stderr,"socket lisen error:%s\n\a",strerror(errno));
exit(1);
}
while(1)
{
sin_size=sizeof(struct sockaddr_in);
if((new_fd= accept(sockfd,(struct sockaddr *)(&client_addr),&sin_size))==-1)
{
fprintf(stderr,"socket accept error:%s\n\a",strerror(errno));
exit(1);
}
buffer[nbytes]='\0';
printf("Server recevied %s\n",buffer);
close(new_fd);
}
}
char buffer[1024];
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)// 极为容易出错,函数()跟一个值比较,尤其是类似于 变量1=函数(),这样的形式,=号的优先级为14,要远远低于==,<,>,
{
fprintf(stderr,"socket error:%s\n\a",strerror(errno));
exit(1);
}
bzero(&server_addr,sizeof(struct sockaddr_in));
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
server_addr.sin_port=htons(portnumber);
if(bind(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))!= 0 )
{
fprintf(stderr,"socket bind error:%s\n\a",strerror(errno));
exit(1);
}
if((listen(sockfd,5))!= 0 )
{
fprintf(stderr,"socket lisen error:%s\n\a",strerror(errno));
exit(1);
}
while(1)
{
sin_size=sizeof(struct sockaddr_in);
if((new_fd= accept(sockfd,(struct sockaddr *)(&client_addr),&sin_size))==-1)
{
fprintf(stderr,"socket accept error:%s\n\a",strerror(errno));
exit(1);
}
buffer[nbytes]='\0';
printf("Server recevied %s\n",buffer);
close(new_fd);
}
}
// 网上这种错误很多,大致分为三类,1,类似于我红色标注的那样,sockfd赋值错误,这种低级错误,2,端口号乱设,portnumber 一定要大于1024, 3. 初始化 server_addr 出错,