#Terminal says core dumped when I enter an IP or hex address. Not seeing what is wrong with my code.

1 messages · Page 1 of 1 (latest)

runic sigilBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

ocean gyro
#

Difficult to be 100% sure where '*' starts messing with the format, but best guess this is the correct code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>

void convertToIP(char* input) {
    struct addrinfo hints, *res;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;

    if (getaddrinfo(input, NULL, &hints, &res) == 0) {
        char ip[INET_ADDRSTRLEN];
        struct sockaddr_in* addr = (struct sockaddr_in*)res->ai_addr;
        inet_ntop(AF_INET, &(addr->sin_addr), ip, INET_ADDRSTRLEN);
        printf("IP Address: %s\n", ip);
    } else {
        printf("Invalid input for IP address.\n");
    }

    freeaddrinfo(res);
}

void convertToHex(char input) {
    struct addrinfo hints, *res;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET6;

    if (getaddrinfo(input, NULL, &hints, &res) == 0) {
        char hex[INET6_ADDRSTRLEN];
        struct sockaddr_in6* addr6 = (struct sockaddr_in6 *)res->ai_addr;
        inet_ntop(AF_INET6, &(addr6->sin6_addr), hex, INET6_ADDRSTRLEN);
        printf("Hexadecimal Address: %s\n", hex);
    } else {
        printf("Invalid input for hexadecimal address.\n");
    }

    freeaddrinfo(res);
}

int main() {
    char input[50];

    printf("Enter an IP address or a hexadecimal address: ");
    scanf("%s", input);

    // Check if input is an IP address
    if (getaddrinfo(input, NULL, NULL, NULL) == 0) {
        convertToIP(input);
    }
    // Check if input is a hexadecimal address
    else if (getaddrinfo(input, NULL, NULL, NULL) == 0) {
        convertToHex(input);
    } else {
        printf("Invalid input. Please enter a valid IP address or hexadecimal address.\n");
    }

    return 0;
}
crystal flame
#

I appreciate your help my friend 🤝🏽

ocean gyro
#

As a general rule, I would always (at the very least) assert a pointer before dereferencing it.
Especially if my code did not provide this pointer.

Example:

if (getaddrinfo(input, NULL, &hints, &res) == 0) {
  assert(res != NULL);
  assert(res->ai-addr != NULL);

  ...
}

Requires #include <assert.h>

#

Also, initialise pointers to NULL.