~gpanders/iboot

9d2c674cecd98b6464f8f244f32ab4a9cabb6d1e — Greg Anders 3 months ago a7b1e52
Use POSIX compatible socket implementation
3 files changed, 14 insertions(+), 32 deletions(-)

M Makefile
M config.def.h
M iboot.c
M Makefile => Makefile +1 -1
@@ 1,4 1,4 @@
CFLAGS := -Wall -Wpedantic -Os
CFLAGS := -Wall -Wpedantic -Os -std=c99

iboot: iboot.c config.h
	$(CC) $(CFLAGS) -o $@ $<

M config.def.h => config.def.h +1 -1
@@ 1,3 1,3 @@
static const char ADDRESS[]  = "192.168.1.254";
static const char PORT[]     = "80";
static const short PORT      = 80;
static const char PASSWORD[] = "";

M iboot.c => iboot.c +12 -30
@@ 1,4 1,4 @@
#include <netdb.h>
#include <arpa/inet.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>


@@ 27,41 27,23 @@ enum action {

int create_socket()
{
	int sockfd;
	struct addrinfo *result, *rp;
	struct addrinfo hints = {
		.ai_family = AF_INET,
		.ai_socktype = SOCK_STREAM,
		.ai_flags = 0,
		.ai_protocol = 0,
	};

	int s = getaddrinfo(ADDRESS, PORT, &hints, &result);
	if (s != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0) {
		fprintf(stderr, "Failed to create socket\n");
		exit(EXIT_FAILURE);
	}

	for (rp = result; rp != NULL; rp = rp->ai_next) {
		sockfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
		if (sockfd == -1) {
			continue;
		}

		if (connect(sockfd, rp->ai_addr, rp->ai_addrlen) != -1) {
			break;
		}

		close(sockfd);
	}
	struct sockaddr_in addr = {
		.sin_family = AF_INET,
		.sin_port = htons(PORT),
		.sin_addr = { .s_addr = inet_addr(ADDRESS) },
	};

	if (rp == NULL) {
		fprintf(stderr, "Could not connect\n");
	if (connect(sockfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
		fprintf(stderr, "Failed to connect\n");
		exit(EXIT_FAILURE);
	}

	freeaddrinfo(result);

	return sockfd;
}



@@ 121,5 103,5 @@ int main(int argc, char *argv[])
	int sockfd = create_socket();
	send_command(sockfd, action);

	exit(EXIT_SUCCESS);
	return EXIT_SUCCESS;
}