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

socket connect error return -1
刚刚学习linux,学习socket的时候第一个例子到client的connect函数就出现了错误。返回-1.

server:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define LISTENQ 5
#define MAXLINE 512

int main(){
int listenfd , connfd ;
struct sockaddr_in servaddr , cliaddr ;
socklen_t len ;
char buff[MAXLINE] ;
time_t ticks ;
listenfd = socket(AF_INET , SOCK_STREAM , 0) ;
if(listenfd < 0){
printf("Socket created failed.\n") ;
}
servaddr.sin_family = AF_INET ;
servaddr.sin_family = htons(6666) ;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY) ;
if(bind(listenfd , (struct sockaddr*)&servaddr , sizeof(servaddr)) < 0){
printf("bind failed.\n") ;
return -1 ;
}
printf("listening...\n") ;
listen(listenfd , LISTENQ) ;
while(1){
len = sizeof(cliaddr) ;
connfd = accept(listenfd , (struct sockaddr*)&cliaddr , &len) ;
printf("connect from %s , port %d\n" , inet_ntoa(cliaddr.sin_addr.s_addr) , 
ntohs(cliaddr.sin_port)) ;
ticks = time(NULL) ;
sprintf(buff , "%.24s \r\n" , ctime(&ticks)) ;
write(connfd , buff , strlen(buff)) ;
close(connfd) ;
}
}

client:
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define MAXBUFFSIZE 256
#define PORT 6666
#define HOST_ADDR "127.0.0.1"

int main(int argc , char *argv[]){
int sockfd , n ;
char recvbuff[MAXBUFFSIZE] ;
struct sockaddr_in servaddr ;
sockfd = socket(AF_INET , SOCK_STREAM , 0) ;
if(sockfd < 0){
printf("Socket create failed.\n") ;
return -1 ;
}

servaddr.sin_family = AF_INET ;
servaddr.sin_port = htons(6666) ;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY) ;
printf("connecting...\n") ;

int connect_ret = connect(sockfd , (struct sockaddr*)&servaddr , sizeof(servaddr)) ;

if(connect_ret < 0){
printf("Connect server failed connect_ret = %d.\n" , connect_ret) ;
return -1 ;
}

while((n == read(sockfd , recvbuff , MAXBUFFSIZE)) > 0){
recvbuff[n] = 0 ;
fputs(recvbuff , stdout) ;
}

if(n < 0){
printf("Read failed.\n") ;
return -2 ;
}

return 0 ;
}

------解决方案--------------------
servaddr.sin_family = AF_INET ;
servaddr.sin_port = htons(6666) ;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY) ;

客户端这里不能INADDR_ANY啊,填个127.0.0.1吧。
------解决方案--------------------
servaddr.sin_family = AF_INET ;
 servaddr.sin_family = htons(6666) ;
 
这里怎么对同一个成员赋值了两次?而且貌似第二个是要绑定到端口吧?
如果是端口的话,那也是 servaddr.sin_port = htons(6666)