平台:运行 Ubuntu 的 Odroid N2
我正在尝试从此处的 Unix 套接字示例编译和链接客户端和监听器 - https://opensource.com/article/19/4/interprocess-communication-linux-networking ;代码是:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include "sock.h"
void report(const char* msg, int terminate) {
perror(msg);
if (terminate) exit(-1); /* failure */
}
int main() {
int fd = socket(AF_INET, /* network versus AF_LOCAL */
SOCK_STREAM, /* reliable, bidirectional, arbitrary payload size */
0); /* system picks underlying protocol (TCP) */
if (fd < 0) report("socket", 1); /* terminate */
/* bind the server's local address in memory */
struct sockaddr_in saddr;
memset(&saddr, 0, sizeof(saddr)); /* clear the bytes */
saddr.sin_family = AF_INET; /* versus AF_LOCAL */
saddr.sin_addr.s_addr = htonl(INADDR_ANY); /* host-to-network endian */
saddr.sin_port = htons(PortNumber); /* for listening */
if (bind(fd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0)
report("bind", 1); /* terminate */
/* listen to the socket */
if (listen(fd, MaxConnects) < 0) /* listen for clients, up to MaxConnects */
report("listen", 1); /* terminate */
fprintf(stderr, "Listening on port %i for clients...\n", PortNumber);
/* a server traditionally listens indefinitely */
while (1) {
struct sockaddr_in caddr; /* client address */
int len = sizeof(caddr); /* address length could change */
int client_fd = accept(fd, (struct sockaddr*) &caddr, &len); /* accept blocks */
if (client_fd < 0) {
report("accept", 0); /* don't terminate, though there's a problem */
continue;
}
/* read from client */
int i;
for (i = 0; i < ConversationLen; i++) {
char buffer[BuffSize + 1];
memset(buffer, '\0', sizeof(buffer));
int count = read(client_fd, buffer, sizeof(buffer));
if (count > 0) {
puts(buffer);
write(client_fd, buffer, sizeof(buffer)); /* echo as confirmation */
}
}
close(client_fd); /* break connection */
} /* while(1) */
return 0;
}
我认为必要的头文件应该在系统上,因为作为练习,我在这里从源代码(使用 native 编译过程)重建了 linux - https://wiki.odroid.com/odroid-n2/software/building_kernel ,它已编译、链接并将启动。但是,在尝试编译套接字示例时,我遗漏了一些基本的东西:当我使用
gcc listener.c -o listener
...它给出:
defs.h: No such file or directory
#include <defs.h>
到目前为止我尝试了什么:
我已经安装了 build-essential 和 linux-libc-dev。同样的结果。 作为对像我这样的问题的回答,我找到了安装内核头文件的指南。我试过如下:
- 当我使用
uname -r
时,我得到:4.9.196+ 当我尝试安装特定于该版本的头文件时,如:
sudo apt install linux-headers-$(uname -r)
...我得到:E:无法找到软件包 linux-headers-4.9.196
linux 源代码及其所有包含文件都在/home/odroid/linux 中;所以我想我可以通过这样做来包含这个库:
gcc -I/home/odroid/linux/include listener.c -o listener
但是,当我这样做时,由于类型冲突,它给出了很多错误,并且仍然找不到 defs.h 。
我的路径: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
我错过了什么?
最佳答案
defs.h 似乎不是内核头文件。它包含在示例中;见上面的评论。
关于c - Unix 套接字示例,编译器找不到 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58582947/