artester 发表于 2016-07-31 21:48

SOS!为什么运行时报错“connect error():Connection refused”

本人刚学网络编程,为了增加自信心,跟着书本抄了一个简单程序,结果报错“connect() error:connection refused​”。哪位神仙大侠帮忙看看问题出在哪,不胜感激兼涕零,谢谢谢谢!!!

附注:环境是虚拟机Linux,防火墙已关

以下为完整的程序(出问题代码段已用***********标识出来。)​

#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>


#define HOSTNAMELEN 40
#define BUFLEN 1024
#define PORT 13


int main(int argc, char *argv[])
{
int rc;
int sockfd;
char buf;
char* pc;
struct sockaddr_in sa;
struct hostent* hen;


if(argc<2){
fprintf(stderr,"Missing host name\n");
exit(1);
}


hen = gethostbyname(argv);
if(!hen){
perror("Couldn't resolve host name");
}


memset(&sa,0,sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(PORT);
memcpy(&sa.sin_addr.s_addr,hen->h_addr_list,hen->h_length);


sockfd = socket(AF_INET,SOCK_STREAM,0);
if(sockfd < 0){
perror("socket() failed");
}

**********************************************************************

**********************************************************************
rc = connect(sockfd,(struct sockaddr *)&sa,sizeof(sa));
if(rc){
perror("connect() error");
}
***********************************************************************

***********************************************************************

pc = buf;
while(rc = read(sockfd,pc,BUFLEN - (pc - buf))){
pc += rc;
}


close(sockfd);
*pc = '\0';
printf("Time: %s",buf);
return 0;
}

LeonaLuHuFei 发表于 2016-08-08 10:31

connect 这个函数需要用root权限来运行,所以你的这个程序要root权限来执行。希望能帮到你。

魔鬼的惊叹 发表于 2016-08-10 09:12

Connection refused 表示没有端口在监听。
小于1024的port一般是让系统用的,平时写程序port最好大于1024
页: [1]
查看完整版本: SOS!为什么运行时报错“connect error():Connection refused”