我尝试基于UNIX网络套接字创建简单的客户端\服务器程序。
有服务器代码
/* Headers */
#include "common/service.h"
#include "net/protocol.h"
int main(int argc, char** argv) {
/* Setting up socket */
int sock = socket(AF_INET, SOCK_STREAM, 0);
$( sock < 0, "socket", NULL );
struct sockaddr_in srv_address, cli_address;
memset((char *) &srv_address, 0, sizeof(srv_address));
srv_address.sin_family = AF_INET;
srv_address.sin_addr.s_addr = INADDR_ANY;
srv_address.sin_port = htons(RKP_RL_DEFAULT_PORT);
$(
bind(sock, (struct sockaddr*) &srv_address, sizeof(srv_address)) < 0,
"bind", NULL
);
/* Listening */
listen(sock, 1);
/* Accepting */
int ca_len = sizeof(cli_address);
int cli_sock = accept( sock, (struct sockaddr*) &cli_address, &ca_len );
$( cli_sock < 0, "accept", NULL );
/* Processing */
char accept_buffer[RKP_BUFFER_SZ] = {0};
read( cli_sock, accept_buffer, RKP_BUFFER_SZ-1 );
printf( "Incoming message: %s", accept_buffer );
write( cli_sock, "OK", 3 );
close(cli_sock);
close(sock);
return 0;
}
客户端代码
/* Headers */
#include "common/service.h"
#include "net/protocol.h"
int main(int argc, char** argv) {
$( argc != 2, argv[0], "Wrong syntax" );
// argv[1] contains server address
int port = RKP_RL_DEFAULT_PORT;
int sock = socket( AF_INET, SOCK_STREAM, 0 );
$( sock < 0, "socket", NULL );
struct hostent* server;
server = gethostbyname(argv[1]);
$( server == NULL, "gethostbyname", "Host %s not found", argv[1] );
struct sockaddr_in srv_address;
memset( (char*) &srv_address, 0, sizeof(srv_address) );
srv_address.sin_family = AF_INET;
strncpy( (char*) &srv_address.sin_addr.s_addr, (char*) server->h_addr_list[0], server->h_length);
srv_address.sin_port = htons(port);
$( connect(sock, &srv_address, sizeof(srv_address)) < 0, "connect", NULL );
char accept_buffer[RKP_BUFFER_SZ];
memset( accept_buffer, 0, RKP_BUFFER_SZ );
printf("Enter message\n");
fgets( accept_buffer, RKP_BUFFER_SZ-1, stdin );
write( sock, accept_buffer, strlen(accept_buffer) );
memset( accept_buffer, 0, RKP_BUFFER_SZ );
read( sock, accept_buffer, RKP_BUFFER_SZ-1 );
printf( "Server answer: %s\n", accept_buffer );
close(sock);
return 0;
}
然后我使用参数127.0.0.1
,localhost
和192.168.0.1
启动服务器和客户端。两个程序都使用端口6662.几秒钟后才开始我有错误:
connect: Connection timed out
我如何解决这个问题?
答案 0 :(得分:1)
参考这一行:
strncpy( (char*) &srv_address.sin_addr.s_addr, (char*) server->h_addr_list[0], server->h_length);
strncpy()
适用于0
- 已终止char
- 数组,C-“字符串”。如果要复制二进制数据,请改用memcpy()
。
memcpy(&srv_address.sin_addr.s_addr, server->h_addr_list[0], server->h_length);
如果不是在Windows或某些旧的UNIX上这行
int ca_len = sizeof(cli_address);
应该是
socklen_t ca_len = sizeof(cli_address);
要确定accept()
的第3个参数是什么类型,请查阅文档。