新手求解Linux Fedora socket连接是提示Connection refused??
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define MAXLINE 4096
main(int argc, char** argv)
{
int sockfd,n;
char recvline[MAXLINE + 1];
struct sockaddr_in servaddr;
if(argv < 2){
fprintf(stderr,"Please enter the server's hostname!\n");
exit(1);
}
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
perror("socket创建出错!");
exit(1);
}
bzero(&servaddr,8);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(6666);
servaddr.sin_addr.s_addr=INADDR_ANY;
if(inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0){
perror("Inet_pton错误!");
exit(1);
}
if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(struct sockaddr)) == -1)
{
perror("connect出错!");
exit(1);
}
while((n = read(sockfd, recvline, MAXLINE)) > 0){
recvline[n] = 0;
if(fputs(recvline, stdout) == EOF)
{
perror("fputs出错!");
exit(1);
}
}
if(n < 0)
{
perror("read出错!");
exit(1);
}
}
新手求解,为什么连接任何IP地址都提示Connection refused,防火墙也关闭了,端口也换了。。。。
------解决方案--------------------bzero不对啊,还有其他两处小错,一起改了!
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define MAXLINE 4096
main(int argc, char** argv)
{
int sockfd,n;
char recvline[MAXLINE + 1];
struct sockaddr_in servaddr;
if(argc < 2){ /* argv ===> argc */
fprintf(stderr,"Please enter the server's hostname!\n");
exit(1);
}
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
perror("socket创建出错!");
exit(1);
}
bzero(&servaddr,sizeof(servaddr)); /* 8 ===> sizeof(servaddr) */
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(6666);
/* servaddr.sin_addr.s_addr=INADDR_ANY; ===> deleted */
if(inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0){
perror("Inet_pton错误!");