Ich versuche eine kleine Beispielanwendung zu schreiben, um einen TCP-Port zu hören, aber aus irgendeinem Grund funktioniert es nicht.Beim Abhören eines TCP-Ports passiert nichts.
Es scheint zu erreichen accept(3p)
, aber lsof -i :1080
berichtet, dass nichts auf diesen Port hört. Es gibt keine Fehler oder irgendetwas anderes, das entfernt offensichtlich ist.
Irgendwelche Hinweise?
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
const int THREADS = 4;
const int BUFFER_SIZE = 256;
void usage(char *app_name) {
printf("Usage: %s PORT\n", app_name);
}
int main(int argc, char **argv) {
struct sockaddr_in6 serv_addr, addr_cli;
char buffer[BUFFER_SIZE];
int sockfd, sock_cli, n, port;
if (argc < 2) {
usage(argv[0]);
return -1;
}
port = atoi(argv[1]);
if ((sockfd = socket(AF_INET6, SOCK_STREAM, 0)) < 0) {
perror("Could not open socket");
return errno;
}
serv_addr.sin6_family = AF_INET6;
serv_addr.sin6_port = htonl(port);
// other addresses: INADDR_LOOPBACK, INADDR_ANY
serv_addr.sin6_addr = in6addr_any;
serv_addr.sin6_scope_id = 0;
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) != 0) {
perror("Could not bind to socket");
return errno;
}
if (listen(sockfd, THREADS + 1) < 0) {
perror("Could not listen to socket");
return errno;
}
printf("Listening on :%d\n", port);
unsigned long l;
if ((sock_cli = accept(sockfd, (struct sockaddr *) &addr_cli, (socklen_t*) &l)) != 0) {
perror("Could not accept connections on socket");
return errno;
}
printf("Connection accepted\n");
while ((n = recv(sock_cli, buffer, BUFFER_SIZE, 0)) > 0) {
printf("> Got data: %s\n", buffer);
}
if (n < 0) {
printf("Could not receive data\n");
return errno;
}
printf("Bye!\n");
}
htonl (port) sollte htons (port) sein – immibis