遇到的问题
客户端连接Connection refused
解决方案
1.先在本地测试ser和client,保证程序可以正常连接
2.查看服务器的防火墙是否关闭
命令
firewall-cmd --state
systemctl stop firewalld.service //关闭防火墙
3.查看对应的服务器程序是否在监听
netstat -an|grep 端口号
4.服务器需要放开对应的端口
5.服务器绑定内网IP,客户端绑定公网IP
ifconfig //查看服务器的内网IP地址
6.ping 公网IP测试
注意事项
服务器要设置为内网IP,客户端要设置为公网IP
服务端代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <arpa/inet.h>
int main(int argc, char *argv[]) {
int socket_desc, client_sock, c;
struct sockaddr_in server, client;
char client_message[2000];
// 创建socket
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if (socket_desc == -1) {
printf("Could not create socket");
}
// 设置服务器地址和端口
server.sin_family = AF_INET;
//这里要设置为服务器内网的IP地址
server.sin_addr.s_addr = inet_addr("8.8.8.8");
server.sin_port = htons(9999);
int on = 1;
setsockopt(socket_desc,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
// 绑定socket到指定地址和端口
if (bind(socket_desc, (struct sockaddr *)&server, sizeof(server)) < 0) {
perror("bind failed. Error");
return 1;
}
// 监听连接
listen(socket_desc, 3);
printf("Waiting for incoming connections...\n");
c = sizeof(struct sockaddr_in);
// 接受连接
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t *)&c);
if (client_sock < 0) {
perror("accept failed");
return 1;
}
printf("Connection accepted\n");
// 接收客户端消息
if (recv(client_sock, client_message, 2000, 0) < 0) {
printf("recv failed");
}
printf("Client message: %s\n", client_message);
// 发送响应给客户端
char *server_message = "Hello from server";
if (send(client_sock, server_message, strlen(server_message), 0) < 0) {
printf("Send failed");
return 1;
}
// 关闭连接
close(client_sock);
close(socket_desc);
return 0;
}
客户端代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int sock;
struct sockaddr_in server;
char message[1000], server_reply[2000];
// 创建socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
printf("Could not create socket");
}
// 设置服务器地址和端口
//注意这里需要设置服务器的公网IP地址
server.sin_addr.s_addr = inet_addr("8.8.8.8");
server.sin_family = AF_INET;
server.sin_port = htons(9999);
// 连接服务器
if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
perror("connect failed. Error");
return 1;
}
printf("Connected\n");
// 发送数据
strcpy(message, "Hello from client");
if (send(sock, message, strlen(message), 0) < 0) {
printf("Send failed");
return 1;
}
// 接收服务器响应
if (recv(sock, server_reply, 2000, 0) < 0) {
printf("recv failed");
return 1;
}
printf("Server reply: %s\n", server_reply);
// 关闭socket
close(sock);
return 0;
}
运行结果:
参考链接:
【网络】连接服务器失败(错误原因:Connection refused)| error 111: (111) Connection refused 原因分析-CSDN博客