我想在同一个套接字上发送和接收数据包,是否可以或者我必须创建两个套接字,一个发送一个接收?如果是的话,你能举个例子吗?
另一个问题:如何从收到的数据包中获取源IP?
编辑(代码示例):
int main(void) {
struct sockaddr_in si_me, si_other;
int s, i, slen=sizeof(si_other);
char buf[BUFLEN];
if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
die("socket");
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(1234);
si_me.sin_addr.s_addr = htonl(192.168.1.1);
if (bind(s, &si_me, sizeof(si_me))==-1)
die("bind");
if (recvfrom(s, buf, BUFLEN, 0, &si_other, &slen)==-1)
diep("recvfrom()");
printf("Data: %s \nReceived from %s:%d\n\n", buf, inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
//now I want the server to answer back to the client
close(s);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我必须检查Linux系统信息。我可以在 C 中执行系统命令,但是这样做我为每个进程创建了一个新进程,这非常昂贵。我想知道是否有一种方法可以在不强制执行 shell 命令的情况下获取系统信息。我已经环顾了一段时间,但什么也没找到。实际上,我什至不确定通过 Bash 从我的 C 程序中调用它们来执行命令还是找到一种仅使用 C 来完成任务的方法更方便。
可以在EOF之后读取文件吗?
我正在读取一个文件,该文件在其结尾或多个EOF字符之前可能包含EOF字符.该文件是一个简单的文本,我能够知道使用fsize的字符数,但看起来像getc从EOF返回到文件末尾的EOF(或-1).
int c = 0;
char x;
FILE *file = fopen("MyTextFile.txt", "r");
off_t size = fsize("MyTextFile.txt");
while (c < size) {
x = getc(file);
if (x != -1)
printf("%c ", x);
else
printf("\nFOUND EOF!\n");
c++;
}
fclose(file);
Run Code Online (Sandbox Code Playgroud)
不幸的是,即使我确定文件内容在EOF之后仍然存在,我无法阅读其余内容.
已解决:使用"rb"而不是"r"进行读取并使用x作为int允许我读取整个文件,包括多个EOF.不确定这是一个技巧还是允许的东西,但是有效.