get port number from envvar
This commit is contained in:
+50
-1
@@ -1,5 +1,54 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
|
||||
const char *LOCALHOST = "127.0.0.1";
|
||||
|
||||
int read_env_int(const char *var) {
|
||||
const char* port_str = getenv(var);
|
||||
|
||||
if (port_str == NULL) {
|
||||
fprintf(stderr, "error: %s environment variable not set.\n", var);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
char* endptr;
|
||||
long val = strtol(port_str, &endptr, 10);
|
||||
if (endptr == port_str || *endptr != '\0') {
|
||||
fprintf(stderr, "error: invalid number format for %s.\n", var);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
return (int)val;
|
||||
}
|
||||
|
||||
int rcon_connect(int port) {
|
||||
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sockfd < 0) {
|
||||
perror("socket creation failed");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
struct sockaddr_in server_addr;
|
||||
memset(&server_addr, 0, sizeof(server_addr));
|
||||
server_addr.sin_family = AF_INET;
|
||||
server_addr.sin_port = htons(port);
|
||||
inet_pton(AF_INET, LOCALHOST, &server_addr.sin_addr);
|
||||
|
||||
if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
|
||||
perror("connection failed");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
printf("connected to rcon server\n");
|
||||
return sockfd;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
printf("hello");
|
||||
const int PORT_NUM = read_env_int("RCON_PORT_NUMBER");
|
||||
printf("port: %d\n", PORT_NUM);
|
||||
|
||||
rcon_connect(PORT_NUM);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user