-3

I am a student, I am programming network practical work with the C language, my question is: how can I read MAC address (xx:xx:xx:xx:xx:xx) from the console, and store it in a table, I tried this but it isn't easy to manipulate them after.

Are there any better suggestions?

char MAC[18] = {""};
printf("\n\tEntrez l'@ Mac (XX:XX:XX:XX:XX:XX) en Hex :");
fgets(MAC,sizeof(MAC),stdin); //read MAC
  • You should take this question to a different forum as it directly violates the house rules of StackOverflow. Qu stipend posted here should be about particular problems you are trying to solve with a set of technologies and need help with. – Alla B Dec 27 '15 at 19:11
  • Just about any programming language has tooling for network communications. – David Dec 27 '15 at 19:11
  • C also can be used. ***[Look at this example.](http://stackoverflow.com/a/1779758/645128)*** ***[Or, this one.](http://stackoverflow.com/a/1780367/645128)*** – ryyker Dec 27 '15 at 20:02

1 Answers1

0

You can certainly read the MAC address in hex from the user as shown, except for a small issue: giving fgets a buffer just large enough for the 17 characters and a final '\0' will cause the linefeed typed by the user to stay in the stdin stream. It will be read before any further input, probably not what you would expect.

Furthermore, you want to convert this address into the binary format expected by the socket interface.

Give fgets a larger buffer, and parse with sscanf:

    char line[80];
    unsigned char MAC[6];

    printf("\n\tEntrez l'adresse Mac (XX:XX:XX:XX:XX:XX) en Hexa :");
    if (fgets(line, sizeof(line), stdin)
    &&  sscanf(line, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
               MAC, MAC+1, MAC+2, MAC+3, MAC+4, MAC+5) == 6) {
        // MAC address correctly parsed into MAC[0...5]
    } else {
        // invalid input.
    }
chqrlie
  • 131,814
  • 10
  • 121
  • 189