c - 套接字错误:连接被拒绝

时间:2017-11-06 21:11:59

标签: c linux sockets ubuntu unix

我正在尝试用C编写程序,当我尝试通过端口9000或任何其他端口进行连接时出现此错误。 当我写这篇文章时,它让我拒绝连接:

  

./ client hostname-ubuntu 9000

     

./ client 127.0.0.1 9000

     

./ client localhost 9000

- > Server.c代码:

我做错了什么?哪里出错了?请帮帮我。

#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
int main(int arg,char*argv[]){
int sd,sd_c,port,r;
struct sockaddr_in my_addr, cli_addr;
socklen_t cli_addr_size;
char buf[100];
if (arg!=2){
        fprintf(stderr, "Use:server-port\n");
        return 1;
    }
memset(&my_addr,0,sizeof(my_addr));
my_addr.sin_family=AF_UNIX;
if(1!=sscanf(argv[1],"%d",&port)){
    fprintf(stderr,"Port number must be a number\n");
    return 1;
    }
my_addr.sin_port=htons(port);
my_addr.sin_addr.s_addr=htonl(INADDR_ANY);

sd=socket(PF_UNIX,SOCK_STREAM,0);
if(-1==bind(sd,(struct sockaddr*)&my_addr,sizeof(my_addr))){
    perror("bind()");
        return 1;
    }
listen(sd,1);
cli_addr_size=sizeof(cli_addr);
sd_c=accept(sd,(struct sockaddr*)&cli_addr,&cli_addr_size);
printf("Client connected from %s:%d\n",inet_ntoa(cli_addr.sin_addr),ntohs(cli_addr.sin_port));
close(sd);
while((r=recv(sd_c,buf,100,0))>0){
    write(1,buf,r);
    }
    if(r==-1){
     perror("recv()");
    return 1;
    }
send(sd_c,"xyz",3,0);
close(sd_c);
return 0;
}

- &gt; Client.c代码

#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
int main(int arg,char*argv[]){
int sd,r,port;
struct hostent *hh;
struct sockaddr_in adr;
char buf[100];
if (arg!=3){
        fprintf(stderr, "Use : client-address-port\n");
        return 1;
    }
memset(&adr,0,sizeof(adr));
adr.sin_family=AF_INET;
if(1!=sscanf(argv[2],"%d",&port)){
    fprintf(stderr,"Port number is not a number\n");
    return 1;
    }
adr.sin_port=htons(port);
hh=gethostbyname(argv[1]);
if(hh==0||hh->h_addrtype!=AF_INET||hh->h_length<=0){
    fprintf(stderr,"Can't find out server address\n");
    return 1;
    }
memcpy(&adr.sin_addr,hh->h_addr_list[0],4);
sd=socket(PF_INET,SOCK_STREAM,0);

if(-1==connect(sd,(struct sockaddr*)&adr,sizeof(adr))){
    perror("connect()");
        return 1;
    }
send(sd,"abcd",4,0);
shutdown(sd,SHUT_WR);
while((r=recv(sd,buf,100,0))>0){
    write(1,buf,r);
    }
    if(r==-1){
     perror("recv()");
    return 1;
    }
close(sd);
return 0;
}

1 个答案:

答案 0 :(得分:0)

您在程序中使用了两种不同的协议。客户端程序中的AF_INET和服务器端的AF_UNIX。那永远不会奏效。修改这些代码行。

my_addr.sin_family=AF_UNIX;

my_addr.sin_family=AF_INET;

在客户端使用AF_INET;

sd=socket(PF_UNIX,SOCK_STREAM,0);

sd=socket(PF_INET,SOCK_STREAM,0);

希望有帮助...