最近我一直在努力用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;
}
答案 0 :(得分:0)
<强>解答:强>
问题是我在 server.c 中的send()
函数内部而不是客户端套接字中提供了服务器套接字。因此代码工作没有任何错误,但行为是不正确的。归功于RemyLebeau in the comments,他指出了这一点并为我节省了无数个小时的挣扎。