There's a dynamic IP address (the public IP of my home) that I'd like to track (i.e., have it as a file on my OpenBSD server). I came up with this simple server:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
int
main(int argc, char *argv[])
{
int socket_desc,
new_socket,
c;
struct sockaddr_in server,
client;
char *message;
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if (socket_desc == -1) {
return 1;
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(1234);
if (bind(socket_desc, (struct sockaddr *) &server, sizeof(server)) < 0) {
return 2;
}
listen(socket_desc, 3);
for (;;) {
c = sizeof(struct sockaddr_in);
new_socket =
accept(socket_desc, (struct sockaddr *) &client,
(socklen_t *) & c);
if (new_socket < 0) {
return 3;
}
int client_port = ntohs(client.sin_port);
char *client_ip = inet_ntoa(client.sin_addr);
for (int i = 0; i < 100; i) {
if (client_ip[i] == 0)
break;
printf("%c", client_ip[i]);
}
printf("\n");
write(new_socket, client_ip, strlen(client_ip));
write(new_socket, "\n", 1);
}
return 0;
}
I developed it on my Raspberry Pi (my main computer), running Raspberry Pi OS Buster (basically Debian GNU/Linux Buster). It compiles well with both gcc(1)
and tcc(1)
. Same on my x86_64 Artix Linux laptop. However, when I tried it on OpenBSD with cc(1)
(which is Clang), I receive:
iplog4.c:14:24: error: variable has incomplete type 'struct sockaddr_in'
struct sockaddr_in server,
^
iplog4.c:14:12: note: forward declaration of 'struct sockaddr_in'
struct sockaddr_in server,
^
iplog4.c:15:21: error: variable has incomplete type 'struct sockaddr_in'
client;
^
iplog4.c:14:12: note: forward declaration of 'struct sockaddr_in'
struct sockaddr_in server,
^
iplog4.c:26:30: error: use of undeclared identifier 'INADDR_ANY'
server.sin_addr.s_addr = INADDR_ANY;
^
iplog4.c:39:13: error: invalid application of 'sizeof' to an incomplete type 'struct sockaddr_in'
c = sizeof(struct sockaddr_in);
^ ~~~~~~~~~~~~~~~~~~~~
iplog4.c:14:12: note: forward declaration of 'struct sockaddr_in'
struct sockaddr_in server,
^
4 errors generated.
CodePudding user response:
You need the following include to make it compile:
#include <netinet/in.h>