socket 编程 :总是protocal mismatch
大家好,我在学习socket网络编程 ,在网上找到一个程序,一个clint 程序 ,一个server程序
我是这样运行的:
gcc -o client client.c
gcc -o server server .c
./server 22
ctrl +c
telnet localhost 22
然后出现几行字说链接成功接着我输什么都是
protocal mismatch
有谁知道为什么么么?
如下:
client 程序 :
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#define BUFFER_SIZE 1024
int handing(int sock){
char buffer[BUFFER_SIZE];
int bytes;
bytes=recv(sock,buffer,sizeof(buffer)-1,0);
if(bytes==-1) return -1;
buffer[bytes]='\0';
printf("%s",buffer);
return 0;
}
int main(int argc,char *argv[]){
int s;
struct sockaddr_in srv;
if(argc!=3){
printf("usage !");
return 1;
}
s=socket(AF_INET,SOCK_STREAM,0);
srv.sin_addr.s_addr=inet_addr(argv[1]);
srv.sin_port=htons((unsigned short int) atoi(argv[2]));
srv.sin_family=AF_INET;
if(connect(s,&srv,sizeof(srv))==-1){
perror("connect");
return 3;
}
if(handing(s)==-1){
fprintf(stderr,"%s: error in handing()\n",argv[0]);
return 4;
}
close(s);
return 0;
}
server程序 :
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<unistd.h>
#define BUFFER_SIZE 1024
int handing(int c){
char buffer[BUFFER_SIZE],name[BUFFER_SIZE];
int bytes;
strcpy(buffer,"My name is: ");
bytes=send(c,buffer,strlen(buffer),0);
bytes=recv(c,name,strlen(name)-1,0);
name[bytes]='\0';
sprintf(buffer,"hallo %s,nice to meet you !\r\n",name);
bytes=send(c,buffer,strlen(buffer),0);
return 0;
}
int main(int argc,char *argv[]){
int s,c,cli_size;
struct sockaddr_in srv,cli;
if(argc!=2){
printf("usage\n");
return 1;
}
s=socket(AF_INET,SOCK_STREAM,0);
srv.sin_addr.s_addr=INADDR_ANY;
srv.sin_port=htons((unsigned short int)atoi(argv[1]));
srv.sin_family=AF_INET;
bind(s,&srv,sizeof(srv));
listen(s,3);
for(;;){
cli_size=sizeof(cli);
c=accept(s,&cli,&cli_size);
printf("client from %s",inet_ntoa(cli.sin_addr));
handing(c);
close(c);
}
return 0;
}