最近,我一直在尝试使用C套接字做很多事情,因为这是我将来需要使用的语言。但是,我遇到了无法解决的问题。我同时创建了客户端和服务器-不幸的是,这两个二进制文件拒绝相互连接。我的意思是,当我在同一台计算机上运行服务器二进制文件和客户端二进制文件时,我都不会出现任何错误,但是也没有连接。有任何想法吗?这是代码!
(Ubuntu,使用gcc编译的C代码,服务器代码和客户端代码都在同一台计算机上的2个不同终端中运行。)
Server.c:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h> //inet_aton(), inet_ntoa() etc
#include <sys/types.h>
#include <netinet/in.h>
#define PORT 8000
#define ERROR perror("Something went wrong! => ");
#define BUFFERSIZE 256
int main()
{
int sockfd, client_socketfd;
int bytes_sent;
socklen_t sin_size;
struct sockaddr_in server_addr;
struct sockaddr_in connectedClient_addr;
char message[BUFFERSIZE] = "Welcome to the server!";
if((sockfd = socket(PF_INET, SOCK_STREAM ,0)) == -1) {
ERROR;
exit(-1);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY; //Subject to change
if((bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr))) == -1) {
ERROR;
exit(-2);
}
if((listen(sockfd, 5)) == -1) {
ERROR;
exit(-3);
}
int addrlen = sizeof(connectedClient_addr);
if((client_socketfd = accept(sockfd, (struct sockaddr *)&connectedClient_addr, (socklen_t*)&addrlen)) == -1){
ERROR;
exit(-4);
}
printf("Got a connection from: %s at port: %d" , inet_ntoa(connectedClient_addr.sin_addr), PORT);
if((send(sockfd, &message, BUFFERSIZE, 0)) == -1) {
ERROR;
exit(-5);
}
close(sockfd);
close(client_socketfd);
return 0;
}
-
Client.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8000
#define ERROR perror("Something went wrong! =>");
#define BUFFERSIZE 256
int main()
{
int sockfd;
struct sockaddr_in client_addr;
char message[BUFFERSIZE] = "Successfully connected!";
int bytes_received, bytes_sent;
char buffer[BUFFERSIZE];
if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
ERROR;
exit(-1);
}
client_addr.sin_family = AF_INET;
client_addr.sin_port = htons(PORT);
client_addr.sin_addr.s_addr = INADDR_ANY;
if((connect(sockfd, (struct sockaddr*)&client_addr, sizeof(client_addr))) == -1) {
ERROR;
exit(-2);
}
if((bytes_received = recv(sockfd, &buffer, BUFFERSIZE, 0)) == -1) {
ERROR;
exit(-3);
}
printf("Received %d bytes:\n" , bytes_received);
printf("%s", buffer);
close(sockfd);
return 0;
}
最佳答案
回答:
问题是我在server.c的send()
函数内部提供了服务器套接字,而不是客户端套接字。因此,代码可以正常工作,没有任何错误,但是行为不正确。归功于RemyLebeau in the comments,他指出了这一点,并为我节省了无数小时的苦苦挣扎。
关于c - C套接字(Linux)无法连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45358069/