#include
#include
#include
#include
#include
#include
#define SERVPORT 3333
#define BACKLOG 10
typedef struct sockaddr_in st;
typedef struct sockaddr sd;
int main()
{
int sockfd,clientfd;
st my_adder;
st client_adder;
int sin_size;
if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
{perror("socket default!");
exit(1);
}
printf("%d",sockfd);
my_adder.sin_family = AF_INET;
my_adder.sin_port = htons(SERVPORT);
my_adder.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_adder.sin_zero),8);
if(bind(sockfd,(sd *) &my_adder,sizeof(sd)) == -1)
{perror("bind error!");
exit(1);
}
if(listen(sockfd,BACKLOG) == -1){
perror("linsten error");
exit(1);
}
while(1){
sin_size = sizeof(st);
if((clientfd = accept(sockfd,(sd *)&client_adder,&sin_size)) == -1){
perror("accept error!");
continue;
}
printf("accept a meg from:%s\n",inet_ntoa(client_adder.sin_addr));
if(!fork()){
if(send(clientfd,"connect\n",26,0) == -1)
perror("send error!");
close(clientfd);
exit(0);
}
close(clientfd);
}
}
//客户端程序
#include
#include
#include
#include
#include
#include
#include
typedef struct sockaddr_in st;
typedef struct sockaddr sd;
#define SERVPORT 3333
#define MAXDATASIZE 100
int main(int argc,char *argv[])
{
int sockfd,recvbytes;
char buf[MAXDATASIZE];
struct hostent *host;
st servaddr;
if(argc<2){
fprintf(stdin,"please enter the sercer's hostname!\n");
exit(1);
}
if((host = gethostbyname(argv[1])) == NULL){
perror("gethostbyname error!");
exit(1);
}
if (sockfd = socket(AF_INET,SOCK_STREAM,0) == -1){
perror("socket creat error!");
exit(1);
}
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERVPORT);
servaddr.sin_addr = *((struct in_addr *)host->h_addr);
//inet_pton( AF_INET, "127.0.0.3", &servaddr.sin_addr );
bzero(&(servaddr.sin_zero),8);
if (connect(sockfd,(sd *)&servaddr,sizeof(sd)) == -1){
perror("connect error!");
exit(1);
}
if((recvbytes = recv(sockfd,buf,MAXDATASIZE,0)) == -1){
perror("receve error!");
exit(1);
}
buf[recvbytes] = '\0';
printf("receve:%s",buf);
close(sockfd);
}
sydnash 于 2008-11-10 16:51:09发表:
当我在以个终端运行服务器端程序后,打开另外以个终端运行时出现如下错误
connect error!: Socket operation on non-socket
请大家帮帮忙解决下啊
[ 本帖最后由 sydnash 于 2008-11-10 16:54 编辑 ]